difftreelog
chore add Fractionalizer contract documentation, prevent QTZ/UNQ transfers from nonowners, tests for TransfersNotAllowed
in: master
3 files changed
pallets/refungible/src/erc_token.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet EVM API for token pieces18//!19//! Provides ERC-20 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;2324#[cfg(not(feature = "std"))]25use alloc::format;2627use core::{28 char::{REPLACEMENT_CHARACTER, decode_utf16},29 convert::TryInto,30 ops::Deref,31};32use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};33use pallet_common::{34 CommonWeightInfo,35 erc::{CommonEvmHandler, PrecompileResult, static_property::key},36 eth::map_eth_to_id,37};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};39use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};41use sp_core::H160;42use sp_std::vec::Vec;43use up_data_structs::{mapping::TokenAddressMapping, PropertyScope, TokenId};4445use crate::{46 Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,47 TokenProperties, TotalSupply, weights::WeightInfo,48};4950pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);5152#[solidity_interface(name = "ERC1633")]53impl<T: Config> RefungibleTokenHandle<T> {54 fn parent_token(&self) -> Result<address> {55 self.consume_store_reads(2)?;56 let props = <TokenProperties<T>>::get((self.id, self.1));57 let key = key::parent_nft();5859 let key_scoped = PropertyScope::Eth60 .apply(key)61 .expect("property key shouldn't exceed length limit");62 if let Some(value) = props.get(&key_scoped) {63 Ok(H160::from_slice(value.as_slice()))64 } else {65 Ok(*T::CrossTokenAddressMapping::token_to_address(self.id, self.1).as_eth())66 }67 }6869 fn parent_token_id(&self) -> Result<uint256> {70 self.consume_store_reads(2)?;71 let props = <TokenProperties<T>>::get((self.id, self.1));72 let key = key::parent_nft();7374 let key_scoped = PropertyScope::Eth75 .apply(key)76 .expect("property key shouldn't exceed length limit");77 if let Some(value) = props.get(&key_scoped) {78 let nft_token_address = H160::from_slice(value.as_slice());79 let nft_token_account = T::CrossAccountId::from_eth(nft_token_address);80 let (_, token_id) = T::CrossTokenAddressMapping::address_to_token(&nft_token_account)81 .ok_or("parent NFT should contain NFT token address")?;8283 Ok(token_id.into())84 } else {85 Ok(self.1.into())86 }87 }88}8990#[solidity_interface(name = "ERC1633UniqueExtensions")]91impl<T: Config> RefungibleTokenHandle<T> {92 #[solidity(rename_selector = "setParentNFT")]93 #[weight(<CommonWeights<T>>::token_owner() + <SelfWeightOf<T>>::set_parent_nft_unchecked())]94 fn set_parent_nft(95 &mut self,96 caller: caller,97 collection: address,98 nft_id: uint256,99 ) -> Result<bool> {100 self.consume_store_reads(1)?;101 let caller = T::CrossAccountId::from_eth(caller);102 let nft_collection = map_eth_to_id(&collection).ok_or("collection not found")?;103 let nft_token = nft_id.try_into()?;104105 <Pallet<T>>::set_parent_nft(&self.0, self.1, caller, nft_collection, nft_token)106 .map_err(dispatch_to_evm::<T>)?;107108 Ok(true)109 }110}111112#[derive(ToLog)]113pub enum ERC20Events {114 /// @dev This event is emitted when the amount of tokens (value) is sent115 /// from the from address to the to address. In the case of minting new116 /// tokens, the transfer is usually from the 0 address while in the case117 /// of burning tokens the transfer is to 0.118 Transfer {119 #[indexed]120 from: address,121 #[indexed]122 to: address,123 value: uint256,124 },125 /// @dev This event is emitted when the amount of tokens (value) is approved126 /// by the owner to be used by the spender.127 Approval {128 #[indexed]129 owner: address,130 #[indexed]131 spender: address,132 value: uint256,133 },134}135136/// @title Standard ERC20 token137///138/// @dev Implementation of the basic standard token.139/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md140#[solidity_interface(name = "ERC20", events(ERC20Events))]141impl<T: Config> RefungibleTokenHandle<T> {142 /// @return the name of the token.143 fn name(&self) -> Result<string> {144 Ok(decode_utf16(self.name.iter().copied())145 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))146 .collect::<string>())147 }148149 /// @return the symbol of the token.150 fn symbol(&self) -> Result<string> {151 Ok(string::from_utf8_lossy(&self.token_prefix).into())152 }153154 /// @dev Total number of tokens in existence155 fn total_supply(&self) -> Result<uint256> {156 self.consume_store_reads(1)?;157 Ok(<TotalSupply<T>>::get((self.id, self.1)).into())158 }159160 /// @dev Not supported161 fn decimals(&self) -> Result<uint8> {162 // Decimals aren't supported for refungible tokens163 Ok(0)164 }165166 /// @dev Gets the balance of the specified address.167 /// @param owner The address to query the balance of.168 /// @return An uint256 representing the amount owned by the passed address.169 fn balance_of(&self, owner: address) -> Result<uint256> {170 self.consume_store_reads(1)?;171 let owner = T::CrossAccountId::from_eth(owner);172 let balance = <Balance<T>>::get((self.id, self.1, owner));173 Ok(balance.into())174 }175176 /// @dev Transfer token for a specified address177 /// @param to The address to transfer to.178 /// @param amount The amount to be transferred.179 #[weight(<CommonWeights<T>>::transfer())]180 fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {181 let caller = T::CrossAccountId::from_eth(caller);182 let to = T::CrossAccountId::from_eth(to);183 let amount = amount.try_into().map_err(|_| "amount overflow")?;184 let budget = self185 .recorder186 .weight_calls_budget(<StructureWeight<T>>::find_parent());187188 <Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)189 .map_err(|_| "transfer error")?;190 Ok(true)191 }192193 /// @dev Transfer tokens from one address to another194 /// @param from address The address which you want to send tokens from195 /// @param to address The address which you want to transfer to196 /// @param amount uint256 the amount of tokens to be transferred197 #[weight(<CommonWeights<T>>::transfer_from())]198 fn transfer_from(199 &mut self,200 caller: caller,201 from: address,202 to: address,203 amount: uint256,204 ) -> Result<bool> {205 let caller = T::CrossAccountId::from_eth(caller);206 let from = T::CrossAccountId::from_eth(from);207 let to = T::CrossAccountId::from_eth(to);208 let amount = amount.try_into().map_err(|_| "amount overflow")?;209 let budget = self210 .recorder211 .weight_calls_budget(<StructureWeight<T>>::find_parent());212213 <Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)214 .map_err(dispatch_to_evm::<T>)?;215 Ok(true)216 }217218 /// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.219 /// Beware that changing an allowance with this method brings the risk that someone may use both the old220 /// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this221 /// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:222 /// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729223 /// @param spender The address which will spend the funds.224 /// @param amount The amount of tokens to be spent.225 #[weight(<SelfWeightOf<T>>::approve())]226 fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {227 let caller = T::CrossAccountId::from_eth(caller);228 let spender = T::CrossAccountId::from_eth(spender);229 let amount = amount.try_into().map_err(|_| "amount overflow")?;230231 <Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)232 .map_err(dispatch_to_evm::<T>)?;233 Ok(true)234 }235236 /// @dev Function to check the amount of tokens that an owner allowed to a spender.237 /// @param owner address The address which owns the funds.238 /// @param spender address The address which will spend the funds.239 /// @return A uint256 specifying the amount of tokens still available for the spender.240 fn allowance(&self, owner: address, spender: address) -> Result<uint256> {241 self.consume_store_reads(1)?;242 let owner = T::CrossAccountId::from_eth(owner);243 let spender = T::CrossAccountId::from_eth(spender);244245 Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())246 }247}248249#[solidity_interface(name = "ERC20UniqueExtensions")]250impl<T: Config> RefungibleTokenHandle<T> {251 /// @dev Function that burns an amount of the token of a given account,252 /// deducting from the sender's allowance for said account.253 /// @param from The account whose tokens will be burnt.254 /// @param amount The amount that will be burnt.255 #[weight(<SelfWeightOf<T>>::burn_from())]256 fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {257 let caller = T::CrossAccountId::from_eth(caller);258 let from = T::CrossAccountId::from_eth(from);259 let amount = amount.try_into().map_err(|_| "amount overflow")?;260 let budget = self261 .recorder262 .weight_calls_budget(<StructureWeight<T>>::find_parent());263264 <Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)265 .map_err(dispatch_to_evm::<T>)?;266 Ok(true)267 }268269 /// @dev Function that changes total amount of the tokens.270 /// Throws if `msg.sender` doesn't owns all of the tokens.271 /// @param amount New total amount of the tokens.272 #[weight(<SelfWeightOf<T>>::repartition_item())]273 fn repartition(&mut self, caller: caller, amount: uint256) -> Result<bool> {274 let caller = T::CrossAccountId::from_eth(caller);275 let amount = amount.try_into().map_err(|_| "amount overflow")?;276277 <Pallet<T>>::repartition(self, &caller, self.1, amount).map_err(dispatch_to_evm::<T>)?;278 Ok(true)279 }280}281282impl<T: Config> RefungibleTokenHandle<T> {283 pub fn into_inner(self) -> RefungibleHandle<T> {284 self.0285 }286 pub fn common_mut(&mut self) -> &mut RefungibleHandle<T> {287 &mut self.0288 }289}290291impl<T: Config> WithRecorder<T> for RefungibleTokenHandle<T> {292 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {293 self.0.recorder()294 }295 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {296 self.0.into_recorder()297 }298}299300impl<T: Config> Deref for RefungibleTokenHandle<T> {301 type Target = RefungibleHandle<T>;302303 fn deref(&self) -> &Self::Target {304 &self.0305 }306}307308#[solidity_interface(309 name = "UniqueRefungibleToken",310 is(ERC20, ERC20UniqueExtensions, ERC1633, ERC1633UniqueExtensions)311)]312impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}313314generate_stubgen!(gen_impl, UniqueRefungibleTokenCall<()>, true);315generate_stubgen!(gen_iface, UniqueRefungibleTokenCall<()>, false);316317impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T>318where319 T::AccountId: From<[u8; 32]>,320{321 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");322323 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {324 call::<T, UniqueRefungibleTokenCall<T>, _, _>(handle, self)325 }326}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet EVM API for token pieces18//!19//! Provides ERC-20 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;2324#[cfg(not(feature = "std"))]25use alloc::format;2627use core::{28 char::{REPLACEMENT_CHARACTER, decode_utf16},29 convert::TryInto,30 ops::Deref,31};32use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};33use pallet_common::{34 CommonWeightInfo,35 erc::{CommonEvmHandler, PrecompileResult, static_property::key},36 eth::map_eth_to_id,37};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};39use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};41use sp_core::H160;42use sp_std::vec::Vec;43use up_data_structs::{mapping::TokenAddressMapping, PropertyScope, TokenId};4445use crate::{46 Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,47 TokenProperties, TotalSupply, weights::WeightInfo,48};4950pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);5152#[solidity_interface(name = "ERC1633")]53impl<T: Config> RefungibleTokenHandle<T> {54 fn parent_token(&self) -> Result<address> {55 self.consume_store_reads(2)?;56 let props = <TokenProperties<T>>::get((self.id, self.1));57 let key = key::parent_nft();5859 let key_scoped = PropertyScope::Eth60 .apply(key)61 .expect("property key shouldn't exceed length limit");62 if let Some(value) = props.get(&key_scoped) {63 Ok(H160::from_slice(value.as_slice()))64 } else {65 Ok(*T::CrossTokenAddressMapping::token_to_address(self.id, self.1).as_eth())66 }67 }6869 fn parent_token_id(&self) -> Result<uint256> {70 self.consume_store_reads(2)?;71 let props = <TokenProperties<T>>::get((self.id, self.1));72 let key = key::parent_nft();7374 let key_scoped = PropertyScope::Eth75 .apply(key)76 .expect("property key shouldn't exceed length limit");77 if let Some(value) = props.get(&key_scoped) {78 let nft_token_address = H160::from_slice(value.as_slice());79 let nft_token_account = T::CrossAccountId::from_eth(nft_token_address);80 let (_, token_id) = T::CrossTokenAddressMapping::address_to_token(&nft_token_account)81 .ok_or("parent NFT should contain NFT token address")?;8283 Ok(token_id.into())84 } else {85 Ok(self.1.into())86 }87 }88}8990#[solidity_interface(name = "ERC1633UniqueExtensions")]91impl<T: Config> RefungibleTokenHandle<T> {92 #[solidity(rename_selector = "setParentNFT")]93 #[weight(<CommonWeights<T>>::token_owner() + <SelfWeightOf<T>>::set_parent_nft_unchecked())]94 fn set_parent_nft(95 &mut self,96 caller: caller,97 collection: address,98 nft_id: uint256,99 ) -> Result<bool> {100 self.consume_store_reads(1)?;101 let caller = T::CrossAccountId::from_eth(caller);102 let nft_collection = map_eth_to_id(&collection).ok_or("collection not found")?;103 let nft_token = nft_id.try_into()?;104105 <Pallet<T>>::set_parent_nft(&self.0, self.1, caller, nft_collection, nft_token)106 .map_err(dispatch_to_evm::<T>)?;107108 Ok(true)109 }110}111112#[derive(ToLog)]113pub enum ERC20Events {114 /// @dev This event is emitted when the amount of tokens (value) is sent115 /// from the from address to the to address. In the case of minting new116 /// tokens, the transfer is usually from the 0 address while in the case117 /// of burning tokens the transfer is to 0.118 Transfer {119 #[indexed]120 from: address,121 #[indexed]122 to: address,123 value: uint256,124 },125 /// @dev This event is emitted when the amount of tokens (value) is approved126 /// by the owner to be used by the spender.127 Approval {128 #[indexed]129 owner: address,130 #[indexed]131 spender: address,132 value: uint256,133 },134}135136/// @title Standard ERC20 token137///138/// @dev Implementation of the basic standard token.139/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md140#[solidity_interface(name = "ERC20", events(ERC20Events))]141impl<T: Config> RefungibleTokenHandle<T> {142 /// @return the name of the token.143 fn name(&self) -> Result<string> {144 Ok(decode_utf16(self.name.iter().copied())145 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))146 .collect::<string>())147 }148149 /// @return the symbol of the token.150 fn symbol(&self) -> Result<string> {151 Ok(string::from_utf8_lossy(&self.token_prefix).into())152 }153154 /// @dev Total number of tokens in existence155 fn total_supply(&self) -> Result<uint256> {156 self.consume_store_reads(1)?;157 Ok(<TotalSupply<T>>::get((self.id, self.1)).into())158 }159160 /// @dev Not supported161 fn decimals(&self) -> Result<uint8> {162 // Decimals aren't supported for refungible tokens163 Ok(0)164 }165166 /// @dev Gets the balance of the specified address.167 /// @param owner The address to query the balance of.168 /// @return An uint256 representing the amount owned by the passed address.169 fn balance_of(&self, owner: address) -> Result<uint256> {170 self.consume_store_reads(1)?;171 let owner = T::CrossAccountId::from_eth(owner);172 let balance = <Balance<T>>::get((self.id, self.1, owner));173 Ok(balance.into())174 }175176 /// @dev Transfer token for a specified address177 /// @param to The address to transfer to.178 /// @param amount The amount to be transferred.179 #[weight(<CommonWeights<T>>::transfer())]180 fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {181 let caller = T::CrossAccountId::from_eth(caller);182 let to = T::CrossAccountId::from_eth(to);183 let amount = amount.try_into().map_err(|_| "amount overflow")?;184 let budget = self185 .recorder186 .weight_calls_budget(<StructureWeight<T>>::find_parent());187188 <Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)189 .map_err(dispatch_to_evm::<T>)?;190 Ok(true)191 }192193 /// @dev Transfer tokens from one address to another194 /// @param from address The address which you want to send tokens from195 /// @param to address The address which you want to transfer to196 /// @param amount uint256 the amount of tokens to be transferred197 #[weight(<CommonWeights<T>>::transfer_from())]198 fn transfer_from(199 &mut self,200 caller: caller,201 from: address,202 to: address,203 amount: uint256,204 ) -> Result<bool> {205 let caller = T::CrossAccountId::from_eth(caller);206 let from = T::CrossAccountId::from_eth(from);207 let to = T::CrossAccountId::from_eth(to);208 let amount = amount.try_into().map_err(|_| "amount overflow")?;209 let budget = self210 .recorder211 .weight_calls_budget(<StructureWeight<T>>::find_parent());212213 <Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)214 .map_err(dispatch_to_evm::<T>)?;215 Ok(true)216 }217218 /// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.219 /// Beware that changing an allowance with this method brings the risk that someone may use both the old220 /// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this221 /// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:222 /// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729223 /// @param spender The address which will spend the funds.224 /// @param amount The amount of tokens to be spent.225 #[weight(<SelfWeightOf<T>>::approve())]226 fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {227 let caller = T::CrossAccountId::from_eth(caller);228 let spender = T::CrossAccountId::from_eth(spender);229 let amount = amount.try_into().map_err(|_| "amount overflow")?;230231 <Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)232 .map_err(dispatch_to_evm::<T>)?;233 Ok(true)234 }235236 /// @dev Function to check the amount of tokens that an owner allowed to a spender.237 /// @param owner address The address which owns the funds.238 /// @param spender address The address which will spend the funds.239 /// @return A uint256 specifying the amount of tokens still available for the spender.240 fn allowance(&self, owner: address, spender: address) -> Result<uint256> {241 self.consume_store_reads(1)?;242 let owner = T::CrossAccountId::from_eth(owner);243 let spender = T::CrossAccountId::from_eth(spender);244245 Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())246 }247}248249#[solidity_interface(name = "ERC20UniqueExtensions")]250impl<T: Config> RefungibleTokenHandle<T> {251 /// @dev Function that burns an amount of the token of a given account,252 /// deducting from the sender's allowance for said account.253 /// @param from The account whose tokens will be burnt.254 /// @param amount The amount that will be burnt.255 #[weight(<SelfWeightOf<T>>::burn_from())]256 fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {257 let caller = T::CrossAccountId::from_eth(caller);258 let from = T::CrossAccountId::from_eth(from);259 let amount = amount.try_into().map_err(|_| "amount overflow")?;260 let budget = self261 .recorder262 .weight_calls_budget(<StructureWeight<T>>::find_parent());263264 <Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)265 .map_err(dispatch_to_evm::<T>)?;266 Ok(true)267 }268269 /// @dev Function that changes total amount of the tokens.270 /// Throws if `msg.sender` doesn't owns all of the tokens.271 /// @param amount New total amount of the tokens.272 #[weight(<SelfWeightOf<T>>::repartition_item())]273 fn repartition(&mut self, caller: caller, amount: uint256) -> Result<bool> {274 let caller = T::CrossAccountId::from_eth(caller);275 let amount = amount.try_into().map_err(|_| "amount overflow")?;276277 <Pallet<T>>::repartition(self, &caller, self.1, amount).map_err(dispatch_to_evm::<T>)?;278 Ok(true)279 }280}281282impl<T: Config> RefungibleTokenHandle<T> {283 pub fn into_inner(self) -> RefungibleHandle<T> {284 self.0285 }286 pub fn common_mut(&mut self) -> &mut RefungibleHandle<T> {287 &mut self.0288 }289}290291impl<T: Config> WithRecorder<T> for RefungibleTokenHandle<T> {292 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {293 self.0.recorder()294 }295 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {296 self.0.into_recorder()297 }298}299300impl<T: Config> Deref for RefungibleTokenHandle<T> {301 type Target = RefungibleHandle<T>;302303 fn deref(&self) -> &Self::Target {304 &self.0305 }306}307308#[solidity_interface(309 name = "UniqueRefungibleToken",310 is(ERC20, ERC20UniqueExtensions, ERC1633, ERC1633UniqueExtensions)311)]312impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}313314generate_stubgen!(gen_impl, UniqueRefungibleTokenCall<()>, true);315generate_stubgen!(gen_iface, UniqueRefungibleTokenCall<()>, false);316317impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T>318where319 T::AccountId: From<[u8; 32]>,320{321 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");322323 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {324 call::<T, UniqueRefungibleTokenCall<T>, _, _>(handle, self)325 }326}tests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth--- a/tests/src/eth/fractionalizer/Fractionalizer.sol
+++ b/tests/src/eth/fractionalizer/Fractionalizer.sol
@@ -6,6 +6,9 @@
import {UniqueRefungible} from "../api/UniqueRefungible.sol";
import {UniqueNFT} from "../api/UniqueNFT.sol";
+/// @dev Fractionalization contract. It stores mappings between NFT and RFT tokens,
+/// stores allowlist of NFT tokens available for fractionalization, has methods
+/// for fractionalization and defractionalization of NFT tokens.
contract Fractionalizer {
struct Token {
address _collection;
@@ -17,9 +20,10 @@
mapping(address => Token) rft2nftMapping;
bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));
- constructor() {
- }
+ //TODO: add nonPayable modifier after Solidity updates to 0.9.
+ receive() external payable onlyOwner {}
+ /// @dev Method modifier to only allow contract owner to call it.
modifier onlyOwner() {
address contracthelpersAddress = 0x842899ECF380553E8a4de75bF534cdf6fBF64049;
ContractHelpers contractHelpers = ContractHelpers(contracthelpersAddress);
@@ -28,11 +32,26 @@
_;
}
+ /// @dev This emits when RFT collection setting is changed.
event RFTCollectionSet(address _collection);
+
+ /// @dev This emits when NFT collection is allowed or disallowed.
event AllowListSet(address _collection, bool _status);
+
+ /// @dev This emits when NFT token is fractionalized by contract.
event Fractionalized(address _collection, uint256 _tokenId, address _rftToken, uint128 _amount);
+
+ /// @dev This emits when NFT token is defractionalized by contract.
event Defractionalized(address _rftToken, address _nftCollection, uint256 _nftTokenId);
+ /// Set RFT collection that contract will work with. RFT tokens for fractionalized NFT tokens
+ /// would be created in this collection.
+ /// @dev Throws if RFT collection is already configured for this contract.
+ /// Throws if collection of wrong type (NFT, Fungible) is provided instead
+ /// of RFT collection.
+ /// Throws if `msg.sender` is not owner or admin of provided RFT collection.
+ /// Can only be called by contract owner.
+ /// @param _collection address of RFT collection.
function setRFTCollection(address _collection) public onlyOwner {
require(
rftCollection == address(0),
@@ -53,6 +72,13 @@
emit RFTCollectionSet(rftCollection);
}
+ /// Creates and sets RFT collection that contract will work with. RFT tokens for fractionalized NFT tokens
+ /// would be created in this collection.
+ /// @dev Throws if RFT collection is already configured for this contract.
+ /// Can only be called by contract owner.
+ /// @param _name name for created RFT collection.
+ /// @param _description description for created RFT collection.
+ /// @param _tokenPrefix token prefix for created RFT collection.
function createAndSetRFTCollection(string calldata _name, string calldata _description, string calldata _tokenPrefix) public onlyOwner {
require(
rftCollection == address(0),
@@ -63,11 +89,25 @@
emit RFTCollectionSet(rftCollection);
}
+ /// Allow or disallow NFT collection tokens from being fractionalized by this contract.
+ /// @dev Can only be called by contract owner.
+ /// @param collection NFT token address.
+ /// @param status `true` to allow and `false` to disallow NFT token.
function setNftCollectionIsAllowed(address collection, bool status) public onlyOwner {
nftCollectionAllowList[collection] = status;
emit AllowListSet(collection, status);
}
+ /// Fractionilize NFT token.
+ /// @dev Takes NFT token from `msg.sender` and transfers RFT token to `msg.sender`
+ /// instead. Creates new RFT token if provided NFT token never was fractionalized
+ /// by this contract or existing RFT token if it was.
+ /// Throws if RFT collection isn't configured for this contract.
+ /// Throws if fractionalization of provided NFT token is not allowed
+ /// Throws if `msg.sender` is not owner of provided NFT token
+ /// @param _collection NFT collection address
+ /// @param _token id of NFT token to be fractionalized
+ /// @param _pieces number of pieces new RFT token would have
function nft2rft(address _collection, uint256 _token, uint128 _pieces) public {
require(
rftCollection != address(0),
@@ -109,6 +149,15 @@
emit Fractionalized(_collection, _token, rftTokenAddress, _pieces);
}
+ /// Defrationalize NFT token.
+ /// @dev Takes RFT token from `msg.sender` and transfers corresponding NFT token
+ /// to `msg.sender` instead.
+ /// Throws if RFT collection isn't configured for this contract.
+ /// Throws if provided RFT token is no from configured RFT collection.
+ /// Throws if RFT token was not created by this contract.
+ /// Throws if `msg.sender` isn't owner of all RFT token pieces.
+ /// @param _collection RFT collection address
+ /// @param _token id of RFT token
function rft2nft(address _collection, uint256 _token) public {
require(
rftCollection != address(0),
tests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth--- a/tests/src/eth/fractionalizer/fractionalizer.test.ts
+++ b/tests/src/eth/fractionalizer/fractionalizer.test.ts
@@ -19,17 +19,15 @@
import {ApiPromise} from '@polkadot/api';
import {evmToAddress} from '@polkadot/util-crypto';
import {readFile} from 'fs/promises';
-import {submitTransactionAsync} from '../../substrate/substrate-api';
-import {UNIQUE} from '../../util/helpers';
+import {executeTransaction, submitTransactionAsync} from '../../substrate/substrate-api';
+import {getCreateCollectionResult, getCreateItemResult, UNIQUE} from '../../util/helpers';
import {collectionIdToAddress, CompiledContract, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, GAS_ARGS, itWeb3, tokenIdFromAddress, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from '../util/helpers';
import {Contract} from 'web3-eth-contract';
import * as solc from 'solc';
import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
import chaiLike from 'chai-like';
import {IKeyringPair} from '@polkadot/types/types';
-chai.use(chaiAsPromised);
chai.use(chaiLike);
const expect = chai.expect;
let fractionalizer: CompiledContract;
@@ -93,9 +91,8 @@
async function initFractionalizer(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair, owner: string) {
const fractionalizer = await deployFractionalizer(web3, owner);
- const tx = api.tx.balances.transfer(evmToAddress(fractionalizer.options.address), 10n * UNIQUE);
- const alice = privateKeyWrapper('//Alice');
- await submitTransactionAsync(alice, tx);
+ const amount = 10n * UNIQUE;
+ await web3.eth.sendTransaction({from: owner, to: fractionalizer.options.address, value: `${amount}`, ...GAS_ARGS});
const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send();
const rftCollectionAddress = result.events.RFTCollectionSet.returnValues._collection;
return {fractionalizer, rftCollectionAddress};
@@ -151,8 +148,7 @@
itWeb3('Set Allowlist', async ({api, web3, privateKeyWrapper}) => {
const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
-
+ const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
const result1 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send({from: owner});
expect(result1.events).to.be.like({
@@ -238,7 +234,7 @@
await fractionalizer.methods.setRFTCollection(collectionIdAddress).send();
await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())
- .to.eventually.be.rejectedWith(/RFT collection is already set$/g);
+ .to.be.rejectedWith(/RFT collection is already set$/g);
});
itWeb3('call setRFTCollection with NFT collection', async ({api, web3, privateKeyWrapper}) => {
@@ -250,7 +246,7 @@
await nftContract.methods.addCollectionAdmin(fractionalizer.options.address).send();
await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())
- .to.eventually.be.rejectedWith(/Wrong collection type. Collection is not refungible.$/g);
+ .to.be.rejectedWith(/Wrong collection type. Collection is not refungible.$/g);
});
itWeb3('call setRFTCollection while not collection admin', async ({api, web3, privateKeyWrapper}) => {
@@ -259,7 +255,7 @@
const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);
await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())
- .to.eventually.be.rejectedWith(/Fractionalizer contract should be an admin of the collection$/g);
+ .to.be.rejectedWith(/Fractionalizer contract should be an admin of the collection$/g);
});
itWeb3('call setRFTCollection after createAndSetRFTCollection', async ({api, web3, privateKeyWrapper}) => {
@@ -273,7 +269,7 @@
const collectionIdAddress = result.events.RFTCollectionSet.returnValues._collection;
await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())
- .to.eventually.be.rejectedWith(/RFT collection is already set$/g);
+ .to.be.rejectedWith(/RFT collection is already set$/g);
});
itWeb3('call nft2rft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {
@@ -287,7 +283,7 @@
const fractionalizer = await deployFractionalizer(web3, owner);
await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())
- .to.eventually.be.rejectedWith(/RFT collection is not set$/g);
+ .to.be.rejectedWith(/RFT collection is not set$/g);
});
itWeb3('call nft2rft while not owner of NFT token', async ({api, web3, privateKeyWrapper}) => {
@@ -305,7 +301,7 @@
await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();
await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())
- .to.eventually.be.rejectedWith(/Only token owner could fractionalize it$/g);
+ .to.be.rejectedWith(/Only token owner could fractionalize it$/g);
});
itWeb3('call nft2rft while not in list of allowed accounts', async ({api, web3, privateKeyWrapper}) => {
@@ -320,7 +316,7 @@
await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();
await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())
- .to.eventually.be.rejectedWith(/Fractionalization of this collection is not allowed by admin$/g);
+ .to.be.rejectedWith(/Fractionalization of this collection is not allowed by admin$/g);
});
itWeb3('call nft2rft while fractionalizer doesnt have approval for nft token', async ({api, web3, privateKeyWrapper}) => {
@@ -335,7 +331,7 @@
await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();
await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())
- .to.eventually.be.rejectedWith(/ApprovedValueTooLow$/g);
+ .to.be.rejectedWith(/ApprovedValueTooLow$/g);
});
itWeb3('call rft2nft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {
@@ -348,7 +344,7 @@
await refungibleContract.methods.mint(owner, rftTokenId).send();
await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())
- .to.eventually.be.rejectedWith(/RFT collection is not set$/g);
+ .to.be.rejectedWith(/RFT collection is not set$/g);
});
itWeb3('call rft2nft for RFT token that is not from configured RFT collection', async ({api, web3, privateKeyWrapper}) => {
@@ -361,7 +357,7 @@
await refungibleContract.methods.mint(owner, rftTokenId).send();
await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())
- .to.eventually.be.rejectedWith(/Wrong RFT collection$/g);
+ .to.be.rejectedWith(/Wrong RFT collection$/g);
});
itWeb3('call rft2nft for RFT token that was not minted by fractionalizer contract', async ({api, web3, privateKeyWrapper}) => {
@@ -378,7 +374,7 @@
await refungibleContract.methods.mint(owner, rftTokenId).send();
await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())
- .to.eventually.be.rejectedWith(/No corresponding NFT token found$/g);
+ .to.be.rejectedWith(/No corresponding NFT token found$/g);
});
itWeb3('call rft2nft without owning all RFT pieces', async ({api, web3, privateKeyWrapper}) => {
@@ -393,6 +389,82 @@
await refungibleTokenContract.methods.transfer(receiver, 50).send();
await refungibleTokenContract.methods.approve(fractionalizer.options.address, 50).send();
await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, tokenId).call())
- .to.eventually.be.rejectedWith(/Not all pieces are owned by the caller$/g);
+ .to.be.rejectedWith(/Not all pieces are owned by the caller$/g);
+ });
+
+ itWeb3('send QTZ/UNQ to contract from non owner', async ({api, web3, privateKeyWrapper}) => {
+ const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ const payer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+ const fractionalizer = await deployFractionalizer(web3, owner);
+ const amount = 10n * UNIQUE;
+ await expect(web3.eth.sendTransaction({from: payer, to: fractionalizer.options.address, value: `${amount}`, ...GAS_ARGS})).to.be.rejected;
+ });
+
+ itWeb3('fractionalize NFT with NFT transfers disallowed', async ({api, web3, privateKeyWrapper}) => {
+ const alice = privateKeyWrapper('//Alice');
+ let collectionId;
+ {
+ const tx = api.tx.unique.createCollectionEx({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getCreateCollectionResult(events);
+ collectionId = result.collectionId;
+ }
+ const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ let nftTokenId;
+ {
+ const createData = {nft: {}};
+ const tx = api.tx.unique.createItem(collectionId, {Ethereum: owner}, createData as any);
+ const events = await executeTransaction(api, alice, tx);
+ const result = getCreateItemResult(events);
+ nftTokenId = result.itemId;
+ }
+ {
+ const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, false);
+ await executeTransaction(api, alice, tx);
+ }
+ const nftCollectionAddress = collectionIdToAddress(collectionId);
+ const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+ await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();
+
+ const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+ await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();
+ await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())
+ .to.be.rejectedWith(/TransferNotAllowed$/g);
+ });
+
+ itWeb3('fractionalize NFT with RFT transfers disallowed', async ({api, web3, privateKeyWrapper}) => {
+ const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ const alice = privateKeyWrapper('//Alice');
+
+ let collectionId;
+ {
+ const tx = api.tx.unique.createCollectionEx({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'ReFungible'});
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getCreateCollectionResult(events);
+ collectionId = result.collectionId;
+ }
+ const rftCollectionAddress = collectionIdToAddress(collectionId);
+ const fractionalizer = await deployFractionalizer(web3, owner);
+ {
+ const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: fractionalizer.options.address});
+ await submitTransactionAsync(alice, changeAdminTx);
+ }
+ await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send();
+ {
+ const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, false);
+ await executeTransaction(api, alice, tx);
+ }
+
+ const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
+ const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+ const nftTokenId = await nftContract.methods.nextTokenId().call();
+ await nftContract.methods.mint(owner, nftTokenId).send();
+
+ await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();
+ await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();
+
+ await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100n).call())
+ .to.be.rejectedWith(/TransferNotAllowed$/g);
});
});
\ No newline at end of file