git.delta.rocks / unique-network / refs/commits / 203ce836134a

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    return await helper.ethContract.deployByCode(44      marketOwner,45      'Market',46      (await readFile(`${dirname}/Market.sol`)).toString(),47      [48        {49          solPath: '@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol',50          fsPath: `${dirname}/../api/UniqueNFT.sol`,51        },52        {53          solPath: '@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol',54          fsPath: `${dirname}/../api/UniqueFungible.sol`,55        },56        {57          solPath: '@openzeppelin/contracts/utils/introspection/IERC165.sol',58          fsPath: `${dirname}/../../../../node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol`,59        },60        {61          solPath: '@openzeppelin/contracts/access/Ownable.sol',62          fsPath: `${dirname}/../../../../node_modules/@openzeppelin/contracts/access/Ownable.sol`,63        },64        {65          solPath: '@openzeppelin/contracts/utils/Context.sol',66          fsPath: `${dirname}/../../../../node_modules/@openzeppelin/contracts/utils/Context.sol`,67        },68        {69          solPath: '@openzeppelin/contracts/security/ReentrancyGuard.sol',70          fsPath: `${dirname}/../../../../node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol`,71        },72        {73          solPath: '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol',74          fsPath: `${dirname}/../../../../node_modules/@openzeppelin/contracts/utils/introspection/ERC165Checker.sol`,75        },76        {77          solPath: '@openzeppelin/contracts/token/ERC721/IERC721.sol',78          fsPath: `${dirname}/../../../../node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol`,79        },80        {81          solPath: '@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol',82          fsPath: `${dirname}/../api/CollectionHelpers.sol`,83        },84        {85          solPath: 'royalty/UniqueRoyaltyHelper.sol',86          fsPath: `${dirname}/royalty/UniqueRoyaltyHelper.sol`,87        },88        {89          solPath: 'royalty/UniqueRoyalty.sol',90          fsPath: `${dirname}/royalty/UniqueRoyalty.sol`,91        },92        {93          solPath: 'royalty/LibPart.sol',94          fsPath: `${dirname}/royalty/LibPart.sol`,95        },96      ],97      15000000,98      [MARKET_FEE, 0],99    );100  }101102  function substrateAddressToHex(sub: Uint8Array| string, web3: web3.default) {103    if(typeof sub === 'string')104      return web3.utils.padLeft(web3.utils.toHex(web3.utils.toBN(sub)), 64);105    else if(sub instanceof Uint8Array)106      return web3.utils.padLeft(web3.utils.bytesToHex(Array.from(sub)), 64);107    throw Error('Infallible');108  }109110  itEth('Put + Buy [eth]', async ({helper}) => {111    const ONE_TOKEN = helper.balance.getOneTokenNominal();112    const PRICE = 2n * ONE_TOKEN;  // 2 UNQ113    const marketOwner = await helper.eth.createAccountWithBalance(donor, 60000n);114    const market = await deployMarket(helper, marketOwner);115    const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);116117    // Set external sponsoring118    await contractHelpers.methods.setSponsor(market.options.address, marketOwner).send({from: marketOwner});119    await contractHelpers.methods.confirmSponsorship(market.options.address).send({from: marketOwner});120121    // Configure sponsoring122    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});123    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});124125    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');126    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);127128    // Set collection sponsoring129    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});130    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});131132    const sellerCross = helper.ethCrossAccount.createAccount();133    const result = await collection.methods.mintCross(sellerCross, []).send();134    const tokenId = result.events.Transfer.returnValues.tokenId;135    await collection.methods.approve(market.options.address, tokenId).send({from: sellerCross.eth});136137    // Seller has no funds at all, his transactions are sponsored138    const sellerBalance = await helper.balance.getEthereum(sellerCross.eth);139    expect(sellerBalance).to.be.eq(0n);140141    const putResult = await market.methods.put(collectionId, tokenId, PRICE.toString(), 1, sellerCross).send({142      from: sellerCross.eth, gasLimit: 1_000_000,143    });144    expect(putResult.events.TokenIsUpForSale).is.not.undefined;145146    // Seller balance are still 0147    const sellerBalanceAfter = await helper.balance.getEthereum(sellerCross.eth);148    expect(sellerBalanceAfter).to.be.eq(0n);149150    let ownerCross = await collection.methods.ownerOfCross(tokenId).call();151    expect(ownerCross.eth).to.be.eq(sellerCross.eth);152    expect(ownerCross.sub).to.be.eq(sellerCross.sub);153154    const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 10n);155156    // Buyer has only 10 UNQ157    const buyerBalance = await helper.balance.getEthereum(buyerCross.eth);158    expect(buyerBalance).to.be.eq(10n * ONE_TOKEN);159160    const buyResult = await market.methods.buy(collectionId, tokenId, 1, buyerCross).send({from: buyerCross.eth, value: PRICE.toString(), gasLimit: 1_000_000});161    expect(buyResult.events.TokenIsPurchased).is.not.undefined;162163    // Buyer pays only value, transaction use sponsoring164    const buyerBalanceAfter = await helper.balance.getEthereum(buyerCross.eth);165    expect(buyerBalanceAfter).to.be.eq(10n * ONE_TOKEN - PRICE);166167    ownerCross = await collection.methods.ownerOfCross(tokenId).call();168    expect(ownerCross.eth).to.be.eq(buyerCross.eth);169    expect(ownerCross.sub).to.be.eq(buyerCross.sub);170  });171172  itEth('Put + Buy [sub]', async ({helper}) => {173    const ONE_TOKEN = helper.balance.getOneTokenNominal();174    const PRICE = 2n * ONE_TOKEN;  // 2 UNQ175    const web3 = helper.getWeb3();176    const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);177    const market = await deployMarket(helper, marketOwner);178    const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);179180    // Set self sponsoring from contract balance181    await contractHelpers.methods.selfSponsoredEnable(market.options.address).send({from: marketOwner});182    await helper.eth.transferBalanceFromSubstrate(donor, market.options.address, 10n);183184    // Configure sponsoring185    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});186    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});187188    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');189    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);190191    // Set collection sponsoring192    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});193    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});194195    const seller = helper.util.fromSeed(`//Market-seller-${(new Date()).getTime()}`);196    const sellerCross = helper.ethCrossAccount.fromKeyringPair(seller);197198    // Seller has no funds at all, his transactions are sponsored199    {200      const sellerBalance = await helper.balance.getSubstrate(seller.address);201      expect(sellerBalance).to.be.eq(0n);202    }203204    const result = await collection.methods.mintCross(sellerCross, []).send();205    const tokenId = result.events.Transfer.returnValues.tokenId;206    await helper.nft.approveToken(seller, collectionId, tokenId, {Ethereum: market.options.address});207208    await helper.eth.sendEVM(seller, market.options.address, market.methods.put(collectionId, tokenId, PRICE, 1, sellerCross).encodeABI(), '0');209    // Seller balance is still zero210    {211      const sellerBalance = await helper.balance.getSubstrate(seller.address);212      expect(sellerBalance).to.be.eq(0n);213    }214    let ownerCross = await collection.methods.ownerOfCross(tokenId).call();215    expect(ownerCross.eth).to.be.eq(sellerCross.eth);216    expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(sellerCross.sub, web3));217218    const [buyer] = await helper.arrange.createAccounts([600n], donor);219    // Buyer has only expected balance220    {221      const buyerBalance = await helper.balance.getSubstrate(buyer.address);222      expect(buyerBalance).to.be.eq(600n * ONE_TOKEN);223    }224    const buyerCross = helper.ethCrossAccount.fromKeyringPair(buyer);225226    const buyerBalanceBefore = await helper.balance.getSubstrate(buyer.address);227    await helper.eth.sendEVM(buyer, market.options.address, market.methods.buy(collectionId, tokenId, 1, buyerCross).encodeABI(), PRICE.toString());228    const buyerBalanceAfter = await helper.balance.getSubstrate(buyer.address);229    // Buyer balance not changed: transaction is sponsored230    expect(buyerBalanceBefore).to.be.eq(buyerBalanceAfter + PRICE);231232    const sellerBalanceAfterBuy = BigInt(await helper.balance.getSubstrate(seller.address));233    ownerCross = await collection.methods.ownerOfCross(tokenId).call();234    expect(ownerCross.eth).to.be.eq(buyerCross.eth);235    expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(buyerCross.sub, web3));236237    // Seller got only PRICE - MARKET_FEE238    expect(sellerBalanceAfterBuy).to.be.eq(PRICE * BigInt(100 - MARKET_FEE) / 100n);239  });240});