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

difftreelog

source

tests/src/eth/marketplace-v2/marketplace.test.ts10.9 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/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {readFile} from 'fs/promises';19import {EthUniqueHelper, SponsoringMode, itEth, usingEthPlaygrounds} from '../util';20import {makeNames} from '../../util';21import {expect} from 'chai';22import Web3 from 'web3';2324const {dirname} = makeNames(import.meta.url);2526const MARKET_FEE = 1;2728describe('Market V2 Contract', () => {29  let donor: IKeyringPair;3031  before(async () => {32    await usingEthPlaygrounds(async (helper, privateKey) => {33      donor = await privateKey({url: import.meta.url});3435      const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);3637      await deployMarket(helper, marketOwner);38    });39  });4041  async function deployMarket(helper: EthUniqueHelper, marketOwner: string) {42    return await helper.ethContract.deployByCode(43      marketOwner,44      'Market',45      (await readFile(`${dirname}/Market.sol`)).toString(),46      [47        {48          solPath: '@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol',49          fsPath: `${dirname}/../api/UniqueNFT.sol`,50        },51        {52          solPath: '@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol',53          fsPath: `${dirname}/../api/UniqueFungible.sol`,54        },55        {56          solPath: '@openzeppelin/contracts/utils/introspection/IERC165.sol',57          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol`,58        },59        {60          solPath: '@openzeppelin/contracts/access/Ownable.sol',61          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/access/Ownable.sol`,62        },63        {64          solPath: '@openzeppelin/contracts/utils/Context.sol',65          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/Context.sol`,66        },67        {68          solPath: '@openzeppelin/contracts/security/ReentrancyGuard.sol',69          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol`,70        },71        {72          solPath: '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol',73          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/ERC165Checker.sol`,74        },75        {76          solPath: '@openzeppelin/contracts/token/ERC721/IERC721.sol',77          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol`,78        },79        {80          solPath: '@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol',81          fsPath: `${dirname}/../api/CollectionHelpers.sol`,82        },83        {84          solPath: 'royalty/UniqueRoyaltyHelper.sol',85          fsPath: `${dirname}/royalty/UniqueRoyaltyHelper.sol`,86        },87        {88          solPath: 'royalty/UniqueRoyalty.sol',89          fsPath: `${dirname}/royalty/UniqueRoyalty.sol`,90        },91        {92          solPath: 'royalty/LibPart.sol',93          fsPath: `${dirname}/royalty/LibPart.sol`,94        },95      ],96      15000000,97      [MARKET_FEE, 0],98    );99  }100101  function substrateAddressToHex(sub: Uint8Array| string, web3: Web3) {102    if(typeof sub === 'string')103      return web3.utils.padLeft(web3.utils.toHex(web3.utils.toBN(sub)), 64);104    else if(sub instanceof Uint8Array)105      return web3.utils.padLeft(web3.utils.bytesToHex(Array.from(sub)), 64);106  }107108  itEth('Put + Buy [eth]', async ({helper}) => {109    const ONE_TOKEN = helper.balance.getOneTokenNominal();110    const PRICE = 2n * ONE_TOKEN;  // 2 UNQ111    const marketOwner = await helper.eth.createAccountWithBalance(donor, 60000n);112    const market = await deployMarket(helper, marketOwner);113    const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);114115    // Set external sponsoring116    await contractHelpers.methods.setSponsor(market.options.address, marketOwner).send({from: marketOwner});117    await contractHelpers.methods.confirmSponsorship(market.options.address).send({from: marketOwner});118119    // Configure sponsoring120    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});121    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});122123    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');124    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);125126    // Set collection sponsoring127    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});128    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});129130    const sellerCross = helper.ethCrossAccount.createAccount();131    const result = await collection.methods.mintCross(sellerCross, []).send();132    const tokenId = result.events.Transfer.returnValues.tokenId;133    await collection.methods.approve(market.options.address, tokenId).send({from: sellerCross.eth});134135    // Seller has no funds at all, his transactions are sponsored136    const sellerBalance = await helper.balance.getEthereum(sellerCross.eth);137    expect(sellerBalance).to.be.eq(0n);138139    const putResult = await market.methods.put(collectionId, tokenId, PRICE.toString(), 1, sellerCross).send({140      from: sellerCross.eth, gasLimit: 1_000_000,141    });142    expect(putResult.events.TokenIsUpForSale).is.not.undefined;143144    // Seller balance are still 0145    const sellerBalanceAfter = await helper.balance.getEthereum(sellerCross.eth);146    expect(sellerBalanceAfter).to.be.eq(0n);147148    let ownerCross = await collection.methods.ownerOfCross(tokenId).call();149    expect(ownerCross.eth).to.be.eq(sellerCross.eth);150    expect(ownerCross.sub).to.be.eq(sellerCross.sub);151152    const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 10n);153154    // Buyer has only 10 UNQ155    const buyerBalance = await helper.balance.getEthereum(buyerCross.eth);156    expect(buyerBalance).to.be.eq(10n * ONE_TOKEN);157158    const buyResult = await market.methods.buy(collectionId, tokenId, 1, buyerCross).send({from: buyerCross.eth, value: PRICE.toString(), gasLimit: 1_000_000});159    expect(buyResult.events.TokenIsPurchased).is.not.undefined;160161    // Buyer pays only value, transaction use sponsoring162    const buyerBalanceAfter = await helper.balance.getEthereum(buyerCross.eth);163    expect(buyerBalanceAfter).to.be.eq(10n * ONE_TOKEN - PRICE);164165    ownerCross = await collection.methods.ownerOfCross(tokenId).call();166    expect(ownerCross.eth).to.be.eq(buyerCross.eth);167    expect(ownerCross.sub).to.be.eq(buyerCross.sub);168  });169170  itEth('Put + Buy [sub]', async ({helper}) => {171    const ONE_TOKEN = helper.balance.getOneTokenNominal();172    const PRICE = 2n * ONE_TOKEN;  // 2 UNQ173    const web3 = helper.getWeb3();174    const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);175    const market = await deployMarket(helper, marketOwner);176    const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);177178    // Set self sponsoring from contract balance179    await contractHelpers.methods.selfSponsoredEnable(market.options.address).send({from: marketOwner});180    await helper.eth.transferBalanceFromSubstrate(donor, market.options.address, 10n);181182    // Configure sponsoring183    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});184    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});185186    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');187    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);188189    // Set collection sponsoring190    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});191    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});192193    const seller = helper.util.fromSeed(`//Market-seller-${(new Date()).getTime()}`);194    const sellerCross = helper.ethCrossAccount.fromKeyringPair(seller);195196    // Seller has no funds at all, his transactions are sponsored197    {198      const sellerBalance = await helper.balance.getSubstrate(seller.address);199      expect(sellerBalance).to.be.eq(0n);200    }201202    const result = await collection.methods.mintCross(sellerCross, []).send();203    const tokenId = result.events.Transfer.returnValues.tokenId;204    await helper.nft.approveToken(seller, collectionId, tokenId, {Ethereum: market.options.address});205206    await helper.eth.sendEVM(seller, market.options.address, market.methods.put(collectionId, tokenId, PRICE, 1, sellerCross).encodeABI(), '0');207    // Seller balance is still zero208    {209      const sellerBalance = await helper.balance.getSubstrate(seller.address);210      expect(sellerBalance).to.be.eq(0n);211    }212    let ownerCross = await collection.methods.ownerOfCross(tokenId).call();213    expect(ownerCross.eth).to.be.eq(sellerCross.eth);214    expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(sellerCross.sub, web3));215216    const [buyer] = await helper.arrange.createAccounts([600n], donor);217    // Buyer has only expected balance218    {219      const buyerBalance = await helper.balance.getSubstrate(buyer.address);220      expect(buyerBalance).to.be.eq(600n * ONE_TOKEN);221    }222    const buyerCross = helper.ethCrossAccount.fromKeyringPair(buyer);223224    const buyerBalanceBefore = await helper.balance.getSubstrate(buyer.address);225    await helper.eth.sendEVM(buyer, market.options.address, market.methods.buy(collectionId, tokenId, 1, buyerCross).encodeABI(), PRICE.toString());226    const buyerBalanceAfter = await helper.balance.getSubstrate(buyer.address);227    // Buyer balance not changed: transaction is sponsored228    expect(buyerBalanceBefore).to.be.eq(buyerBalanceAfter + PRICE);229230    const sellerBalanceAfterBuy = BigInt(await helper.balance.getSubstrate(seller.address));231    ownerCross = await collection.methods.ownerOfCross(tokenId).call();232    expect(ownerCross.eth).to.be.eq(buyerCross.eth);233    expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(buyerCross.sub, web3));234235    // Seller got only PRICE - MARKET_FEE236    expect(sellerBalanceAfterBuy).to.be.eq(PRICE * BigInt(100 - MARKET_FEE) / 100n);237  });238});