difftreelog
Merge pull request #542 from UniqueNetwork/fix/RFT_and_fractionalizer
in: master
14 files changed
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth281 let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;281 let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;282 }: {<Pallet<T>>::repartition(&collection, &owner, item, 200)?}282 }: {<Pallet<T>>::repartition(&collection, &owner, item, 200)?}283284 set_parent_nft_unchecked {285 bench_init!{286 owner: sub; collection: collection(owner);287 sender: cross_from_sub(owner); owner: cross_sub;288 };289 let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;290291 }: {<Pallet<T>>::set_parent_nft_unchecked(&collection, item, owner, T::CrossAccountId::from_eth(H160::default()))?}292283293 token_owner {284 token_owner {294 bench_init!{285 bench_init!{pallets/refungible/src/erc_token.rsdiffbeforeafterboth29 convert::TryInto,29 convert::TryInto,30 ops::Deref,30 ops::Deref,31};31};32use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};32use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};33use pallet_common::{33use pallet_common::{34 CommonWeightInfo,34 CommonWeightInfo,35 erc::{CommonEvmHandler, PrecompileResult, static_property::key},35 erc::{CommonEvmHandler, PrecompileResult},36 eth::map_eth_to_id,36 eth::collection_id_to_address,37};37};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};39use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};39use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};41use sp_core::H160;42use sp_std::vec::Vec;41use sp_std::vec::Vec;43use up_data_structs::{mapping::TokenAddressMapping, PropertyScope, TokenId};42use up_data_structs::TokenId;444345use crate::{44use crate::{46 Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,45 Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,47 TokenProperties, TotalSupply, weights::WeightInfo,46 TotalSupply, weights::WeightInfo,48};47};494850pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);49pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);515052#[solidity_interface(name = ERC1633)]51#[solidity_interface(name = ERC1633)]53impl<T: Config> RefungibleTokenHandle<T> {52impl<T: Config> RefungibleTokenHandle<T> {54 fn parent_token(&self) -> Result<address> {53 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()))54 Ok(collection_id_to_address(self.id))64 } else {65 Ok(*T::CrossTokenAddressMapping::token_to_address(self.id, self.1).as_eth())66 }67 }55 }685669 fn parent_token_id(&self) -> Result<uint256> {57 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())58 Ok(self.1.into())86 }87 }59 }88}60}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}11161112#[derive(ToLog)]62#[derive(ToLog)]113pub enum ERC20Events {63pub enum ERC20Events {307257308#[solidity_interface(258#[solidity_interface(309 name = UniqueRefungibleToken,259 name = UniqueRefungibleToken,310 is(ERC20, ERC20UniqueExtensions, ERC1633, ERC1633UniqueExtensions)260 is(ERC20, ERC20UniqueExtensions, ERC1633)311)]261)]312impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}262impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}313263pallets/refungible/src/lib.rsdiffbeforeafterboth1380 }1380 }1381 }1381 }13821383 /// Sets the NFT token as a parent for the RFT token1384 ///1385 /// Throws if `sender` is not the owner of the NFT token.1386 /// Throws if `sender` is not the owner of all of the RFT token pieces.1387 pub fn set_parent_nft(1388 collection: &RefungibleHandle<T>,1389 rft_token_id: TokenId,1390 sender: T::CrossAccountId,1391 nft_collection: CollectionId,1392 nft_token: TokenId,1393 ) -> DispatchResult {1394 let handle = <CollectionHandle<T>>::try_get(nft_collection)?;1395 if handle.mode != CollectionMode::NFT {1396 return Err("Only NFT token could be parent to RFT".into());1397 }1398 let dispatch = T::CollectionDispatch::dispatch(handle);1399 let dispatch = dispatch.as_dyn();14001401 let owner = dispatch.token_owner(nft_token).ok_or("owner not found")?;1402 if owner != sender {1403 return Err("Only owned token could be set as parent".into());1404 }14051406 let nft_token_address =1407 T::CrossTokenAddressMapping::token_to_address(nft_collection, nft_token);14081409 Self::set_parent_nft_unchecked(collection, rft_token_id, sender, nft_token_address)1410 }14111412 /// Sets the NFT token as a parent for the RFT token1413 ///1414 /// `sender` should be the owner of the NFT token.1415 /// Throws if `sender` is not the owner of all of the RFT token pieces.1416 pub fn set_parent_nft_unchecked(1417 collection: &RefungibleHandle<T>,1418 rft_token_id: TokenId,1419 sender: T::CrossAccountId,1420 nft_token_address: T::CrossAccountId,1421 ) -> DispatchResult {1422 let owner_balance = <Balance<T>>::get((collection.id, rft_token_id, &sender));1423 let total_supply = <TotalSupply<T>>::get((collection.id, rft_token_id));1424 if total_supply != owner_balance {1425 return Err("token has multiple owners".into());1426 }14271428 let parent_nft_property_key = key::parent_nft();14291430 let parent_nft_property_value =1431 property_value_from_bytes(&nft_token_address.as_eth().to_fixed_bytes())1432 .expect("address should fit in value length limit");14331434 <Pallet<T>>::set_scoped_token_property(1435 collection.id,1436 rft_token_id,1437 PropertyScope::Eth,1438 Property {1439 key: parent_nft_property_key,1440 value: parent_nft_property_value,1441 },1442 )?;14431444 Ok(())1445 }1446}1382}14471383pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungibleToken.soldiffbeforeafterboth21 }21 }22}22}2324/// @dev the ERC-165 identifier for this interface is 0x042f110625contract ERC1633UniqueExtensions is Dummy, ERC165 {26 /// @dev EVM selector for this function is: 0x042f1106,27 /// or in textual repr: setParentNFT(address,uint256)28 function setParentNFT(address collection, uint256 nftId)29 public30 returns (bool)31 {32 require(false, stub_error);33 collection;34 nftId;35 dummy = 0;36 return false;37 }38}392340/// @dev the ERC-165 identifier for this interface is 0x5755c3f224/// @dev the ERC-165 identifier for this interface is 0x5755c3f241contract ERC1633 is Dummy, ERC165 {25contract ERC1633 is Dummy, ERC165 {222 ERC165,206 ERC165,223 ERC20,207 ERC20,224 ERC20UniqueExtensions,208 ERC20UniqueExtensions,225 ERC1633,209 ERC1633226 ERC1633UniqueExtensions227{}210{}228211pallets/refungible/src/weights.rsdiffbeforeafterboth53 fn set_token_properties(b: u32, ) -> Weight;53 fn set_token_properties(b: u32, ) -> Weight;54 fn delete_token_properties(b: u32, ) -> Weight;54 fn delete_token_properties(b: u32, ) -> Weight;55 fn repartition_item() -> Weight;55 fn repartition_item() -> Weight;56 fn set_parent_nft_unchecked() -> Weight;57 fn token_owner() -> Weight;56 fn token_owner() -> Weight;58}57}5958255 .saturating_add(T::DbWeight::get().reads(2 as Weight))254 .saturating_add(T::DbWeight::get().reads(2 as Weight))256 .saturating_add(T::DbWeight::get().writes(2 as Weight))255 .saturating_add(T::DbWeight::get().writes(2 as Weight))257 }256 }258 // Storage: Refungible Balance (r:1 w:0)259 // Storage: Refungible TotalSupply (r:1 w:0)260 // Storage: Refungible TokenProperties (r:1 w:1)261 fn set_parent_nft_unchecked() -> Weight {262 (12_015_000 as Weight)263 .saturating_add(T::DbWeight::get().reads(3 as Weight))264 .saturating_add(T::DbWeight::get().writes(1 as Weight))265 }266 // Storage: Refungible Balance (r:2 w:0)257 // Storage: Refungible Balance (r:2 w:0)267 fn token_owner() -> Weight {258 fn token_owner() -> Weight {268 (9_431_000 as Weight)259 (9_431_000 as Weight)467 .saturating_add(RocksDbWeight::get().reads(2 as Weight))458 .saturating_add(RocksDbWeight::get().reads(2 as Weight))468 .saturating_add(RocksDbWeight::get().writes(2 as Weight))459 .saturating_add(RocksDbWeight::get().writes(2 as Weight))469 }460 }470 // Storage: Refungible Balance (r:1 w:0)471 // Storage: Refungible TotalSupply (r:1 w:0)472 // Storage: Refungible TokenProperties (r:1 w:1)473 fn set_parent_nft_unchecked() -> Weight {474 (12_015_000 as Weight)475 .saturating_add(RocksDbWeight::get().reads(3 as Weight))476 .saturating_add(RocksDbWeight::get().writes(1 as Weight))477 }478 // Storage: Refungible Balance (r:2 w:0)461 // Storage: Refungible Balance (r:2 w:0)479 fn token_owner() -> Weight {462 fn token_owner() -> Weight {480 (9_431_000 as Weight)463 (9_431_000 as Weight)pallets/unique/src/eth/mod.rsdiffbeforeafterboth154 Ok(data)154 Ok(data)155}155}156157fn parent_nft_property_permissions() -> PropertyKeyPermission {158 PropertyKeyPermission {159 key: key::parent_nft(),160 permission: PropertyPermission {161 mutable: false,162 collection_admin: false,163 token_owner: true,164 },165 }166}167156168fn create_refungible_collection_internal<157fn create_refungible_collection_internal<169 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,158 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,189 let collection_id = T::CollectionDispatch::create(caller.clone(), data)178 let collection_id = T::CollectionDispatch::create(caller.clone(), data)190 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;179 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;191192 let handle = <CollectionHandle<T>>::try_get(collection_id).map_err(dispatch_to_evm::<T>)?;193 <PalletCommon<T>>::set_scoped_token_property_permissions(194 &handle,195 &caller,196 PropertyScope::Eth,197 vec![parent_nft_property_permissions()],198 )199 .map_err(dispatch_to_evm::<T>)?;200201 let address = pallet_common::eth::collection_id_to_address(collection_id);180 let address = pallet_common::eth::collection_id_to_address(collection_id);202 Ok(address)181 Ok(address)primitives/data-structs/src/lib.rsdiffbeforeafterboth1050pub enum PropertyScope {1050pub enum PropertyScope {1051 None,1051 None,1052 Rmrk,1052 Rmrk,1053 Eth,1054}1053}105510541056impl PropertyScope {1055impl PropertyScope {1059 let scope_str: &[u8] = match self {1058 let scope_str: &[u8] = match self {1060 Self::None => return Ok(key),1059 Self::None => return Ok(key),1061 Self::Rmrk => b"rmrk",1060 Self::Rmrk => b"rmrk",1062 Self::Eth => b"eth",1063 };1061 };106410621065 [scope_str, b":", key.as_slice()]1063 [scope_str, b":", key.as_slice()]tests/src/eth/api/UniqueRefungibleToken.soldiffbeforeafterboth12 function supportsInterface(bytes4 interfaceID) external view returns (bool);12 function supportsInterface(bytes4 interfaceID) external view returns (bool);13}13}1415/// @dev the ERC-165 identifier for this interface is 0x042f110616interface ERC1633UniqueExtensions is Dummy, ERC165 {17 /// @dev EVM selector for this function is: 0x042f1106,18 /// or in textual repr: setParentNFT(address,uint256)19 function setParentNFT(address collection, uint256 nftId)20 external21 returns (bool);22}231424/// @dev the ERC-165 identifier for this interface is 0x5755c3f215/// @dev the ERC-165 identifier for this interface is 0x5755c3f225interface ERC1633 is Dummy, ERC165 {16interface ERC1633 is Dummy, ERC165 {140 ERC165,131 ERC165,141 ERC20,132 ERC20,142 ERC20UniqueExtensions,133 ERC20UniqueExtensions,143 ERC1633,134 ERC1633144 ERC1633UniqueExtensions145{}135{}146136tests/src/eth/base.test.tsdiffbeforeafterboth94 });94 });959596 itWeb3('ERC721 support', async ({web3}) => {96 itWeb3('ERC721 support', async ({web3}) => {97 expect(await contract(web3).methods.supportsInterface('0x58800161').call()).to.be.true;97 expect(await contract(web3).methods.supportsInterface('0x780e9d63').call()).to.be.true;98 });98 });9999100 itWeb3('ERC721Metadata support', async ({web3}) => {100 itWeb3('ERC721Metadata support', async ({web3}) => {tests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth16 }16 }17 address rftCollection;17 address rftCollection;18 mapping(address => bool) nftCollectionAllowList;18 mapping(address => bool) nftCollectionAllowList;19 mapping(address => mapping(uint256 => uint256)) nft2rftMapping;19 mapping(address => mapping(uint256 => uint256)) public nft2rftMapping;20 mapping(address => Token) rft2nftMapping;20 mapping(address => Token) public rft2nftMapping;21 bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));21 bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));222223 receive() external payable onlyOwner {}23 receive() external payable onlyOwner {}137 rft2nftMapping[rftTokenAddress] = Token(_collection, _token);137 rft2nftMapping[rftTokenAddress] = Token(_collection, _token);138138139 rftTokenContract = UniqueRefungibleToken(rftTokenAddress);139 rftTokenContract = UniqueRefungibleToken(rftTokenAddress);140 rftTokenContract.setParentNFT(_collection, _token);141 } else {140 } else {142 rftTokenId = nft2rftMapping[_collection][_token];141 rftTokenId = nft2rftMapping[_collection][_token];143 rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);142 rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);tests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth224 });224 });225 });225 });226227 itWeb3('Test fractionalizer NFT <-> RFT mapping ', async ({api, web3, privateKeyWrapper}) => {228 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);229230 const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);231 const {rftTokenAddress, nftCollectionAddress, nftTokenId} = await createRFTToken(api, web3, owner, fractionalizer, 100n);232233 const {collectionId, tokenId} = tokenIdFromAddress(rftTokenAddress);234 const refungibleAddress = collectionIdToAddress(collectionId);235 expect(rftCollectionAddress).to.be.equal(refungibleAddress);236 const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);237 await refungibleTokenContract.methods.approve(fractionalizer.options.address, 100).send();238239 const rft2nft = await fractionalizer.methods.rft2nftMapping(rftTokenAddress).call();240 expect(rft2nft).to.be.like({241 _collection: nftCollectionAddress,242 _tokenId: nftTokenId,243 });244245 const nft2rft = await fractionalizer.methods.nft2rftMapping(nftCollectionAddress, nftTokenId).call();246 expect(nft2rft).to.be.eq(tokenId.toString());247 });226});248});227249228250tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth655 await requirePallets(this, [Pallets.ReFungible]);655 await requirePallets(this, [Pallets.ReFungible]);656 });656 });657658 itWeb3('Parent NFT token address and id', async ({api, web3, privateKeyWrapper}) => {659 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);660661 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);662 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);663 const nftTokenId = await nftContract.methods.nextTokenId().call();664 await nftContract.methods.mint(owner, nftTokenId).send();665 const nftCollectionId = collectionIdFromAddress(nftCollectionAddress);666667 const {collectionIdAddress, collectionId} = await createRefungibleCollection(api, web3, owner);668 const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);669 const refungibleTokenId = await refungibleContract.methods.nextTokenId().call();670 await refungibleContract.methods.mint(owner, refungibleTokenId).send();671672 const rftTokenAddress = tokenIdToAddress(collectionId, refungibleTokenId);673 const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);674 await refungibleTokenContract.methods.setParentNFT(nftCollectionAddress, nftTokenId).send();675676 const tokenAddress = await refungibleTokenContract.methods.parentToken().call();677 const tokenId = await refungibleTokenContract.methods.parentTokenId().call();678 const nftTokenAddress = tokenIdToAddress(nftCollectionId, nftTokenId);679 expect(tokenAddress).to.be.equal(nftTokenAddress);680 expect(tokenId).to.be.equal(nftTokenId);681 });682657683 itWeb3('Default parent token address and id', async ({api, web3, privateKeyWrapper}) => {658 itWeb3('Default parent token address and id', async ({api, web3, privateKeyWrapper}) => {684 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);659 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);693668694 const tokenAddress = await refungibleTokenContract.methods.parentToken().call();669 const tokenAddress = await refungibleTokenContract.methods.parentToken().call();695 const tokenId = await refungibleTokenContract.methods.parentTokenId().call();670 const tokenId = await refungibleTokenContract.methods.parentTokenId().call();696 expect(tokenAddress).to.be.equal(rftTokenAddress);671 expect(tokenAddress).to.be.equal(collectionIdAddress);697 expect(tokenId).to.be.equal(refungibleTokenId);672 expect(tokenId).to.be.equal(refungibleTokenId);698 });673 });699});674});tests/src/eth/reFungibleTokenAbi.jsondiffbeforeafterboth125 "stateMutability": "nonpayable",125 "stateMutability": "nonpayable",126 "type": "function"126 "type": "function"127 },127 },128 {129 "inputs": [130 { "internalType": "address", "name": "collection", "type": "address" },131 { "internalType": "uint256", "name": "nftId", "type": "uint256" }132 ],133 "name": "setParentNFT",134 "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],135 "stateMutability": "nonpayable",136 "type": "function"137 },138 {128 {139 "inputs": [129 "inputs": [140 { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }130 { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }