difftreelog
chore add Fractionalizer contract documentation, prevent QTZ/UNQ transfers from nonowners, tests for TransfersNotAllowed
in: master
3 files changed
pallets/refungible/src/erc_token.rsdiffbeforeafterboth186 .weight_calls_budget(<StructureWeight<T>>::find_parent());186 .weight_calls_budget(<StructureWeight<T>>::find_parent());187187188 <Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)188 <Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)189 .map_err(|_| "transfer error")?;189 .map_err(dispatch_to_evm::<T>)?;190 Ok(true)190 Ok(true)191 }191 }192192tests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth6import {UniqueRefungible} from "../api/UniqueRefungible.sol";6import {UniqueRefungible} from "../api/UniqueRefungible.sol";7import {UniqueNFT} from "../api/UniqueNFT.sol";7import {UniqueNFT} from "../api/UniqueNFT.sol";889/// @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.9contract Fractionalizer {12contract Fractionalizer {10 struct Token {13 struct Token {11 address _collection;14 address _collection;17 mapping(address => Token) rft2nftMapping;20 mapping(address => Token) rft2nftMapping;18 bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));21 bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));192223 //TODO: add nonPayable modifier after Solidity updates to 0.9.20 constructor() {24 receive() external payable onlyOwner {}21 }252226 /// @dev Method modifier to only allow contract owner to call it.23 modifier onlyOwner() {27 modifier onlyOwner() {24 address contracthelpersAddress = 0x842899ECF380553E8a4de75bF534cdf6fBF64049;28 address contracthelpersAddress = 0x842899ECF380553E8a4de75bF534cdf6fBF64049;25 ContractHelpers contractHelpers = ContractHelpers(contracthelpersAddress);29 ContractHelpers contractHelpers = ContractHelpers(contracthelpersAddress);28 _;32 _;29 }33 }303435 /// @dev This emits when RFT collection setting is changed.31 event RFTCollectionSet(address _collection);36 event RFTCollectionSet(address _collection);3738 /// @dev This emits when NFT collection is allowed or disallowed.32 event AllowListSet(address _collection, bool _status);39 event AllowListSet(address _collection, bool _status);4041 /// @dev This emits when NFT token is fractionalized by contract.33 event Fractionalized(address _collection, uint256 _tokenId, address _rftToken, uint128 _amount);42 event Fractionalized(address _collection, uint256 _tokenId, address _rftToken, uint128 _amount);4344 /// @dev This emits when NFT token is defractionalized by contract.34 event Defractionalized(address _rftToken, address _nftCollection, uint256 _nftTokenId);45 event Defractionalized(address _rftToken, address _nftCollection, uint256 _nftTokenId);354647 /// Set RFT collection that contract will work with. RFT tokens for fractionalized NFT tokens48 /// would be created in this collection.49 /// @dev Throws if RFT collection is already configured for this contract.50 /// Throws if collection of wrong type (NFT, Fungible) is provided instead51 /// of RFT collection.52 /// Throws if `msg.sender` is not owner or admin of provided RFT collection.53 /// Can only be called by contract owner.54 /// @param _collection address of RFT collection.36 function setRFTCollection(address _collection) public onlyOwner {55 function setRFTCollection(address _collection) public onlyOwner {37 require(56 require(38 rftCollection == address(0),57 rftCollection == address(0),53 emit RFTCollectionSet(rftCollection);72 emit RFTCollectionSet(rftCollection);54 }73 }557475 /// Creates and sets RFT collection that contract will work with. RFT tokens for fractionalized NFT tokens76 /// would be created in this collection.77 /// @dev Throws if RFT collection is already configured for this contract.78 /// Can only be called by contract owner.79 /// @param _name name for created RFT collection.80 /// @param _description description for created RFT collection.81 /// @param _tokenPrefix token prefix for created RFT collection.56 function createAndSetRFTCollection(string calldata _name, string calldata _description, string calldata _tokenPrefix) public onlyOwner {82 function createAndSetRFTCollection(string calldata _name, string calldata _description, string calldata _tokenPrefix) public onlyOwner {57 require(83 require(58 rftCollection == address(0),84 rftCollection == address(0),63 emit RFTCollectionSet(rftCollection);89 emit RFTCollectionSet(rftCollection);64 }90 }659192 /// Allow or disallow NFT collection tokens from being fractionalized by this contract.93 /// @dev Can only be called by contract owner.94 /// @param collection NFT token address.95 /// @param status `true` to allow and `false` to disallow NFT token.66 function setNftCollectionIsAllowed(address collection, bool status) public onlyOwner {96 function setNftCollectionIsAllowed(address collection, bool status) public onlyOwner {67 nftCollectionAllowList[collection] = status;97 nftCollectionAllowList[collection] = status;68 emit AllowListSet(collection, status);98 emit AllowListSet(collection, status);69 }99 }70100101 /// Fractionilize NFT token.102 /// @dev Takes NFT token from `msg.sender` and transfers RFT token to `msg.sender`103 /// instead. Creates new RFT token if provided NFT token never was fractionalized104 /// by this contract or existing RFT token if it was.105 /// Throws if RFT collection isn't configured for this contract.106 /// Throws if fractionalization of provided NFT token is not allowed107 /// Throws if `msg.sender` is not owner of provided NFT token108 /// @param _collection NFT collection address109 /// @param _token id of NFT token to be fractionalized110 /// @param _pieces number of pieces new RFT token would have71 function nft2rft(address _collection, uint256 _token, uint128 _pieces) public {111 function nft2rft(address _collection, uint256 _token, uint128 _pieces) public {72 require(112 require(73 rftCollection != address(0),113 rftCollection != address(0),109 emit Fractionalized(_collection, _token, rftTokenAddress, _pieces);149 emit Fractionalized(_collection, _token, rftTokenAddress, _pieces);110 }150 }111151152 /// Defrationalize NFT token.153 /// @dev Takes RFT token from `msg.sender` and transfers corresponding NFT token154 /// to `msg.sender` instead.155 /// Throws if RFT collection isn't configured for this contract.156 /// Throws if provided RFT token is no from configured RFT collection.157 /// Throws if RFT token was not created by this contract.158 /// Throws if `msg.sender` isn't owner of all RFT token pieces.159 /// @param _collection RFT collection address160 /// @param _token id of RFT token112 function rft2nft(address _collection, uint256 _token) public {161 function rft2nft(address _collection, uint256 _token) public {113 require(162 require(114 rftCollection != address(0),163 rftCollection != address(0),tests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth19import {ApiPromise} from '@polkadot/api';19import {ApiPromise} from '@polkadot/api';20import {evmToAddress} from '@polkadot/util-crypto';20import {evmToAddress} from '@polkadot/util-crypto';21import {readFile} from 'fs/promises';21import {readFile} from 'fs/promises';22import {submitTransactionAsync} from '../../substrate/substrate-api';22import {executeTransaction, submitTransactionAsync} from '../../substrate/substrate-api';23import {UNIQUE} from '../../util/helpers';23import {getCreateCollectionResult, getCreateItemResult, UNIQUE} from '../../util/helpers';24import {collectionIdToAddress, CompiledContract, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, GAS_ARGS, itWeb3, tokenIdFromAddress, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} 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';25import {Contract} from 'web3-eth-contract';26import * as solc from 'solc';26import * as solc from 'solc';272728import chai from 'chai';28import chai from 'chai';29import chaiAsPromised from 'chai-as-promised';30import chaiLike from 'chai-like';29import chaiLike from 'chai-like';31import {IKeyringPair} from '@polkadot/types/types';30import {IKeyringPair} from '@polkadot/types/types';32chai.use(chaiAsPromised);33chai.use(chaiLike);31chai.use(chaiLike);34const expect = chai.expect;32const expect = chai.expect;35let fractionalizer: CompiledContract;33let fractionalizer: CompiledContract;939194async function initFractionalizer(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair, owner: string) {92async function initFractionalizer(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair, owner: string) {95 const fractionalizer = await deployFractionalizer(web3, owner);93 const fractionalizer = await deployFractionalizer(web3, owner);96 const tx = api.tx.balances.transfer(evmToAddress(fractionalizer.options.address), 10n * UNIQUE);94 const amount = 10n * UNIQUE;97 const alice = privateKeyWrapper('//Alice');95 await web3.eth.sendTransaction({from: owner, to: fractionalizer.options.address, value: `${amount}`, ...GAS_ARGS});98 await submitTransactionAsync(alice, tx);99 const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send();96 const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send();100 const rftCollectionAddress = result.events.RFTCollectionSet.returnValues._collection;97 const rftCollectionAddress = result.events.RFTCollectionSet.returnValues._collection;101 return {fractionalizer, rftCollectionAddress};98 return {fractionalizer, rftCollectionAddress};151148152 itWeb3('Set Allowlist', async ({api, web3, privateKeyWrapper}) => {149 itWeb3('Set Allowlist', async ({api, web3, privateKeyWrapper}) => {153 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);150 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);154 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner); 151 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);155156 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);152 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);157 const result1 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send({from: owner});153 const result1 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send({from: owner});238 await fractionalizer.methods.setRFTCollection(collectionIdAddress).send();234 await fractionalizer.methods.setRFTCollection(collectionIdAddress).send();239235240 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())236 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())241 .to.eventually.be.rejectedWith(/RFT collection is already set$/g);237 .to.be.rejectedWith(/RFT collection is already set$/g);242 });238 });243239244 itWeb3('call setRFTCollection with NFT collection', async ({api, web3, privateKeyWrapper}) => {240 itWeb3('call setRFTCollection with NFT collection', async ({api, web3, privateKeyWrapper}) => {250 await nftContract.methods.addCollectionAdmin(fractionalizer.options.address).send();246 await nftContract.methods.addCollectionAdmin(fractionalizer.options.address).send();251247252 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())248 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())253 .to.eventually.be.rejectedWith(/Wrong collection type. Collection is not refungible.$/g);249 .to.be.rejectedWith(/Wrong collection type. Collection is not refungible.$/g);254 });250 });255251256 itWeb3('call setRFTCollection while not collection admin', async ({api, web3, privateKeyWrapper}) => {252 itWeb3('call setRFTCollection while not collection admin', async ({api, web3, privateKeyWrapper}) => {259 const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);255 const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);260256261 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())257 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())262 .to.eventually.be.rejectedWith(/Fractionalizer contract should be an admin of the collection$/g);258 .to.be.rejectedWith(/Fractionalizer contract should be an admin of the collection$/g);263 });259 });264260265 itWeb3('call setRFTCollection after createAndSetRFTCollection', async ({api, web3, privateKeyWrapper}) => {261 itWeb3('call setRFTCollection after createAndSetRFTCollection', async ({api, web3, privateKeyWrapper}) => {273 const collectionIdAddress = result.events.RFTCollectionSet.returnValues._collection;269 const collectionIdAddress = result.events.RFTCollectionSet.returnValues._collection;274270275 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())271 await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())276 .to.eventually.be.rejectedWith(/RFT collection is already set$/g);272 .to.be.rejectedWith(/RFT collection is already set$/g);277 });273 });278274279 itWeb3('call nft2rft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {275 itWeb3('call nft2rft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {287 const fractionalizer = await deployFractionalizer(web3, owner);283 const fractionalizer = await deployFractionalizer(web3, owner);288284289 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())285 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())290 .to.eventually.be.rejectedWith(/RFT collection is not set$/g);286 .to.be.rejectedWith(/RFT collection is not set$/g);291 });287 });292288293 itWeb3('call nft2rft while not owner of NFT token', async ({api, web3, privateKeyWrapper}) => {289 itWeb3('call nft2rft while not owner of NFT token', async ({api, web3, privateKeyWrapper}) => {305 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();301 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();306302307 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())303 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())308 .to.eventually.be.rejectedWith(/Only token owner could fractionalize it$/g);304 .to.be.rejectedWith(/Only token owner could fractionalize it$/g);309 });305 });310306311 itWeb3('call nft2rft while not in list of allowed accounts', async ({api, web3, privateKeyWrapper}) => {307 itWeb3('call nft2rft while not in list of allowed accounts', async ({api, web3, privateKeyWrapper}) => {320316321 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();317 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();322 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())318 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())323 .to.eventually.be.rejectedWith(/Fractionalization of this collection is not allowed by admin$/g);319 .to.be.rejectedWith(/Fractionalization of this collection is not allowed by admin$/g);324 });320 });325321326 itWeb3('call nft2rft while fractionalizer doesnt have approval for nft token', async ({api, web3, privateKeyWrapper}) => {322 itWeb3('call nft2rft while fractionalizer doesnt have approval for nft token', async ({api, web3, privateKeyWrapper}) => {335331336 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();332 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();337 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())333 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())338 .to.eventually.be.rejectedWith(/ApprovedValueTooLow$/g);334 .to.be.rejectedWith(/ApprovedValueTooLow$/g);339 });335 });340336341 itWeb3('call rft2nft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {337 itWeb3('call rft2nft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {348 await refungibleContract.methods.mint(owner, rftTokenId).send();344 await refungibleContract.methods.mint(owner, rftTokenId).send();349 345 350 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())346 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())351 .to.eventually.be.rejectedWith(/RFT collection is not set$/g);347 .to.be.rejectedWith(/RFT collection is not set$/g);352 });348 });353349354 itWeb3('call rft2nft for RFT token that is not from configured RFT collection', async ({api, web3, privateKeyWrapper}) => {350 itWeb3('call rft2nft for RFT token that is not from configured RFT collection', async ({api, web3, privateKeyWrapper}) => {361 await refungibleContract.methods.mint(owner, rftTokenId).send();357 await refungibleContract.methods.mint(owner, rftTokenId).send();362 358 363 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())359 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())364 .to.eventually.be.rejectedWith(/Wrong RFT collection$/g);360 .to.be.rejectedWith(/Wrong RFT collection$/g);365 });361 });366362367 itWeb3('call rft2nft for RFT token that was not minted by fractionalizer contract', async ({api, web3, privateKeyWrapper}) => {363 itWeb3('call rft2nft for RFT token that was not minted by fractionalizer contract', async ({api, web3, privateKeyWrapper}) => {378 await refungibleContract.methods.mint(owner, rftTokenId).send();374 await refungibleContract.methods.mint(owner, rftTokenId).send();379 375 380 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())376 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())381 .to.eventually.be.rejectedWith(/No corresponding NFT token found$/g);377 .to.be.rejectedWith(/No corresponding NFT token found$/g);382 });378 });383379384 itWeb3('call rft2nft without owning all RFT pieces', async ({api, web3, privateKeyWrapper}) => {380 itWeb3('call rft2nft without owning all RFT pieces', async ({api, web3, privateKeyWrapper}) => {393 await refungibleTokenContract.methods.transfer(receiver, 50).send();389 await refungibleTokenContract.methods.transfer(receiver, 50).send();394 await refungibleTokenContract.methods.approve(fractionalizer.options.address, 50).send();390 await refungibleTokenContract.methods.approve(fractionalizer.options.address, 50).send();395 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, tokenId).call())391 await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, tokenId).call())396 .to.eventually.be.rejectedWith(/Not all pieces are owned by the caller$/g);392 .to.be.rejectedWith(/Not all pieces are owned by the caller$/g);393 });394395 itWeb3('send QTZ/UNQ to contract from non owner', async ({api, web3, privateKeyWrapper}) => {396 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);397 const payer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);398399 const fractionalizer = await deployFractionalizer(web3, owner);400 const amount = 10n * UNIQUE;401 await expect(web3.eth.sendTransaction({from: payer, to: fractionalizer.options.address, value: `${amount}`, ...GAS_ARGS})).to.be.rejected;402 });403404 itWeb3('fractionalize NFT with NFT transfers disallowed', async ({api, web3, privateKeyWrapper}) => {405 const alice = privateKeyWrapper('//Alice');406 let collectionId;407 {408 const tx = api.tx.unique.createCollectionEx({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});409 const events = await submitTransactionAsync(alice, tx);410 const result = getCreateCollectionResult(events);411 collectionId = result.collectionId;412 }413 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);414 let nftTokenId;415 {416 const createData = {nft: {}};417 const tx = api.tx.unique.createItem(collectionId, {Ethereum: owner}, createData as any);418 const events = await executeTransaction(api, alice, tx);419 const result = getCreateItemResult(events);420 nftTokenId = result.itemId;421 }422 {423 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, false);424 await executeTransaction(api, alice, tx);425 }426 const nftCollectionAddress = collectionIdToAddress(collectionId);427 const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);428 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();429430 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);431 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();432 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())433 .to.be.rejectedWith(/TransferNotAllowed$/g);434 });435 436 itWeb3('fractionalize NFT with RFT transfers disallowed', async ({api, web3, privateKeyWrapper}) => {437 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);438 const alice = privateKeyWrapper('//Alice');439440 let collectionId;441 {442 const tx = api.tx.unique.createCollectionEx({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'ReFungible'});443 const events = await submitTransactionAsync(alice, tx);444 const result = getCreateCollectionResult(events);445 collectionId = result.collectionId;446 }447 const rftCollectionAddress = collectionIdToAddress(collectionId);448 const fractionalizer = await deployFractionalizer(web3, owner);449 {450 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: fractionalizer.options.address});451 await submitTransactionAsync(alice, changeAdminTx);452 }453 await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send();454 {455 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, false);456 await executeTransaction(api, alice, tx);457 }458459 const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);460 const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);461 const nftTokenId = await nftContract.methods.nextTokenId().call();462 await nftContract.methods.mint(owner, nftTokenId).send();463464 await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();465 await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();466467 await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100n).call())468 .to.be.rejectedWith(/TransferNotAllowed$/g);397 });469 });398});470});