git.delta.rocks / unique-network / refs/commits / 6a580826c34a

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 '../util/index.js';21import {EthUniqueHelper} from '../util/playgrounds/unique.dev.js';22import {makeNames} from '../../util/index.js';23import {expect} from 'chai';2425const {dirname} = makeNames(import.meta.url);2627const MARKET_FEE = 1;2829describe('Market V2 Contract', () => {30  let donor: IKeyringPair;3132  before(async () => {33    await usingEthPlaygrounds(async (helper, privateKey) => {34      donor = await privateKey({url: import.meta.url});3536      const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);3738      await deployMarket(helper, marketOwner);39    });40  });4142  async function deployMarket(helper: EthUniqueHelper, marketOwner: string) {43    const nodeModulesDir = `${dirname}/../../../node_modules`;44    const solApiDir = `${dirname}/../api`;45    return await helper.ethContract.deployByCode(46      marketOwner,47      'Market',48      (await readFile(`${dirname}/Market.sol`)).toString(),49      [50        {51          solPath: '@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol',52          fsPath: `${solApiDir}/UniqueNFT.sol`,53        },54        {55          solPath: '@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol',56          fsPath: `${solApiDir}/UniqueFungible.sol`,57        },58        {59          solPath: '@openzeppelin/contracts/utils/introspection/IERC165.sol',60          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/utils/introspection/IERC165.sol`,61        },62        {63          solPath: '@openzeppelin/contracts/access/Ownable.sol',64          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/access/Ownable.sol`,65        },66        {67          solPath: '@openzeppelin/contracts/utils/Context.sol',68          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/utils/Context.sol`,69        },70        {71          solPath: '@openzeppelin/contracts/security/ReentrancyGuard.sol',72          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/security/ReentrancyGuard.sol`,73        },74        {75          solPath: '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol',76          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/utils/introspection/ERC165Checker.sol`,77        },78        {79          solPath: '@openzeppelin/contracts/token/ERC721/IERC721.sol',80          fsPath: `${nodeModulesDir}/@openzeppelin/contracts/token/ERC721/IERC721.sol`,81        },82        {83          solPath: '@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol',84          fsPath: `${solApiDir}/CollectionHelpers.sol`,85        },86        {87          solPath: 'royalty/UniqueRoyaltyHelper.sol',88          fsPath: `${dirname}/royalty/UniqueRoyaltyHelper.sol`,89        },90        {91          solPath: 'royalty/UniqueRoyalty.sol',92          fsPath: `${dirname}/royalty/UniqueRoyalty.sol`,93        },94        {95          solPath: 'royalty/LibPart.sol',96          fsPath: `${dirname}/royalty/LibPart.sol`,97        },98      ],99      15000000,100      [MARKET_FEE, 0],101    );102  }103104  function substrateAddressToHex(sub: Uint8Array| string, web3: web3.default) {105    if(typeof sub === 'string')106      return web3.utils.padLeft(web3.utils.toHex(web3.utils.toBN(sub)), 64);107    else if(sub instanceof Uint8Array)108      return web3.utils.padLeft(web3.utils.bytesToHex(Array.from(sub)), 64);109    throw Error('Infallible');110  }111112  itEth('Put + Buy [eth]', async ({helper}) => {113    const ONE_TOKEN = helper.balance.getOneTokenNominal();114    const PRICE = 2n * ONE_TOKEN;  // 2 UNQ115    const marketOwner = await helper.eth.createAccountWithBalance(donor, 60000n);116    const market = await deployMarket(helper, marketOwner);117    const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);118119    // Set external sponsoring120    await contractHelpers.methods.setSponsor(market.options.address, marketOwner).send({from: marketOwner});121    await contractHelpers.methods.confirmSponsorship(market.options.address).send({from: marketOwner});122123    // Configure sponsoring124    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});125    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});126127    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');128    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);129130    // Set collection sponsoring131    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});132    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});133134    const sellerCross = helper.ethCrossAccount.createAccount();135    const result = await collection.methods.mintCross(sellerCross, []).send();136    const tokenId = result.events.Transfer.returnValues.tokenId;137    await collection.methods.approve(market.options.address, tokenId).send({from: sellerCross.eth});138139    // Seller has no funds at all, his transactions are sponsored140    const sellerBalance = await helper.balance.getEthereum(sellerCross.eth);141    expect(sellerBalance).to.be.eq(0n);142143    const putResult = await market.methods.put(collectionId, tokenId, PRICE.toString(), 1, sellerCross).send({144      from: sellerCross.eth, gasLimit: 1_000_000,145    });146    expect(putResult.events.TokenIsUpForSale).is.not.undefined;147148    // Seller balance are still 0149    const sellerBalanceAfter = await helper.balance.getEthereum(sellerCross.eth);150    expect(sellerBalanceAfter).to.be.eq(0n);151152    let ownerCross = await collection.methods.ownerOfCross(tokenId).call();153    expect(ownerCross.eth).to.be.eq(sellerCross.eth);154    expect(ownerCross.sub).to.be.eq(sellerCross.sub);155156    const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 10n);157158    // Buyer has only 10 UNQ159    const buyerBalance = await helper.balance.getEthereum(buyerCross.eth);160    expect(buyerBalance).to.be.eq(10n * ONE_TOKEN);161162    const buyResult = await market.methods.buy(collectionId, tokenId, 1, buyerCross).send({from: buyerCross.eth, value: PRICE.toString(), gasLimit: 1_000_000});163    expect(buyResult.events.TokenIsPurchased).is.not.undefined;164165    // Buyer pays only value, transaction use sponsoring166    const buyerBalanceAfter = await helper.balance.getEthereum(buyerCross.eth);167    expect(buyerBalanceAfter).to.be.eq(10n * ONE_TOKEN - PRICE);168169    ownerCross = await collection.methods.ownerOfCross(tokenId).call();170    expect(ownerCross.eth).to.be.eq(buyerCross.eth);171    expect(ownerCross.sub).to.be.eq(buyerCross.sub);172  });173174  itEth('Put + Buy [sub]', async ({helper}) => {175    const ONE_TOKEN = helper.balance.getOneTokenNominal();176    const PRICE = 2n * ONE_TOKEN;  // 2 UNQ177    const web3 = helper.getWeb3();178    const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);179    const market = await deployMarket(helper, marketOwner);180    const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);181182    // Set self sponsoring from contract balance183    await contractHelpers.methods.selfSponsoredEnable(market.options.address).send({from: marketOwner});184    await helper.eth.transferBalanceFromSubstrate(donor, market.options.address, 10n);185186    // Configure sponsoring187    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});188    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});189190    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');191    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);192193    // Set collection sponsoring194    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});195    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});196197    const seller = helper.util.fromSeed(`//Market-seller-${(new Date()).getTime()}`);198    const sellerCross = helper.ethCrossAccount.fromKeyringPair(seller);199200    // Seller has no funds at all, his transactions are sponsored201    {202      const sellerBalance = await helper.balance.getSubstrate(seller.address);203      expect(sellerBalance).to.be.eq(0n);204    }205206    const result = await collection.methods.mintCross(sellerCross, []).send();207    const tokenId = result.events.Transfer.returnValues.tokenId;208    await helper.nft.approveToken(seller, collectionId, tokenId, {Ethereum: market.options.address});209210    await helper.eth.sendEVM(seller, market.options.address, market.methods.put(collectionId, tokenId, PRICE, 1, sellerCross).encodeABI(), '0');211    // Seller balance is still zero212    {213      const sellerBalance = await helper.balance.getSubstrate(seller.address);214      expect(sellerBalance).to.be.eq(0n);215    }216    let ownerCross = await collection.methods.ownerOfCross(tokenId).call();217    expect(ownerCross.eth).to.be.eq(sellerCross.eth);218    expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(sellerCross.sub, web3));219220    const [buyer] = await helper.arrange.createAccounts([600n], donor);221    // Buyer has only expected balance222    {223      const buyerBalance = await helper.balance.getSubstrate(buyer.address);224      expect(buyerBalance).to.be.eq(600n * ONE_TOKEN);225    }226    const buyerCross = helper.ethCrossAccount.fromKeyringPair(buyer);227228    const buyerBalanceBefore = await helper.balance.getSubstrate(buyer.address);229    await helper.eth.sendEVM(buyer, market.options.address, market.methods.buy(collectionId, tokenId, 1, buyerCross).encodeABI(), PRICE.toString());230    const buyerBalanceAfter = await helper.balance.getSubstrate(buyer.address);231    // Buyer balance not changed: transaction is sponsored232    expect(buyerBalanceBefore).to.be.eq(buyerBalanceAfter + PRICE);233234    const sellerBalanceAfterBuy = BigInt(await helper.balance.getSubstrate(seller.address));235    ownerCross = await collection.methods.ownerOfCross(tokenId).call();236    expect(ownerCross.eth).to.be.eq(buyerCross.eth);237    expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(buyerCross.sub, web3));238239    // Seller got only PRICE - MARKET_FEE240    expect(sellerBalanceAfterBuy).to.be.eq(PRICE * BigInt(100 - MARKET_FEE) / 100n);241  });242});