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

difftreelog

source

js-packages/tests/eth/marketplace-v2/marketplace.test.ts11.0 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 * as web3 from 'web3';18import type {IKeyringPair} from '@polkadot/types/types';19import {readFile} from 'fs/promises';20import {SponsoringMode, itEth, usingEthPlaygrounds} from '@unique/test-utils/eth/util.js';21import {EthUniqueHelper} from '@unique/test-utils/eth/index.js';22import {makeNames, expect} from '@unique/test-utils/util.js';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    const nodeModulesDir = `${dirname}/../../../node_modules`;43    const solApiDir = `${dirname}/../../../evm-abi/api`;44    return await helper.ethContract.deployByCode(45      marketOwner,46      'Market',47      (await readFile(`${dirname}/Market.sol`)).toString(),48      [49        {50          solPath: '@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol',51          fsPath: `${solApiDir}/UniqueNFT.sol`,52        },53        {54          solPath: '@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol',55          fsPath: `${solApiDir}/UniqueFungible.sol`,56        },57        {58          solPath: '@openzeppelin/contracts/utils/introspection/IERC165.sol',59          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/utils/introspection/IERC165.sol`,60        },61        {62          solPath: '@openzeppelin/contracts/access/Ownable.sol',63          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/access/Ownable.sol`,64        },65        {66          solPath: '@openzeppelin/contracts/utils/Context.sol',67          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/utils/Context.sol`,68        },69        {70          solPath: '@openzeppelin/contracts/security/ReentrancyGuard.sol',71          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/security/ReentrancyGuard.sol`,72        },73        {74          solPath: '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol',75          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/utils/introspection/ERC165Checker.sol`,76        },77        {78          solPath: '@openzeppelin/contracts/token/ERC721/IERC721.sol',79          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/token/ERC721/IERC721.sol`,80        },81        {82          solPath: '@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol',83          fsPath: `${solApiDir}/CollectionHelpers.sol`,84        },85        {86          solPath: 'royalty/UniqueRoyaltyHelper.sol',87          fsPath: `${dirname}/royalty/UniqueRoyaltyHelper.sol`,88        },89        {90          solPath: 'royalty/UniqueRoyalty.sol',91          fsPath: `${dirname}/royalty/UniqueRoyalty.sol`,92        },93        {94          solPath: 'royalty/LibPart.sol',95          fsPath: `${dirname}/royalty/LibPart.sol`,96        },97      ],98      15000000,99      [MARKET_FEE, 0],100    );101  }102103  function substrateAddressToHex(sub: Uint8Array| string, web3: web3.default) {104    if(typeof sub === 'string')105      return web3.utils.padLeft(web3.utils.toHex(web3.utils.toBN(sub)), 64);106    else if(sub instanceof Uint8Array)107      return web3.utils.padLeft(web3.utils.bytesToHex(Array.from(sub)), 64);108    throw Error('Infallible');109  }110111  itEth('Put + Buy [eth]', async ({helper}) => {112    const ONE_TOKEN = helper.balance.getOneTokenNominal();113    const PRICE = 2n * ONE_TOKEN;  // 2 UNQ114    const marketOwner = await helper.eth.createAccountWithBalance(donor, 60000n);115    const market = await deployMarket(helper, marketOwner);116    const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);117118    // Set external sponsoring119    await contractHelpers.methods.setSponsor(market.options.address, marketOwner).send({from: marketOwner});120    await contractHelpers.methods.confirmSponsorship(market.options.address).send({from: marketOwner});121122    // Configure sponsoring123    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});124    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});125126    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');127    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);128129    // Set collection sponsoring130    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});131    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});132133    const sellerCross = helper.ethCrossAccount.createAccount();134    const result = await collection.methods.mintCross(sellerCross, []).send();135    const tokenId = result.events.Transfer.returnValues.tokenId;136    await collection.methods.approve(market.options.address, tokenId).send({from: sellerCross.eth});137138    // Seller has no funds at all, his transactions are sponsored139    const sellerBalance = await helper.balance.getEthereum(sellerCross.eth);140    expect(sellerBalance).to.be.eq(0n);141142    const putResult = await market.methods.put(collectionId, tokenId, PRICE.toString(), 1, sellerCross).send({143      from: sellerCross.eth, gasLimit: 1_000_000,144    });145    expect(putResult.events.TokenIsUpForSale).is.not.undefined;146147    // Seller balance are still 0148    const sellerBalanceAfter = await helper.balance.getEthereum(sellerCross.eth);149    expect(sellerBalanceAfter).to.be.eq(0n);150151    let ownerCross = await collection.methods.ownerOfCross(tokenId).call();152    expect(ownerCross.eth).to.be.eq(sellerCross.eth);153    expect(ownerCross.sub).to.be.eq(sellerCross.sub);154155    const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 10n);156157    // Buyer has only 10 UNQ158    const buyerBalance = await helper.balance.getEthereum(buyerCross.eth);159    expect(buyerBalance).to.be.eq(10n * ONE_TOKEN);160161    const buyResult = await market.methods.buy(collectionId, tokenId, 1, buyerCross).send({from: buyerCross.eth, value: PRICE.toString(), gasLimit: 1_000_000});162    expect(buyResult.events.TokenIsPurchased).is.not.undefined;163164    // Buyer pays only value, transaction use sponsoring165    const buyerBalanceAfter = await helper.balance.getEthereum(buyerCross.eth);166    expect(buyerBalanceAfter).to.be.eq(10n * ONE_TOKEN - PRICE);167168    ownerCross = await collection.methods.ownerOfCross(tokenId).call();169    expect(ownerCross.eth).to.be.eq(buyerCross.eth);170    expect(ownerCross.sub).to.be.eq(buyerCross.sub);171  });172173  itEth('Put + Buy [sub]', async ({helper}) => {174    const ONE_TOKEN = helper.balance.getOneTokenNominal();175    const PRICE = 2n * ONE_TOKEN;  // 2 UNQ176    const web3 = helper.getWeb3();177    const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);178    const market = await deployMarket(helper, marketOwner);179    const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);180181    // Set self sponsoring from contract balance182    await contractHelpers.methods.selfSponsoredEnable(market.options.address).send({from: marketOwner});183    await helper.eth.transferBalanceFromSubstrate(donor, market.options.address, 10n);184185    // Configure sponsoring186    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});187    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});188189    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');190    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);191192    // Set collection sponsoring193    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});194    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});195196    const seller = helper.util.fromSeed(`//Market-seller-${(new Date()).getTime()}`);197    const sellerCross = helper.ethCrossAccount.fromKeyringPair(seller);198199    // Seller has no funds at all, his transactions are sponsored200    {201      const sellerBalance = await helper.balance.getSubstrate(seller.address);202      expect(sellerBalance).to.be.eq(0n);203    }204205    const result = await collection.methods.mintCross(sellerCross, []).send();206    const tokenId = result.events.Transfer.returnValues.tokenId;207    await helper.nft.approveToken(seller, collectionId, tokenId, {Ethereum: market.options.address});208209    await helper.eth.sendEVM(seller, market.options.address, market.methods.put(collectionId, tokenId, PRICE, 1, sellerCross).encodeABI(), '0');210    // Seller balance is still zero211    {212      const sellerBalance = await helper.balance.getSubstrate(seller.address);213      expect(sellerBalance).to.be.eq(0n);214    }215    let ownerCross = await collection.methods.ownerOfCross(tokenId).call();216    expect(ownerCross.eth).to.be.eq(sellerCross.eth);217    expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(sellerCross.sub, web3));218219    const [buyer] = await helper.arrange.createAccounts([600n], donor);220    // Buyer has only expected balance221    {222      const buyerBalance = await helper.balance.getSubstrate(buyer.address);223      expect(buyerBalance).to.be.eq(600n * ONE_TOKEN);224    }225    const buyerCross = helper.ethCrossAccount.fromKeyringPair(buyer);226227    const buyerBalanceBefore = await helper.balance.getSubstrate(buyer.address);228    await helper.eth.sendEVM(buyer, market.options.address, market.methods.buy(collectionId, tokenId, 1, buyerCross).encodeABI(), PRICE.toString());229    const buyerBalanceAfter = await helper.balance.getSubstrate(buyer.address);230    // Buyer balance not changed: transaction is sponsored231    expect(buyerBalanceBefore).to.be.eq(buyerBalanceAfter + PRICE);232233    const sellerBalanceAfterBuy = BigInt(await helper.balance.getSubstrate(seller.address));234    ownerCross = await collection.methods.ownerOfCross(tokenId).call();235    expect(ownerCross.eth).to.be.eq(buyerCross.eth);236    expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(buyerCross.sub, web3));237238    // Seller got only PRICE - MARKET_FEE239    expect(sellerBalanceAfterBuy).to.be.eq(PRICE * BigInt(100 - MARKET_FEE) / 100n);240  });241});