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.soldiffbeforeafterboth--- a/tests/src/eth/fractionalizer/Fractionalizer.sol
+++ b/tests/src/eth/fractionalizer/Fractionalizer.sol
@@ -16,8 +16,8 @@
}
address rftCollection;
mapping(address => bool) nftCollectionAllowList;
- mapping(address => mapping(uint256 => uint256)) nft2rftMapping;
- mapping(address => Token) rft2nftMapping;
+ mapping(address => mapping(uint256 => uint256)) public nft2rftMapping;
+ mapping(address => Token) public rft2nftMapping;
bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));
receive() external payable onlyOwner {}
@@ -137,7 +137,6 @@
rft2nftMapping[rftTokenAddress] = Token(_collection, _token);
rftTokenContract = UniqueRefungibleToken(rftTokenAddress);
- rftTokenContract.setParentNFT(_collection, _token);
} else {
rftTokenId = nft2rftMapping[_collection][_token];
rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);
tests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth1// 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/>.161718import Web3 from 'web3';19import {ApiPromise} from '@polkadot/api';20import {evmToAddress} from '@polkadot/util-crypto';21import {readFile} from 'fs/promises';22import {executeTransaction, submitTransactionAsync} from '../../substrate/substrate-api';23import {getCreateCollectionResult, getCreateItemResult, UNIQUE, requirePallets, Pallets} from '../../util/helpers';24import {collectionIdToAddress, CompiledContract, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, GAS_ARGS, itWeb3, tokenIdFromAddress, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from '../util/helpers';25import {Contract} from 'web3-eth-contract';26import * as solc from 'solc';2728import chai from 'chai';29import chaiLike from 'chai-like';30import {IKeyringPair} from '@polkadot/types/types';31chai.use(chaiLike);32const expect = chai.expect;33let fractionalizer: CompiledContract;3435async function compileFractionalizer() {36 if (!fractionalizer) {37 const input = {38 language: 'Solidity',39 sources: {40 ['Fractionalizer.sol']: {41 content: (await readFile(`${__dirname}/Fractionalizer.sol`)).toString(),42 },43 },44 settings: {45 outputSelection: {46 '*': {47 '*': ['*'],48 },49 },50 },51 };52 const json = JSON.parse(solc.compile(JSON.stringify(input), {import: await findImports()}));53 const out = json.contracts['Fractionalizer.sol']['Fractionalizer'];5455 fractionalizer = {56 abi: out.abi,57 object: '0x' + out.evm.bytecode.object,58 };59 }60 return fractionalizer;61}6263async function findImports() {64 const collectionHelpers = (await readFile(`${__dirname}/../api/CollectionHelpers.sol`)).toString();65 const contractHelpers = (await readFile(`${__dirname}/../api/ContractHelpers.sol`)).toString();66 const uniqueRefungibleToken = (await readFile(`${__dirname}/../api/UniqueRefungibleToken.sol`)).toString();67 const uniqueRefungible = (await readFile(`${__dirname}/../api/UniqueRefungible.sol`)).toString();68 const uniqueNFT = (await readFile(`${__dirname}/../api/UniqueNFT.sol`)).toString();6970 return function(path: string) {71 switch (path) {72 case 'api/CollectionHelpers.sol': return {contents: `${collectionHelpers}`};73 case 'api/ContractHelpers.sol': return {contents: `${contractHelpers}`};74 case 'api/UniqueRefungibleToken.sol': return {contents: `${uniqueRefungibleToken}`};75 case 'api/UniqueRefungible.sol': return {contents: `${uniqueRefungible}`};76 case 'api/UniqueNFT.sol': return {contents: `${uniqueNFT}`};77 default: return {error: 'File not found'};78 }79 };80}8182async function deployFractionalizer(web3: Web3, owner: string) {83 const compiled = await compileFractionalizer();84 const fractionalizerContract = new web3.eth.Contract(compiled.abi, undefined, {85 data: compiled.object,86 from: owner,87 ...GAS_ARGS,88 });89 return await fractionalizerContract.deploy({data: compiled.object}).send({from: owner});90}9192async function initFractionalizer(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair, owner: string) {93 const fractionalizer = await deployFractionalizer(web3, owner);94 const amount = 10n * UNIQUE;95 await web3.eth.sendTransaction({from: owner, to: fractionalizer.options.address, value: `${amount}`, ...GAS_ARGS});96 const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send();97 const rftCollectionAddress = result.events.RFTCollectionSet.returnValues._collection;98 return {fractionalizer, rftCollectionAddress};99}100101async function createRFTToken(api: ApiPromise, web3: Web3, owner: string, fractionalizer: Contract, amount: bigint) {102 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);103 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);104 const nftTokenId = await nftContract.methods.nextTokenId().call();105 await nftContract.methods.mint(owner, nftTokenId).send();106107 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();108 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();109 const result = await fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, amount).send();110 const {_collection, _tokenId, _rftToken} = result.events.Fractionalized.returnValues;111 return {112 nftCollectionAddress: _collection,113 nftTokenId: _tokenId,114 rftTokenAddress: _rftToken,115 };116}117118describe('Fractionalizer contract usage', () => {119 before(async function() {120 await requirePallets(this, [Pallets.ReFungible]);121 });122123 itWeb3('Set RFT collection', async ({api, web3, privateKeyWrapper}) => {124 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);125 const fractionalizer = await deployFractionalizer(web3, owner);126 const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);127 const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);128 await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();129 const result = await fractionalizer.methods.setRFTCollection(collectionIdAddress).send();130 expect(result.events).to.be.like({131 RFTCollectionSet: {132 returnValues: {133 _collection: collectionIdAddress,134 },135 },136 });137 });138139 itWeb3('Mint RFT collection', async ({api, web3, privateKeyWrapper}) => {140 const alice = privateKeyWrapper('//Alice');141 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);142 const fractionalizer = await deployFractionalizer(web3, owner);143 const tx = api.tx.balances.transfer(evmToAddress(fractionalizer.options.address), 10n * UNIQUE);144 await submitTransactionAsync(alice, tx);145146 const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send({from: owner});147 expect(result.events).to.be.like({148 RFTCollectionSet: {},149 });150 expect(result.events.RFTCollectionSet.returnValues._collection).to.be.ok;151 });152153 itWeb3('Set Allowlist', async ({api, web3, privateKeyWrapper}) => {154 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);155 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);156 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);157 const result1 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send({from: owner});158 expect(result1.events).to.be.like({159 AllowListSet: {160 returnValues: {161 _collection: nftCollectionAddress,162 _status: true,163 },164 },165 });166 const result2 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, false).send({from: owner});167 expect(result2.events).to.be.like({168 AllowListSet: {169 returnValues: {170 _collection: nftCollectionAddress,171 _status: false,172 },173 },174 });175 });176177 itWeb3('NFT to RFT', async ({api, web3, privateKeyWrapper}) => {178 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);179180 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);181 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);182 const nftTokenId = await nftContract.methods.nextTokenId().call();183 await nftContract.methods.mint(owner, nftTokenId).send();184185 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);186187 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();188 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();189 const result = await fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).send();190 expect(result.events).to.be.like({191 Fractionalized: {192 returnValues: {193 _collection: nftCollectionAddress,194 _tokenId: nftTokenId,195 _amount: '100',196 },197 },198 });199 const rftTokenAddress = result.events.Fractionalized.returnValues._rftToken;200 const rftTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);201 expect(await rftTokenContract.methods.balanceOf(owner).call()).to.equal('100');202 });203204 itWeb3('RFT to NFT', async ({api, web3, privateKeyWrapper}) => {205 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);206207 const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);208 const {rftTokenAddress, nftCollectionAddress, nftTokenId} = await createRFTToken(api, web3, owner, fractionalizer, 100n);209210 const {collectionId, tokenId} = tokenIdFromAddress(rftTokenAddress);211 const refungibleAddress = collectionIdToAddress(collectionId);212 expect(rftCollectionAddress).to.be.equal(refungibleAddress);213 const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);214 await refungibleTokenContract.methods.approve(fractionalizer.options.address, 100).send();215 const result = await fractionalizer.methods.rft2nft(refungibleAddress, tokenId).send();216 expect(result.events).to.be.like({217 Defractionalized: {218 returnValues: {219 _rftToken: rftTokenAddress,220 _nftCollection: nftCollectionAddress,221 _nftTokenId: nftTokenId,222 },223 },224 });225 });226});227228229230describe('Negative Integration Tests for fractionalizer', () => {231 before(async function() {232 await requirePallets(this, [Pallets.ReFungible]);233 });234235 itWeb3('call setRFTCollection twice', async ({api, web3, privateKeyWrapper}) => {236 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);237 const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);238 const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);239240 const fractionalizer = await deployFractionalizer(web3, owner);241 await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();242 await fractionalizer.methods.setRFTCollection(collectionIdAddress).send();243244 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())245 .to.be.rejectedWith(/RFT collection is already set$/g);246 });247248 itWeb3('call setRFTCollection with NFT collection', async ({api, web3, privateKeyWrapper}) => {249 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);250 const {collectionIdAddress} = await createNonfungibleCollection(api, web3, owner);251 const nftContract = uniqueNFT(web3, collectionIdAddress, owner);252253 const fractionalizer = await deployFractionalizer(web3, owner);254 await nftContract.methods.addCollectionAdmin(fractionalizer.options.address).send();255256 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())257 .to.be.rejectedWith(/Wrong collection type. Collection is not refungible.$/g);258 });259260 itWeb3('call setRFTCollection while not collection admin', async ({api, web3, privateKeyWrapper}) => {261 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);262 const fractionalizer = await deployFractionalizer(web3, owner);263 const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);264265 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())266 .to.be.rejectedWith(/Fractionalizer contract should be an admin of the collection$/g);267 });268269 itWeb3('call setRFTCollection after createAndSetRFTCollection', async ({api, web3, privateKeyWrapper}) => {270 const alice = privateKeyWrapper('//Alice');271 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);272 const fractionalizer = await deployFractionalizer(web3, owner);273 const tx = api.tx.balances.transfer(evmToAddress(fractionalizer.options.address), 10n * UNIQUE);274 await submitTransactionAsync(alice, tx);275276 const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send({from: owner});277 const collectionIdAddress = result.events.RFTCollectionSet.returnValues._collection;278279 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())280 .to.be.rejectedWith(/RFT collection is already set$/g);281 });282283 itWeb3('call nft2rft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {284 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);285286 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);287 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);288 const nftTokenId = await nftContract.methods.nextTokenId().call();289 await nftContract.methods.mint(owner, nftTokenId).send();290291 const fractionalizer = await deployFractionalizer(web3, owner);292293 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())294 .to.be.rejectedWith(/RFT collection is not set$/g);295 });296297 itWeb3('call nft2rft while not owner of NFT token', async ({api, web3, privateKeyWrapper}) => {298 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);299 const nftOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);300301 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);302 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);303 const nftTokenId = await nftContract.methods.nextTokenId().call();304 await nftContract.methods.mint(owner, nftTokenId).send();305 await nftContract.methods.transfer(nftOwner, 1).send();306307308 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);309 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();310311 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())312 .to.be.rejectedWith(/Only token owner could fractionalize it$/g);313 });314315 itWeb3('call nft2rft while not in list of allowed accounts', async ({api, web3, privateKeyWrapper}) => {316 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);317318 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);319 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);320 const nftTokenId = await nftContract.methods.nextTokenId().call();321 await nftContract.methods.mint(owner, nftTokenId).send();322323 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);324325 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();326 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())327 .to.be.rejectedWith(/Fractionalization of this collection is not allowed by admin$/g);328 });329330 itWeb3('call nft2rft while fractionalizer doesnt have approval for nft token', async ({api, web3, privateKeyWrapper}) => {331 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);332333 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);334 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);335 const nftTokenId = await nftContract.methods.nextTokenId().call();336 await nftContract.methods.mint(owner, nftTokenId).send();337338 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);339340 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();341 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())342 .to.be.rejectedWith(/ApprovedValueTooLow$/g);343 });344345 itWeb3('call rft2nft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {346 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);347348 const fractionalizer = await deployFractionalizer(web3, owner);349 const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);350 const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);351 const rftTokenId = await refungibleContract.methods.nextTokenId().call();352 await refungibleContract.methods.mint(owner, rftTokenId).send();353 354 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())355 .to.be.rejectedWith(/RFT collection is not set$/g);356 });357358 itWeb3('call rft2nft for RFT token that is not from configured RFT collection', async ({api, web3, privateKeyWrapper}) => {359 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);360361 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);362 const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);363 const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);364 const rftTokenId = await refungibleContract.methods.nextTokenId().call();365 await refungibleContract.methods.mint(owner, rftTokenId).send();366 367 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())368 .to.be.rejectedWith(/Wrong RFT collection$/g);369 });370371 itWeb3('call rft2nft for RFT token that was not minted by fractionalizer contract', async ({api, web3, privateKeyWrapper}) => {372 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);373 const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);374375 const fractionalizer = await deployFractionalizer(web3, owner);376 const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);377378 await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();379 await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send();380381 const rftTokenId = await refungibleContract.methods.nextTokenId().call();382 await refungibleContract.methods.mint(owner, rftTokenId).send();383 384 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())385 .to.be.rejectedWith(/No corresponding NFT token found$/g);386 });387388 itWeb3('call rft2nft without owning all RFT pieces', async ({api, web3, privateKeyWrapper}) => {389 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);390 const receiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);391392 const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);393 const {rftTokenAddress} = await createRFTToken(api, web3, owner, fractionalizer, 100n);394 395 const {tokenId} = tokenIdFromAddress(rftTokenAddress);396 const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);397 await refungibleTokenContract.methods.transfer(receiver, 50).send();398 await refungibleTokenContract.methods.approve(fractionalizer.options.address, 50).send();399 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, tokenId).call())400 .to.be.rejectedWith(/Not all pieces are owned by the caller$/g);401 });402403 itWeb3('send QTZ/UNQ to contract from non owner', async ({api, web3, privateKeyWrapper}) => {404 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);405 const payer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);406407 const fractionalizer = await deployFractionalizer(web3, owner);408 const amount = 10n * UNIQUE;409 await expect(web3.eth.sendTransaction({from: payer, to: fractionalizer.options.address, value: `${amount}`, ...GAS_ARGS})).to.be.rejected;410 });411412 itWeb3('fractionalize NFT with NFT transfers disallowed', async ({api, web3, privateKeyWrapper}) => {413 const alice = privateKeyWrapper('//Alice');414 let collectionId;415 {416 const tx = api.tx.unique.createCollectionEx({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});417 const events = await submitTransactionAsync(alice, tx);418 const result = getCreateCollectionResult(events);419 collectionId = result.collectionId;420 }421 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);422 let nftTokenId;423 {424 const createData = {nft: {}};425 const tx = api.tx.unique.createItem(collectionId, {Ethereum: owner}, createData as any);426 const events = await executeTransaction(api, alice, tx);427 const result = getCreateItemResult(events);428 nftTokenId = result.itemId;429 }430 {431 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, false);432 await executeTransaction(api, alice, tx);433 }434 const nftCollectionAddress = collectionIdToAddress(collectionId);435 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);436 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();437438 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);439 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();440 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())441 .to.be.rejectedWith(/TransferNotAllowed$/g);442 });443 444 itWeb3('fractionalize NFT with RFT transfers disallowed', async ({api, web3, privateKeyWrapper}) => {445 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);446 const alice = privateKeyWrapper('//Alice');447448 let collectionId;449 {450 const tx = api.tx.unique.createCollectionEx({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'ReFungible'});451 const events = await submitTransactionAsync(alice, tx);452 const result = getCreateCollectionResult(events);453 collectionId = result.collectionId;454 }455 const rftCollectionAddress = collectionIdToAddress(collectionId);456 const fractionalizer = await deployFractionalizer(web3, owner);457 {458 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: fractionalizer.options.address});459 await submitTransactionAsync(alice, changeAdminTx);460 }461 await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send();462 {463 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, false);464 await executeTransaction(api, alice, tx);465 }466467 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);468 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);469 const nftTokenId = await nftContract.methods.nextTokenId().call();470 await nftContract.methods.mint(owner, nftTokenId).send();471472 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();473 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();474475 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100n).call())476 .to.be.rejectedWith(/TransferNotAllowed$/g);477 });478});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/>.161718import Web3 from 'web3';19import {ApiPromise} from '@polkadot/api';20import {evmToAddress} from '@polkadot/util-crypto';21import {readFile} from 'fs/promises';22import {executeTransaction, submitTransactionAsync} from '../../substrate/substrate-api';23import {getCreateCollectionResult, getCreateItemResult, UNIQUE, requirePallets, Pallets} from '../../util/helpers';24import {collectionIdToAddress, CompiledContract, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, GAS_ARGS, itWeb3, tokenIdFromAddress, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from '../util/helpers';25import {Contract} from 'web3-eth-contract';26import * as solc from 'solc';2728import chai from 'chai';29import chaiLike from 'chai-like';30import {IKeyringPair} from '@polkadot/types/types';31chai.use(chaiLike);32const expect = chai.expect;33let fractionalizer: CompiledContract;3435async function compileFractionalizer() {36 if (!fractionalizer) {37 const input = {38 language: 'Solidity',39 sources: {40 ['Fractionalizer.sol']: {41 content: (await readFile(`${__dirname}/Fractionalizer.sol`)).toString(),42 },43 },44 settings: {45 outputSelection: {46 '*': {47 '*': ['*'],48 },49 },50 },51 };52 const json = JSON.parse(solc.compile(JSON.stringify(input), {import: await findImports()}));53 const out = json.contracts['Fractionalizer.sol']['Fractionalizer'];5455 fractionalizer = {56 abi: out.abi,57 object: '0x' + out.evm.bytecode.object,58 };59 }60 return fractionalizer;61}6263async function findImports() {64 const collectionHelpers = (await readFile(`${__dirname}/../api/CollectionHelpers.sol`)).toString();65 const contractHelpers = (await readFile(`${__dirname}/../api/ContractHelpers.sol`)).toString();66 const uniqueRefungibleToken = (await readFile(`${__dirname}/../api/UniqueRefungibleToken.sol`)).toString();67 const uniqueRefungible = (await readFile(`${__dirname}/../api/UniqueRefungible.sol`)).toString();68 const uniqueNFT = (await readFile(`${__dirname}/../api/UniqueNFT.sol`)).toString();6970 return function(path: string) {71 switch (path) {72 case 'api/CollectionHelpers.sol': return {contents: `${collectionHelpers}`};73 case 'api/ContractHelpers.sol': return {contents: `${contractHelpers}`};74 case 'api/UniqueRefungibleToken.sol': return {contents: `${uniqueRefungibleToken}`};75 case 'api/UniqueRefungible.sol': return {contents: `${uniqueRefungible}`};76 case 'api/UniqueNFT.sol': return {contents: `${uniqueNFT}`};77 default: return {error: 'File not found'};78 }79 };80}8182async function deployFractionalizer(web3: Web3, owner: string) {83 const compiled = await compileFractionalizer();84 const fractionalizerContract = new web3.eth.Contract(compiled.abi, undefined, {85 data: compiled.object,86 from: owner,87 ...GAS_ARGS,88 });89 return await fractionalizerContract.deploy({data: compiled.object}).send({from: owner});90}9192async function initFractionalizer(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair, owner: string) {93 const fractionalizer = await deployFractionalizer(web3, owner);94 const amount = 10n * UNIQUE;95 await web3.eth.sendTransaction({from: owner, to: fractionalizer.options.address, value: `${amount}`, ...GAS_ARGS});96 const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send();97 const rftCollectionAddress = result.events.RFTCollectionSet.returnValues._collection;98 return {fractionalizer, rftCollectionAddress};99}100101async function createRFTToken(api: ApiPromise, web3: Web3, owner: string, fractionalizer: Contract, amount: bigint) {102 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);103 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);104 const nftTokenId = await nftContract.methods.nextTokenId().call();105 await nftContract.methods.mint(owner, nftTokenId).send();106107 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();108 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();109 const result = await fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, amount).send();110 const {_collection, _tokenId, _rftToken} = result.events.Fractionalized.returnValues;111 return {112 nftCollectionAddress: _collection,113 nftTokenId: _tokenId,114 rftTokenAddress: _rftToken,115 };116}117118describe('Fractionalizer contract usage', () => {119 before(async function() {120 await requirePallets(this, [Pallets.ReFungible]);121 });122123 itWeb3('Set RFT collection', async ({api, web3, privateKeyWrapper}) => {124 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);125 const fractionalizer = await deployFractionalizer(web3, owner);126 const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);127 const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);128 await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();129 const result = await fractionalizer.methods.setRFTCollection(collectionIdAddress).send();130 expect(result.events).to.be.like({131 RFTCollectionSet: {132 returnValues: {133 _collection: collectionIdAddress,134 },135 },136 });137 });138139 itWeb3('Mint RFT collection', async ({api, web3, privateKeyWrapper}) => {140 const alice = privateKeyWrapper('//Alice');141 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);142 const fractionalizer = await deployFractionalizer(web3, owner);143 const tx = api.tx.balances.transfer(evmToAddress(fractionalizer.options.address), 10n * UNIQUE);144 await submitTransactionAsync(alice, tx);145146 const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send({from: owner});147 expect(result.events).to.be.like({148 RFTCollectionSet: {},149 });150 expect(result.events.RFTCollectionSet.returnValues._collection).to.be.ok;151 });152153 itWeb3('Set Allowlist', async ({api, web3, privateKeyWrapper}) => {154 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);155 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);156 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);157 const result1 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send({from: owner});158 expect(result1.events).to.be.like({159 AllowListSet: {160 returnValues: {161 _collection: nftCollectionAddress,162 _status: true,163 },164 },165 });166 const result2 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, false).send({from: owner});167 expect(result2.events).to.be.like({168 AllowListSet: {169 returnValues: {170 _collection: nftCollectionAddress,171 _status: false,172 },173 },174 });175 });176177 itWeb3('NFT to RFT', async ({api, web3, privateKeyWrapper}) => {178 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);179180 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);181 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);182 const nftTokenId = await nftContract.methods.nextTokenId().call();183 await nftContract.methods.mint(owner, nftTokenId).send();184185 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);186187 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();188 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();189 const result = await fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).send();190 expect(result.events).to.be.like({191 Fractionalized: {192 returnValues: {193 _collection: nftCollectionAddress,194 _tokenId: nftTokenId,195 _amount: '100',196 },197 },198 });199 const rftTokenAddress = result.events.Fractionalized.returnValues._rftToken;200 const rftTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);201 expect(await rftTokenContract.methods.balanceOf(owner).call()).to.equal('100');202 });203204 itWeb3('RFT to NFT', async ({api, web3, privateKeyWrapper}) => {205 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);206207 const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);208 const {rftTokenAddress, nftCollectionAddress, nftTokenId} = await createRFTToken(api, web3, owner, fractionalizer, 100n);209210 const {collectionId, tokenId} = tokenIdFromAddress(rftTokenAddress);211 const refungibleAddress = collectionIdToAddress(collectionId);212 expect(rftCollectionAddress).to.be.equal(refungibleAddress);213 const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);214 await refungibleTokenContract.methods.approve(fractionalizer.options.address, 100).send();215 const result = await fractionalizer.methods.rft2nft(refungibleAddress, tokenId).send();216 expect(result.events).to.be.like({217 Defractionalized: {218 returnValues: {219 _rftToken: rftTokenAddress,220 _nftCollection: nftCollectionAddress,221 _nftTokenId: nftTokenId,222 },223 },224 });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 });248});249250251252describe('Negative Integration Tests for fractionalizer', () => {253 before(async function() {254 await requirePallets(this, [Pallets.ReFungible]);255 });256257 itWeb3('call setRFTCollection twice', async ({api, web3, privateKeyWrapper}) => {258 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);259 const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);260 const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);261262 const fractionalizer = await deployFractionalizer(web3, owner);263 await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();264 await fractionalizer.methods.setRFTCollection(collectionIdAddress).send();265266 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())267 .to.be.rejectedWith(/RFT collection is already set$/g);268 });269270 itWeb3('call setRFTCollection with NFT collection', async ({api, web3, privateKeyWrapper}) => {271 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);272 const {collectionIdAddress} = await createNonfungibleCollection(api, web3, owner);273 const nftContract = uniqueNFT(web3, collectionIdAddress, owner);274275 const fractionalizer = await deployFractionalizer(web3, owner);276 await nftContract.methods.addCollectionAdmin(fractionalizer.options.address).send();277278 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())279 .to.be.rejectedWith(/Wrong collection type. Collection is not refungible.$/g);280 });281282 itWeb3('call setRFTCollection while not collection admin', async ({api, web3, privateKeyWrapper}) => {283 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);284 const fractionalizer = await deployFractionalizer(web3, owner);285 const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);286287 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())288 .to.be.rejectedWith(/Fractionalizer contract should be an admin of the collection$/g);289 });290291 itWeb3('call setRFTCollection after createAndSetRFTCollection', async ({api, web3, privateKeyWrapper}) => {292 const alice = privateKeyWrapper('//Alice');293 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);294 const fractionalizer = await deployFractionalizer(web3, owner);295 const tx = api.tx.balances.transfer(evmToAddress(fractionalizer.options.address), 10n * UNIQUE);296 await submitTransactionAsync(alice, tx);297298 const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send({from: owner});299 const collectionIdAddress = result.events.RFTCollectionSet.returnValues._collection;300301 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())302 .to.be.rejectedWith(/RFT collection is already set$/g);303 });304305 itWeb3('call nft2rft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {306 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);307308 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);309 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);310 const nftTokenId = await nftContract.methods.nextTokenId().call();311 await nftContract.methods.mint(owner, nftTokenId).send();312313 const fractionalizer = await deployFractionalizer(web3, owner);314315 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())316 .to.be.rejectedWith(/RFT collection is not set$/g);317 });318319 itWeb3('call nft2rft while not owner of NFT token', async ({api, web3, privateKeyWrapper}) => {320 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);321 const nftOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);322323 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);324 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);325 const nftTokenId = await nftContract.methods.nextTokenId().call();326 await nftContract.methods.mint(owner, nftTokenId).send();327 await nftContract.methods.transfer(nftOwner, 1).send();328329330 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);331 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();332333 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())334 .to.be.rejectedWith(/Only token owner could fractionalize it$/g);335 });336337 itWeb3('call nft2rft while not in list of allowed accounts', async ({api, web3, privateKeyWrapper}) => {338 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);339340 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);341 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);342 const nftTokenId = await nftContract.methods.nextTokenId().call();343 await nftContract.methods.mint(owner, nftTokenId).send();344345 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);346347 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();348 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())349 .to.be.rejectedWith(/Fractionalization of this collection is not allowed by admin$/g);350 });351352 itWeb3('call nft2rft while fractionalizer doesnt have approval for nft token', async ({api, web3, privateKeyWrapper}) => {353 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);354355 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);356 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);357 const nftTokenId = await nftContract.methods.nextTokenId().call();358 await nftContract.methods.mint(owner, nftTokenId).send();359360 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);361362 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();363 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())364 .to.be.rejectedWith(/ApprovedValueTooLow$/g);365 });366367 itWeb3('call rft2nft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {368 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);369370 const fractionalizer = await deployFractionalizer(web3, owner);371 const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);372 const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);373 const rftTokenId = await refungibleContract.methods.nextTokenId().call();374 await refungibleContract.methods.mint(owner, rftTokenId).send();375 376 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())377 .to.be.rejectedWith(/RFT collection is not set$/g);378 });379380 itWeb3('call rft2nft for RFT token that is not from configured RFT collection', async ({api, web3, privateKeyWrapper}) => {381 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);382383 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);384 const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);385 const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);386 const rftTokenId = await refungibleContract.methods.nextTokenId().call();387 await refungibleContract.methods.mint(owner, rftTokenId).send();388 389 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())390 .to.be.rejectedWith(/Wrong RFT collection$/g);391 });392393 itWeb3('call rft2nft for RFT token that was not minted by fractionalizer contract', async ({api, web3, privateKeyWrapper}) => {394 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);395 const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);396397 const fractionalizer = await deployFractionalizer(web3, owner);398 const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);399400 await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();401 await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send();402403 const rftTokenId = await refungibleContract.methods.nextTokenId().call();404 await refungibleContract.methods.mint(owner, rftTokenId).send();405 406 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())407 .to.be.rejectedWith(/No corresponding NFT token found$/g);408 });409410 itWeb3('call rft2nft without owning all RFT pieces', async ({api, web3, privateKeyWrapper}) => {411 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);412 const receiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);413414 const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);415 const {rftTokenAddress} = await createRFTToken(api, web3, owner, fractionalizer, 100n);416 417 const {tokenId} = tokenIdFromAddress(rftTokenAddress);418 const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);419 await refungibleTokenContract.methods.transfer(receiver, 50).send();420 await refungibleTokenContract.methods.approve(fractionalizer.options.address, 50).send();421 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, tokenId).call())422 .to.be.rejectedWith(/Not all pieces are owned by the caller$/g);423 });424425 itWeb3('send QTZ/UNQ to contract from non owner', async ({api, web3, privateKeyWrapper}) => {426 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);427 const payer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);428429 const fractionalizer = await deployFractionalizer(web3, owner);430 const amount = 10n * UNIQUE;431 await expect(web3.eth.sendTransaction({from: payer, to: fractionalizer.options.address, value: `${amount}`, ...GAS_ARGS})).to.be.rejected;432 });433434 itWeb3('fractionalize NFT with NFT transfers disallowed', async ({api, web3, privateKeyWrapper}) => {435 const alice = privateKeyWrapper('//Alice');436 let collectionId;437 {438 const tx = api.tx.unique.createCollectionEx({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});439 const events = await submitTransactionAsync(alice, tx);440 const result = getCreateCollectionResult(events);441 collectionId = result.collectionId;442 }443 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);444 let nftTokenId;445 {446 const createData = {nft: {}};447 const tx = api.tx.unique.createItem(collectionId, {Ethereum: owner}, createData as any);448 const events = await executeTransaction(api, alice, tx);449 const result = getCreateItemResult(events);450 nftTokenId = result.itemId;451 }452 {453 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, false);454 await executeTransaction(api, alice, tx);455 }456 const nftCollectionAddress = collectionIdToAddress(collectionId);457 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);458 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();459460 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);461 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();462 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())463 .to.be.rejectedWith(/TransferNotAllowed$/g);464 });465 466 itWeb3('fractionalize NFT with RFT transfers disallowed', async ({api, web3, privateKeyWrapper}) => {467 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);468 const alice = privateKeyWrapper('//Alice');469470 let collectionId;471 {472 const tx = api.tx.unique.createCollectionEx({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'ReFungible'});473 const events = await submitTransactionAsync(alice, tx);474 const result = getCreateCollectionResult(events);475 collectionId = result.collectionId;476 }477 const rftCollectionAddress = collectionIdToAddress(collectionId);478 const fractionalizer = await deployFractionalizer(web3, owner);479 {480 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: fractionalizer.options.address});481 await submitTransactionAsync(alice, changeAdminTx);482 }483 await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send();484 {485 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, false);486 await executeTransaction(api, alice, tx);487 }488489 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);490 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);491 const nftTokenId = await nftContract.methods.nextTokenId().call();492 await nftContract.methods.mint(owner, nftTokenId).send();493494 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();495 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();496497 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100n).call())498 .to.be.rejectedWith(/TransferNotAllowed$/g);499 });500});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",