git.delta.rocks / unique-network / refs/commits / c2ed35549db9

difftreelog

source

tests/src/eth/fractionalizer/fractionalizer.test.ts23.2 KiBsourcehistory
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} 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  itWeb3('Set RFT collection', async ({api, web3, privateKeyWrapper}) => {120    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);121    const fractionalizer = await deployFractionalizer(web3, owner);122    const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);123    const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);124    await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();125    const result = await fractionalizer.methods.setRFTCollection(collectionIdAddress).send();126    expect(result.events).to.be.like({127      RFTCollectionSet: {128        returnValues: {129          _collection: collectionIdAddress,130        },131      },132    });133  });134135  itWeb3('Mint RFT collection', async ({api, web3, privateKeyWrapper}) => {136    const alice = privateKeyWrapper('//Alice');137    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);138    const fractionalizer = await deployFractionalizer(web3, owner);139    const tx = api.tx.balances.transfer(evmToAddress(fractionalizer.options.address), 10n * UNIQUE);140    await submitTransactionAsync(alice, tx);141142    const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send({from: owner});143    expect(result.events).to.be.like({144      RFTCollectionSet: {},145    });146    expect(result.events.RFTCollectionSet.returnValues._collection).to.be.ok;147  });148149  itWeb3('Set Allowlist', async ({api, web3, privateKeyWrapper}) => {150    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);151    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);152    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);153    const result1 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send({from: owner});154    expect(result1.events).to.be.like({155      AllowListSet: {156        returnValues: {157          _collection: nftCollectionAddress,158          _status: true,159        },160      },161    });162    const result2 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, false).send({from: owner});163    expect(result2.events).to.be.like({164      AllowListSet: {165        returnValues: {166          _collection: nftCollectionAddress,167          _status: false,168        },169      },170    });171  });172173  itWeb3('NFT to RFT', async ({api, web3, privateKeyWrapper}) => {174    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);175176    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);177    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);178    const nftTokenId = await nftContract.methods.nextTokenId().call();179    await nftContract.methods.mint(owner, nftTokenId).send();180181    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);182183    await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();184    await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();185    const result = await fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).send();186    expect(result.events).to.be.like({187      Fractionalized: {188        returnValues: {189          _collection: nftCollectionAddress,190          _tokenId: nftTokenId,191          _amount: '100',192        },193      },194    });195    const rftTokenAddress = result.events.Fractionalized.returnValues._rftToken;196    const rftTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);197    expect(await rftTokenContract.methods.balanceOf(owner).call()).to.equal('100');198  });199200  itWeb3('RFT to NFT', async ({api, web3, privateKeyWrapper}) => {201    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);202203    const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);204    const {rftTokenAddress, nftCollectionAddress, nftTokenId} = await createRFTToken(api, web3, owner, fractionalizer, 100n);205206    const {collectionId, tokenId} = tokenIdFromAddress(rftTokenAddress);207    const refungibleAddress = collectionIdToAddress(collectionId);208    expect(rftCollectionAddress).to.be.equal(refungibleAddress);209    const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);210    await refungibleTokenContract.methods.approve(fractionalizer.options.address, 100).send();211    const result = await fractionalizer.methods.rft2nft(refungibleAddress, tokenId).send();212    expect(result.events).to.be.like({213      Defractionalized: {214        returnValues: {215          _rftToken: rftTokenAddress,216          _nftCollection: nftCollectionAddress,217          _nftTokenId: nftTokenId,218        },219      },220    });221  });222});223224225226describe('Negative Integration Tests for fractionalizer', () => {227  itWeb3('call setRFTCollection twice', async ({api, web3, privateKeyWrapper}) => {228    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);229    const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);230    const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);231232    const fractionalizer = await deployFractionalizer(web3, owner);233    await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();234    await fractionalizer.methods.setRFTCollection(collectionIdAddress).send();235236    await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())237      .to.be.rejectedWith(/RFT collection is already set$/g);238  });239240  itWeb3('call setRFTCollection with NFT collection', async ({api, web3, privateKeyWrapper}) => {241    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);242    const {collectionIdAddress} = await createNonfungibleCollection(api, web3, owner);243    const nftContract = uniqueNFT(web3, collectionIdAddress, owner);244245    const fractionalizer = await deployFractionalizer(web3, owner);246    await nftContract.methods.addCollectionAdmin(fractionalizer.options.address).send();247248    await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())249      .to.be.rejectedWith(/Wrong collection type. Collection is not refungible.$/g);250  });251252  itWeb3('call setRFTCollection while not collection admin', async ({api, web3, privateKeyWrapper}) => {253    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);254    const fractionalizer = await deployFractionalizer(web3, owner);255    const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);256257    await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())258      .to.be.rejectedWith(/Fractionalizer contract should be an admin of the collection$/g);259  });260261  itWeb3('call setRFTCollection after createAndSetRFTCollection', async ({api, web3, privateKeyWrapper}) => {262    const alice = privateKeyWrapper('//Alice');263    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);264    const fractionalizer = await deployFractionalizer(web3, owner);265    const tx = api.tx.balances.transfer(evmToAddress(fractionalizer.options.address), 10n * UNIQUE);266    await submitTransactionAsync(alice, tx);267268    const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send({from: owner});269    const collectionIdAddress = result.events.RFTCollectionSet.returnValues._collection;270271    await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())272      .to.be.rejectedWith(/RFT collection is already set$/g);273  });274275  itWeb3('call nft2rft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {276    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);277278    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);279    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);280    const nftTokenId = await nftContract.methods.nextTokenId().call();281    await nftContract.methods.mint(owner, nftTokenId).send();282283    const fractionalizer = await deployFractionalizer(web3, owner);284285    await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())286      .to.be.rejectedWith(/RFT collection is not set$/g);287  });288289  itWeb3('call nft2rft while not owner of NFT token', async ({api, web3, privateKeyWrapper}) => {290    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);291    const nftOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);292293    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);294    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);295    const nftTokenId = await nftContract.methods.nextTokenId().call();296    await nftContract.methods.mint(owner, nftTokenId).send();297    await nftContract.methods.transfer(nftOwner, 1).send();298299300    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);301    await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();302303    await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())304      .to.be.rejectedWith(/Only token owner could fractionalize it$/g);305  });306307  itWeb3('call nft2rft while not in list of allowed accounts', async ({api, web3, privateKeyWrapper}) => {308    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);309310    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);311    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);312    const nftTokenId = await nftContract.methods.nextTokenId().call();313    await nftContract.methods.mint(owner, nftTokenId).send();314315    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);316317    await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();318    await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())319      .to.be.rejectedWith(/Fractionalization of this collection is not allowed by admin$/g);320  });321322  itWeb3('call nft2rft while fractionalizer doesnt have approval for nft token', async ({api, web3, privateKeyWrapper}) => {323    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);324325    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);326    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);327    const nftTokenId = await nftContract.methods.nextTokenId().call();328    await nftContract.methods.mint(owner, nftTokenId).send();329330    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);331332    await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();333    await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())334      .to.be.rejectedWith(/ApprovedValueTooLow$/g);335  });336337  itWeb3('call rft2nft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {338    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);339340    const fractionalizer = await deployFractionalizer(web3, owner);341    const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);342    const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);343    const rftTokenId = await refungibleContract.methods.nextTokenId().call();344    await refungibleContract.methods.mint(owner, rftTokenId).send();345    346    await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())347      .to.be.rejectedWith(/RFT collection is not set$/g);348  });349350  itWeb3('call rft2nft for RFT token that is not from configured RFT collection', async ({api, web3, privateKeyWrapper}) => {351    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);352353    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);354    const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);355    const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);356    const rftTokenId = await refungibleContract.methods.nextTokenId().call();357    await refungibleContract.methods.mint(owner, rftTokenId).send();358    359    await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())360      .to.be.rejectedWith(/Wrong RFT collection$/g);361  });362363  itWeb3('call rft2nft for RFT token that was not minted by fractionalizer contract', async ({api, web3, privateKeyWrapper}) => {364    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);365    const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);366367    const fractionalizer = await deployFractionalizer(web3, owner);368    const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);369370    await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();371    await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send();372373    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(/No corresponding NFT token found$/g);378  });379380  itWeb3('call rft2nft without owning all RFT pieces', async ({api, web3, privateKeyWrapper}) => {381    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);382    const receiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);383384    const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);385    const {rftTokenAddress} = await createRFTToken(api, web3, owner, fractionalizer, 100n);386    387    const {tokenId} = tokenIdFromAddress(rftTokenAddress);388    const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);389    await refungibleTokenContract.methods.transfer(receiver, 50).send();390    await refungibleTokenContract.methods.approve(fractionalizer.options.address, 50).send();391    await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, tokenId).call())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);469  });470});