difftreelog
Merge pull request #542 from UniqueNetwork/fix/RFT_and_fractionalizer
in: master
14 files changed
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -281,15 +281,6 @@
let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
}: {<Pallet<T>>::repartition(&collection, &owner, item, 200)?}
- set_parent_nft_unchecked {
- bench_init!{
- owner: sub; collection: collection(owner);
- sender: cross_from_sub(owner); owner: cross_sub;
- };
- let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
-
- }: {<Pallet<T>>::set_parent_nft_unchecked(&collection, item, owner, T::CrossAccountId::from_eth(H160::default()))?}
-
token_owner {
bench_init!{
owner: sub; collection: collection(owner);
pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -29,22 +29,21 @@
convert::TryInto,
ops::Deref,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
use pallet_common::{
CommonWeightInfo,
- erc::{CommonEvmHandler, PrecompileResult, static_property::key},
- eth::map_eth_to_id,
+ erc::{CommonEvmHandler, PrecompileResult},
+ eth::collection_id_to_address,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};
use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
-use sp_core::H160;
use sp_std::vec::Vec;
-use up_data_structs::{mapping::TokenAddressMapping, PropertyScope, TokenId};
+use up_data_structs::TokenId;
use crate::{
Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,
- TokenProperties, TotalSupply, weights::WeightInfo,
+ TotalSupply, weights::WeightInfo,
};
pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);
@@ -52,63 +51,14 @@
#[solidity_interface(name = ERC1633)]
impl<T: Config> RefungibleTokenHandle<T> {
fn parent_token(&self) -> Result<address> {
- self.consume_store_reads(2)?;
- let props = <TokenProperties<T>>::get((self.id, self.1));
- let key = key::parent_nft();
-
- let key_scoped = PropertyScope::Eth
- .apply(key)
- .expect("property key shouldn't exceed length limit");
- if let Some(value) = props.get(&key_scoped) {
- Ok(H160::from_slice(value.as_slice()))
- } else {
- Ok(*T::CrossTokenAddressMapping::token_to_address(self.id, self.1).as_eth())
- }
+ Ok(collection_id_to_address(self.id))
}
fn parent_token_id(&self) -> Result<uint256> {
- self.consume_store_reads(2)?;
- let props = <TokenProperties<T>>::get((self.id, self.1));
- let key = key::parent_nft();
-
- let key_scoped = PropertyScope::Eth
- .apply(key)
- .expect("property key shouldn't exceed length limit");
- if let Some(value) = props.get(&key_scoped) {
- let nft_token_address = H160::from_slice(value.as_slice());
- let nft_token_account = T::CrossAccountId::from_eth(nft_token_address);
- let (_, token_id) = T::CrossTokenAddressMapping::address_to_token(&nft_token_account)
- .ok_or("parent NFT should contain NFT token address")?;
-
- Ok(token_id.into())
- } else {
- Ok(self.1.into())
- }
+ Ok(self.1.into())
}
}
-#[solidity_interface(name = ERC1633UniqueExtensions)]
-impl<T: Config> RefungibleTokenHandle<T> {
- #[solidity(rename_selector = "setParentNFT")]
- #[weight(<CommonWeights<T>>::token_owner() + <SelfWeightOf<T>>::set_parent_nft_unchecked())]
- fn set_parent_nft(
- &mut self,
- caller: caller,
- collection: address,
- nft_id: uint256,
- ) -> Result<bool> {
- self.consume_store_reads(1)?;
- let caller = T::CrossAccountId::from_eth(caller);
- let nft_collection = map_eth_to_id(&collection).ok_or("collection not found")?;
- let nft_token = nft_id.try_into()?;
-
- <Pallet<T>>::set_parent_nft(&self.0, self.1, caller, nft_collection, nft_token)
- .map_err(dispatch_to_evm::<T>)?;
-
- Ok(true)
- }
-}
-
#[derive(ToLog)]
pub enum ERC20Events {
/// @dev This event is emitted when the amount of tokens (value) is sent
@@ -307,7 +257,7 @@
#[solidity_interface(
name = UniqueRefungibleToken,
- is(ERC20, ERC20UniqueExtensions, ERC1633, ERC1633UniqueExtensions)
+ is(ERC20, ERC20UniqueExtensions, ERC1633)
)]
impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1379,68 +1379,4 @@
Some(res)
}
}
-
- /// Sets the NFT token as a parent for the RFT token
- ///
- /// Throws if `sender` is not the owner of the NFT token.
- /// Throws if `sender` is not the owner of all of the RFT token pieces.
- pub fn set_parent_nft(
- collection: &RefungibleHandle<T>,
- rft_token_id: TokenId,
- sender: T::CrossAccountId,
- nft_collection: CollectionId,
- nft_token: TokenId,
- ) -> DispatchResult {
- let handle = <CollectionHandle<T>>::try_get(nft_collection)?;
- if handle.mode != CollectionMode::NFT {
- return Err("Only NFT token could be parent to RFT".into());
- }
- let dispatch = T::CollectionDispatch::dispatch(handle);
- let dispatch = dispatch.as_dyn();
-
- let owner = dispatch.token_owner(nft_token).ok_or("owner not found")?;
- if owner != sender {
- return Err("Only owned token could be set as parent".into());
- }
-
- let nft_token_address =
- T::CrossTokenAddressMapping::token_to_address(nft_collection, nft_token);
-
- Self::set_parent_nft_unchecked(collection, rft_token_id, sender, nft_token_address)
- }
-
- /// Sets the NFT token as a parent for the RFT token
- ///
- /// `sender` should be the owner of the NFT token.
- /// Throws if `sender` is not the owner of all of the RFT token pieces.
- pub fn set_parent_nft_unchecked(
- collection: &RefungibleHandle<T>,
- rft_token_id: TokenId,
- sender: T::CrossAccountId,
- nft_token_address: T::CrossAccountId,
- ) -> DispatchResult {
- let owner_balance = <Balance<T>>::get((collection.id, rft_token_id, &sender));
- let total_supply = <TotalSupply<T>>::get((collection.id, rft_token_id));
- if total_supply != owner_balance {
- return Err("token has multiple owners".into());
- }
-
- let parent_nft_property_key = key::parent_nft();
-
- let parent_nft_property_value =
- property_value_from_bytes(&nft_token_address.as_eth().to_fixed_bytes())
- .expect("address should fit in value length limit");
-
- <Pallet<T>>::set_scoped_token_property(
- collection.id,
- rft_token_id,
- PropertyScope::Eth,
- Property {
- key: parent_nft_property_key,
- value: parent_nft_property_value,
- },
- )?;
-
- Ok(())
- }
}
pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungibleToken.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
@@ -21,22 +21,6 @@
}
}
-/// @dev the ERC-165 identifier for this interface is 0x042f1106
-contract ERC1633UniqueExtensions is Dummy, ERC165 {
- /// @dev EVM selector for this function is: 0x042f1106,
- /// or in textual repr: setParentNFT(address,uint256)
- function setParentNFT(address collection, uint256 nftId)
- public
- returns (bool)
- {
- require(false, stub_error);
- collection;
- nftId;
- dummy = 0;
- return false;
- }
-}
-
/// @dev the ERC-165 identifier for this interface is 0x5755c3f2
contract ERC1633 is Dummy, ERC165 {
/// @dev EVM selector for this function is: 0x80a54001,
@@ -222,6 +206,5 @@
ERC165,
ERC20,
ERC20UniqueExtensions,
- ERC1633,
- ERC1633UniqueExtensions
+ ERC1633
{}
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -53,7 +53,6 @@
fn set_token_properties(b: u32, ) -> Weight;
fn delete_token_properties(b: u32, ) -> Weight;
fn repartition_item() -> Weight;
- fn set_parent_nft_unchecked() -> Weight;
fn token_owner() -> Weight;
}
@@ -254,14 +253,6 @@
(22_356_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
- }
- // Storage: Refungible Balance (r:1 w:0)
- // Storage: Refungible TotalSupply (r:1 w:0)
- // Storage: Refungible TokenProperties (r:1 w:1)
- fn set_parent_nft_unchecked() -> Weight {
- (12_015_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(3 as Weight))
- .saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Refungible Balance (r:2 w:0)
fn token_owner() -> Weight {
@@ -466,14 +457,6 @@
(22_356_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
- }
- // Storage: Refungible Balance (r:1 w:0)
- // Storage: Refungible TotalSupply (r:1 w:0)
- // Storage: Refungible TokenProperties (r:1 w:1)
- fn set_parent_nft_unchecked() -> Weight {
- (12_015_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(3 as Weight))
- .saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Refungible Balance (r:2 w:0)
fn token_owner() -> Weight {
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -154,17 +154,6 @@
Ok(data)
}
-fn parent_nft_property_permissions() -> PropertyKeyPermission {
- PropertyKeyPermission {
- key: key::parent_nft(),
- permission: PropertyPermission {
- mutable: false,
- collection_admin: false,
- token_owner: true,
- },
- }
-}
-
fn create_refungible_collection_internal<
T: Config + pallet_nonfungible::Config + pallet_refungible::Config,
>(
@@ -188,16 +177,6 @@
let collection_id = T::CollectionDispatch::create(caller.clone(), data)
.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
-
- let handle = <CollectionHandle<T>>::try_get(collection_id).map_err(dispatch_to_evm::<T>)?;
- <PalletCommon<T>>::set_scoped_token_property_permissions(
- &handle,
- &caller,
- PropertyScope::Eth,
- vec![parent_nft_property_permissions()],
- )
- .map_err(dispatch_to_evm::<T>)?;
-
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1050,7 +1050,6 @@
pub enum PropertyScope {
None,
Rmrk,
- Eth,
}
impl PropertyScope {
@@ -1059,7 +1058,6 @@
let scope_str: &[u8] = match self {
Self::None => return Ok(key),
Self::Rmrk => b"rmrk",
- Self::Eth => b"eth",
};
[scope_str, b":", key.as_slice()]
tests/src/eth/api/UniqueRefungibleToken.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungibleToken.sol
+++ b/tests/src/eth/api/UniqueRefungibleToken.sol
@@ -12,15 +12,6 @@
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
-/// @dev the ERC-165 identifier for this interface is 0x042f1106
-interface ERC1633UniqueExtensions is Dummy, ERC165 {
- /// @dev EVM selector for this function is: 0x042f1106,
- /// or in textual repr: setParentNFT(address,uint256)
- function setParentNFT(address collection, uint256 nftId)
- external
- returns (bool);
-}
-
/// @dev the ERC-165 identifier for this interface is 0x5755c3f2
interface ERC1633 is Dummy, ERC165 {
/// @dev EVM selector for this function is: 0x80a54001,
@@ -140,6 +131,5 @@
ERC165,
ERC20,
ERC20UniqueExtensions,
- ERC1633,
- ERC1633UniqueExtensions
+ ERC1633
{}
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -94,7 +94,7 @@
});
itWeb3('ERC721 support', async ({web3}) => {
- expect(await contract(web3).methods.supportsInterface('0x58800161').call()).to.be.true;
+ expect(await contract(web3).methods.supportsInterface('0x780e9d63').call()).to.be.true;
});
itWeb3('ERC721Metadata support', async ({web3}) => {
tests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth1// SPDX-License-Identifier: Apache License2pragma solidity >=0.8.0;3import {CollectionHelpers} from "../api/CollectionHelpers.sol";4import {ContractHelpers} from "../api/ContractHelpers.sol";5import {UniqueRefungibleToken} from "../api/UniqueRefungibleToken.sol";6import {UniqueRefungible} from "../api/UniqueRefungible.sol";7import {UniqueNFT} from "../api/UniqueNFT.sol";89/// @dev Fractionalization contract. It stores mappings between NFT and RFT tokens,10/// stores allowlist of NFT tokens available for fractionalization, has methods11/// for fractionalization and defractionalization of NFT tokens.12contract Fractionalizer {13 struct Token {14 address _collection;15 uint256 _tokenId;16 }17 address rftCollection;18 mapping(address => bool) nftCollectionAllowList;19 mapping(address => mapping(uint256 => uint256)) nft2rftMapping;20 mapping(address => Token) rft2nftMapping;21 bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));2223 receive() external payable onlyOwner {}2425 /// @dev Method modifier to only allow contract owner to call it.26 modifier onlyOwner() {27 address contracthelpersAddress = 0x842899ECF380553E8a4de75bF534cdf6fBF64049;28 ContractHelpers contractHelpers = ContractHelpers(contracthelpersAddress);29 address contractOwner = contractHelpers.contractOwner(address(this));30 require(msg.sender == contractOwner, "Only owner can");31 _;32 }3334 /// @dev This emits when RFT collection setting is changed.35 event RFTCollectionSet(address _collection);3637 /// @dev This emits when NFT collection is allowed or disallowed.38 event AllowListSet(address _collection, bool _status);3940 /// @dev This emits when NFT token is fractionalized by contract.41 event Fractionalized(address _collection, uint256 _tokenId, address _rftToken, uint128 _amount);4243 /// @dev This emits when NFT token is defractionalized by contract.44 event Defractionalized(address _rftToken, address _nftCollection, uint256 _nftTokenId);4546 /// Set RFT collection that contract will work with. RFT tokens for fractionalized NFT tokens47 /// would be created in this collection.48 /// @dev Throws if RFT collection is already configured for this contract.49 /// Throws if collection of wrong type (NFT, Fungible) is provided instead50 /// of RFT collection.51 /// Throws if `msg.sender` is not owner or admin of provided RFT collection.52 /// Can only be called by contract owner.53 /// @param _collection address of RFT collection.54 function setRFTCollection(address _collection) public onlyOwner {55 require(56 rftCollection == address(0),57 "RFT collection is already set"58 );59 UniqueRefungible refungibleContract = UniqueRefungible(_collection);60 string memory collectionType = refungibleContract.uniqueCollectionType();61 62 require(63 keccak256(bytes(collectionType)) == refungibleCollectionType,64 "Wrong collection type. Collection is not refungible."65 );66 require(67 refungibleContract.isOwnerOrAdmin(address(this)),68 "Fractionalizer contract should be an admin of the collection"69 );70 rftCollection = _collection;71 emit RFTCollectionSet(rftCollection);72 }7374 /// Creates and sets RFT collection that contract will work with. RFT tokens for fractionalized NFT tokens75 /// would be created in this collection.76 /// @dev Throws if RFT collection is already configured for this contract.77 /// Can only be called by contract owner.78 /// @param _name name for created RFT collection.79 /// @param _description description for created RFT collection.80 /// @param _tokenPrefix token prefix for created RFT collection.81 function createAndSetRFTCollection(string calldata _name, string calldata _description, string calldata _tokenPrefix) public onlyOwner {82 require(83 rftCollection == address(0),84 "RFT collection is already set"85 );86 address collectionHelpers = 0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F;87 rftCollection = CollectionHelpers(collectionHelpers).createRefungibleCollection(_name, _description, _tokenPrefix);88 emit RFTCollectionSet(rftCollection);89 }9091 /// Allow or disallow NFT collection tokens from being fractionalized by this contract.92 /// @dev Can only be called by contract owner.93 /// @param collection NFT token address.94 /// @param status `true` to allow and `false` to disallow NFT token.95 function setNftCollectionIsAllowed(address collection, bool status) public onlyOwner {96 nftCollectionAllowList[collection] = status;97 emit AllowListSet(collection, status);98 }99100 /// Fractionilize NFT token.101 /// @dev Takes NFT token from `msg.sender` and transfers RFT token to `msg.sender`102 /// instead. Creates new RFT token if provided NFT token never was fractionalized103 /// by this contract or existing RFT token if it was.104 /// Throws if RFT collection isn't configured for this contract.105 /// Throws if fractionalization of provided NFT token is not allowed106 /// Throws if `msg.sender` is not owner of provided NFT token107 /// @param _collection NFT collection address108 /// @param _token id of NFT token to be fractionalized109 /// @param _pieces number of pieces new RFT token would have110 function nft2rft(address _collection, uint256 _token, uint128 _pieces) public {111 require(112 rftCollection != address(0),113 "RFT collection is not set"114 );115 UniqueRefungible rftCollectionContract = UniqueRefungible(rftCollection);116 require(117 nftCollectionAllowList[_collection] == true,118 "Fractionalization of this collection is not allowed by admin"119 );120 require(121 UniqueNFT(_collection).ownerOf(_token) == msg.sender,122 "Only token owner could fractionalize it"123 );124 UniqueNFT(_collection).transferFrom(125 msg.sender,126 address(this),127 _token128 );129 uint256 rftTokenId;130 address rftTokenAddress;131 UniqueRefungibleToken rftTokenContract;132 if (nft2rftMapping[_collection][_token] == 0) {133 rftTokenId = rftCollectionContract.nextTokenId();134 rftCollectionContract.mint(address(this), rftTokenId);135 rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);136 nft2rftMapping[_collection][_token] = rftTokenId;137 rft2nftMapping[rftTokenAddress] = Token(_collection, _token);138139 rftTokenContract = UniqueRefungibleToken(rftTokenAddress);140 rftTokenContract.setParentNFT(_collection, _token);141 } else {142 rftTokenId = nft2rftMapping[_collection][_token];143 rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);144 rftTokenContract = UniqueRefungibleToken(rftTokenAddress);145 }146 rftTokenContract.repartition(_pieces);147 rftTokenContract.transfer(msg.sender, _pieces);148 emit Fractionalized(_collection, _token, rftTokenAddress, _pieces);149 }150151 /// Defrationalize NFT token.152 /// @dev Takes RFT token from `msg.sender` and transfers corresponding NFT token153 /// to `msg.sender` instead.154 /// Throws if RFT collection isn't configured for this contract.155 /// Throws if provided RFT token is no from configured RFT collection.156 /// Throws if RFT token was not created by this contract.157 /// Throws if `msg.sender` isn't owner of all RFT token pieces.158 /// @param _collection RFT collection address159 /// @param _token id of RFT token160 function rft2nft(address _collection, uint256 _token) public {161 require(162 rftCollection != address(0),163 "RFT collection is not set"164 );165 require(166 rftCollection == _collection,167 "Wrong RFT collection"168 );169 UniqueRefungible rftCollectionContract = UniqueRefungible(rftCollection);170 address rftTokenAddress = rftCollectionContract.tokenContractAddress(_token);171 Token memory nftToken = rft2nftMapping[rftTokenAddress];172 require(173 nftToken._collection != address(0),174 "No corresponding NFT token found"175 );176 UniqueRefungibleToken rftTokenContract = UniqueRefungibleToken(rftTokenAddress);177 require(178 rftTokenContract.balanceOf(msg.sender) == rftTokenContract.totalSupply(),179 "Not all pieces are owned by the caller"180 );181 rftCollectionContract.transferFrom(msg.sender, address(this), _token);182 UniqueNFT(nftToken._collection).transferFrom(183 address(this),184 msg.sender,185 nftToken._tokenId186 );187 emit Defractionalized(rftTokenAddress, nftToken._collection, nftToken._tokenId);188 }189}1// SPDX-License-Identifier: Apache License2pragma solidity >=0.8.0;3import {CollectionHelpers} from "../api/CollectionHelpers.sol";4import {ContractHelpers} from "../api/ContractHelpers.sol";5import {UniqueRefungibleToken} from "../api/UniqueRefungibleToken.sol";6import {UniqueRefungible} from "../api/UniqueRefungible.sol";7import {UniqueNFT} from "../api/UniqueNFT.sol";89/// @dev Fractionalization contract. It stores mappings between NFT and RFT tokens,10/// stores allowlist of NFT tokens available for fractionalization, has methods11/// for fractionalization and defractionalization of NFT tokens.12contract Fractionalizer {13 struct Token {14 address _collection;15 uint256 _tokenId;16 }17 address rftCollection;18 mapping(address => bool) nftCollectionAllowList;19 mapping(address => mapping(uint256 => uint256)) public nft2rftMapping;20 mapping(address => Token) public rft2nftMapping;21 bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));2223 receive() external payable onlyOwner {}2425 /// @dev Method modifier to only allow contract owner to call it.26 modifier onlyOwner() {27 address contracthelpersAddress = 0x842899ECF380553E8a4de75bF534cdf6fBF64049;28 ContractHelpers contractHelpers = ContractHelpers(contracthelpersAddress);29 address contractOwner = contractHelpers.contractOwner(address(this));30 require(msg.sender == contractOwner, "Only owner can");31 _;32 }3334 /// @dev This emits when RFT collection setting is changed.35 event RFTCollectionSet(address _collection);3637 /// @dev This emits when NFT collection is allowed or disallowed.38 event AllowListSet(address _collection, bool _status);3940 /// @dev This emits when NFT token is fractionalized by contract.41 event Fractionalized(address _collection, uint256 _tokenId, address _rftToken, uint128 _amount);4243 /// @dev This emits when NFT token is defractionalized by contract.44 event Defractionalized(address _rftToken, address _nftCollection, uint256 _nftTokenId);4546 /// Set RFT collection that contract will work with. RFT tokens for fractionalized NFT tokens47 /// would be created in this collection.48 /// @dev Throws if RFT collection is already configured for this contract.49 /// Throws if collection of wrong type (NFT, Fungible) is provided instead50 /// of RFT collection.51 /// Throws if `msg.sender` is not owner or admin of provided RFT collection.52 /// Can only be called by contract owner.53 /// @param _collection address of RFT collection.54 function setRFTCollection(address _collection) public onlyOwner {55 require(56 rftCollection == address(0),57 "RFT collection is already set"58 );59 UniqueRefungible refungibleContract = UniqueRefungible(_collection);60 string memory collectionType = refungibleContract.uniqueCollectionType();61 62 require(63 keccak256(bytes(collectionType)) == refungibleCollectionType,64 "Wrong collection type. Collection is not refungible."65 );66 require(67 refungibleContract.isOwnerOrAdmin(address(this)),68 "Fractionalizer contract should be an admin of the collection"69 );70 rftCollection = _collection;71 emit RFTCollectionSet(rftCollection);72 }7374 /// Creates and sets RFT collection that contract will work with. RFT tokens for fractionalized NFT tokens75 /// would be created in this collection.76 /// @dev Throws if RFT collection is already configured for this contract.77 /// Can only be called by contract owner.78 /// @param _name name for created RFT collection.79 /// @param _description description for created RFT collection.80 /// @param _tokenPrefix token prefix for created RFT collection.81 function createAndSetRFTCollection(string calldata _name, string calldata _description, string calldata _tokenPrefix) public onlyOwner {82 require(83 rftCollection == address(0),84 "RFT collection is already set"85 );86 address collectionHelpers = 0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F;87 rftCollection = CollectionHelpers(collectionHelpers).createRefungibleCollection(_name, _description, _tokenPrefix);88 emit RFTCollectionSet(rftCollection);89 }9091 /// Allow or disallow NFT collection tokens from being fractionalized by this contract.92 /// @dev Can only be called by contract owner.93 /// @param collection NFT token address.94 /// @param status `true` to allow and `false` to disallow NFT token.95 function setNftCollectionIsAllowed(address collection, bool status) public onlyOwner {96 nftCollectionAllowList[collection] = status;97 emit AllowListSet(collection, status);98 }99100 /// Fractionilize NFT token.101 /// @dev Takes NFT token from `msg.sender` and transfers RFT token to `msg.sender`102 /// instead. Creates new RFT token if provided NFT token never was fractionalized103 /// by this contract or existing RFT token if it was.104 /// Throws if RFT collection isn't configured for this contract.105 /// Throws if fractionalization of provided NFT token is not allowed106 /// Throws if `msg.sender` is not owner of provided NFT token107 /// @param _collection NFT collection address108 /// @param _token id of NFT token to be fractionalized109 /// @param _pieces number of pieces new RFT token would have110 function nft2rft(address _collection, uint256 _token, uint128 _pieces) public {111 require(112 rftCollection != address(0),113 "RFT collection is not set"114 );115 UniqueRefungible rftCollectionContract = UniqueRefungible(rftCollection);116 require(117 nftCollectionAllowList[_collection] == true,118 "Fractionalization of this collection is not allowed by admin"119 );120 require(121 UniqueNFT(_collection).ownerOf(_token) == msg.sender,122 "Only token owner could fractionalize it"123 );124 UniqueNFT(_collection).transferFrom(125 msg.sender,126 address(this),127 _token128 );129 uint256 rftTokenId;130 address rftTokenAddress;131 UniqueRefungibleToken rftTokenContract;132 if (nft2rftMapping[_collection][_token] == 0) {133 rftTokenId = rftCollectionContract.nextTokenId();134 rftCollectionContract.mint(address(this), rftTokenId);135 rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);136 nft2rftMapping[_collection][_token] = rftTokenId;137 rft2nftMapping[rftTokenAddress] = Token(_collection, _token);138139 rftTokenContract = UniqueRefungibleToken(rftTokenAddress);140 } else {141 rftTokenId = nft2rftMapping[_collection][_token];142 rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);143 rftTokenContract = UniqueRefungibleToken(rftTokenAddress);144 }145 rftTokenContract.repartition(_pieces);146 rftTokenContract.transfer(msg.sender, _pieces);147 emit Fractionalized(_collection, _token, rftTokenAddress, _pieces);148 }149150 /// Defrationalize NFT token.151 /// @dev Takes RFT token from `msg.sender` and transfers corresponding NFT token152 /// to `msg.sender` instead.153 /// Throws if RFT collection isn't configured for this contract.154 /// Throws if provided RFT token is no from configured RFT collection.155 /// Throws if RFT token was not created by this contract.156 /// Throws if `msg.sender` isn't owner of all RFT token pieces.157 /// @param _collection RFT collection address158 /// @param _token id of RFT token159 function rft2nft(address _collection, uint256 _token) public {160 require(161 rftCollection != address(0),162 "RFT collection is not set"163 );164 require(165 rftCollection == _collection,166 "Wrong RFT collection"167 );168 UniqueRefungible rftCollectionContract = UniqueRefungible(rftCollection);169 address rftTokenAddress = rftCollectionContract.tokenContractAddress(_token);170 Token memory nftToken = rft2nftMapping[rftTokenAddress];171 require(172 nftToken._collection != address(0),173 "No corresponding NFT token found"174 );175 UniqueRefungibleToken rftTokenContract = UniqueRefungibleToken(rftTokenAddress);176 require(177 rftTokenContract.balanceOf(msg.sender) == rftTokenContract.totalSupply(),178 "Not all pieces are owned by the caller"179 );180 rftCollectionContract.transferFrom(msg.sender, address(this), _token);181 UniqueNFT(nftToken._collection).transferFrom(182 address(this),183 msg.sender,184 nftToken._tokenId185 );186 emit Defractionalized(rftTokenAddress, nftToken._collection, nftToken._tokenId);187 }188}tests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth--- a/tests/src/eth/fractionalizer/fractionalizer.test.ts
+++ b/tests/src/eth/fractionalizer/fractionalizer.test.ts
@@ -223,6 +223,28 @@
},
});
});
+
+ itWeb3('Test fractionalizer NFT <-> RFT mapping ', async ({api, web3, privateKeyWrapper}) => {
+ const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+ const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+ const {rftTokenAddress, nftCollectionAddress, nftTokenId} = await createRFTToken(api, web3, owner, fractionalizer, 100n);
+
+ const {collectionId, tokenId} = tokenIdFromAddress(rftTokenAddress);
+ const refungibleAddress = collectionIdToAddress(collectionId);
+ expect(rftCollectionAddress).to.be.equal(refungibleAddress);
+ const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
+ await refungibleTokenContract.methods.approve(fractionalizer.options.address, 100).send();
+
+ const rft2nft = await fractionalizer.methods.rft2nftMapping(rftTokenAddress).call();
+ expect(rft2nft).to.be.like({
+ _collection: nftCollectionAddress,
+ _tokenId: nftTokenId,
+ });
+
+ const nft2rft = await fractionalizer.methods.nft2rftMapping(nftCollectionAddress, nftTokenId).call();
+ expect(nft2rft).to.be.eq(tokenId.toString());
+ });
});
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -655,31 +655,6 @@
await requirePallets(this, [Pallets.ReFungible]);
});
- itWeb3('Parent NFT token address and id', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
- 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();
- const nftCollectionId = collectionIdFromAddress(nftCollectionAddress);
-
- const {collectionIdAddress, collectionId} = await createRefungibleCollection(api, web3, owner);
- const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);
- const refungibleTokenId = await refungibleContract.methods.nextTokenId().call();
- await refungibleContract.methods.mint(owner, refungibleTokenId).send();
-
- const rftTokenAddress = tokenIdToAddress(collectionId, refungibleTokenId);
- const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
- await refungibleTokenContract.methods.setParentNFT(nftCollectionAddress, nftTokenId).send();
-
- const tokenAddress = await refungibleTokenContract.methods.parentToken().call();
- const tokenId = await refungibleTokenContract.methods.parentTokenId().call();
- const nftTokenAddress = tokenIdToAddress(nftCollectionId, nftTokenId);
- expect(tokenAddress).to.be.equal(nftTokenAddress);
- expect(tokenId).to.be.equal(nftTokenId);
- });
-
itWeb3('Default parent token address and id', async ({api, web3, privateKeyWrapper}) => {
const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
@@ -693,7 +668,7 @@
const tokenAddress = await refungibleTokenContract.methods.parentToken().call();
const tokenId = await refungibleTokenContract.methods.parentTokenId().call();
- expect(tokenAddress).to.be.equal(rftTokenAddress);
+ expect(tokenAddress).to.be.equal(collectionIdAddress);
expect(tokenId).to.be.equal(refungibleTokenId);
});
});
tests/src/eth/reFungibleTokenAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleTokenAbi.json
+++ b/tests/src/eth/reFungibleTokenAbi.json
@@ -127,16 +127,6 @@
},
{
"inputs": [
- { "internalType": "address", "name": "collection", "type": "address" },
- { "internalType": "uint256", "name": "nftId", "type": "uint256" }
- ],
- "name": "setParentNFT",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
{ "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
],
"name": "supportsInterface",