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

difftreelog

Update market + substrate sponsoring example

Andy Smith2023-06-27parent: #8196877.patch.diff
in: master

2 files changed

modifiedtests/src/eth/marketplace-v2/Market.soldiffbeforeafterboth
--- a/tests/src/eth/marketplace-v2/Market.sol
+++ b/tests/src/eth/marketplace-v2/Market.sol
@@ -87,6 +87,18 @@
         }
     }
 
+    /**
+     * Fallback that allows this contract to receive native token.
+     * We need this for self-sponsoring
+     */
+    fallback() external payable {}
+
+    /**
+     * Receive also allows this contract to receive native token.
+     * We need this for self-sponsoring
+     */
+    receive() external payable {}
+
     function getErc721(uint32 collectionId) private view returns (IERC721) {
         address collectionAddress = collectionHelpers.collectionAddress(
             collectionId
modifiedtests/src/eth/marketplace-v2/marketplace.test.tsdiffbeforeafterboth
before · tests/src/eth/marketplace-v2/marketplace.test.ts
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);2526describe('Market V2 Contract', () => {27  let donor: IKeyringPair;2829  before(async () => {30    await usingEthPlaygrounds(async (_helper, privateKey) => {31      donor = await privateKey({url: import.meta.url});32    });33  });3435  async function deployMarket(helper: EthUniqueHelper, marketOwner: string) {36    return await helper.ethContract.deployByCode(37      marketOwner,38      'Market',39      (await readFile(`${dirname}/Market.sol`)).toString(),40      [41        {42          solPath: '@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol',43          fsPath: `${dirname}/../api/UniqueNFT.sol`,44        },45        {46          solPath: '@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol',47          fsPath: `${dirname}/../api/UniqueFungible.sol`,48        },49        {50          solPath: '@openzeppelin/contracts/utils/introspection/IERC165.sol',51          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol`,52        },53        {54          solPath: '@openzeppelin/contracts/access/Ownable.sol',55          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/access/Ownable.sol`,56        },57        {58          solPath: '@openzeppelin/contracts/utils/Context.sol',59          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/Context.sol`,60        },61        {62          solPath: '@openzeppelin/contracts/security/ReentrancyGuard.sol',63          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol`,64        },65        {66          solPath: '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol',67          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/ERC165Checker.sol`,68        },69        {70          solPath: '@openzeppelin/contracts/token/ERC721/IERC721.sol',71          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol`,72        },73        {74          solPath: '@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol',75          fsPath: `${dirname}/../api/CollectionHelpers.sol`,76        },77        {78          solPath: 'royalty/UniqueRoyaltyHelper.sol',79          fsPath: `${dirname}/royalty/UniqueRoyaltyHelper.sol`,80        },81        {82          solPath: 'royalty/UniqueRoyalty.sol',83          fsPath: `${dirname}/royalty/UniqueRoyalty.sol`,84        },85        {86          solPath: 'royalty/LibPart.sol',87          fsPath: `${dirname}/royalty/LibPart.sol`,88        },89      ],90      15000000,91      [1, 0],92    );93  }9495  function substrateAddressToHex(sub: Uint8Array| string, web3: Web3) {96    if(typeof sub === 'string')97      return web3.utils.padLeft(web3.utils.toHex(web3.utils.toBN(sub)), 64);98    else if(sub instanceof Uint8Array)99      return web3.utils.padLeft(web3.utils.bytesToHex(Array.from(sub)), 64);100  }101102  itEth('Deploy', async ({helper}) => {103    const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);104105    await deployMarket(helper, marketOwner);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);114    await contractHelpers.methods.selfSponsoredEnable(market.options.address).send({from: marketOwner});115    await helper.eth.transferBalanceFromSubstrate(donor, market.options.address, 10n);116117    // TODO: this should work too, instead of selfSponsoring!118    await contractHelpers.methods.setSponsor(market.options.address, marketOwner).send({from: marketOwner});119    await contractHelpers.methods.confirmSponsorship(market.options.address).send({from: marketOwner});120121    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});122    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});123124    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');125    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);126    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});127    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});128129    const sellerCross = helper.ethCrossAccount.createAccount();130    const result = await collection.methods.mintCross(sellerCross, []).send();131    const tokenId = result.events.Transfer.returnValues.tokenId;132    await collection.methods.approve(market.options.address, tokenId).send({from: sellerCross.eth});133    134    // Seller has no funds at all, his transactions are sponsored135    const sellerBalance = await helper.balance.getEthereum(sellerCross.eth);136    expect(sellerBalance).to.be.eq(0n);137138    const putResult = await market.methods.put(collectionId, tokenId, PRICE.toString(), 1, sellerCross).send({139      from: sellerCross.eth, gasLimit: 1_000_000140    });141    expect(putResult.events.TokenIsUpForSale).is.not.undefined;142143    // Seller balance are still 0144    const sellerBalanceAfter = await helper.balance.getEthereum(sellerCross.eth);145    expect(sellerBalanceAfter).to.be.eq(0n);146    147    let ownerCross = await collection.methods.ownerOfCross(tokenId).call();148    expect(ownerCross.eth).to.be.eq(sellerCross.eth);149    expect(ownerCross.sub).to.be.eq(sellerCross.sub);150151    const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 10n);152    console.log('before buy');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;160    161    // 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 PRICE = 1n;172    const web3 = helper.getWeb3();173    const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);174    const market = await deployMarket(helper, marketOwner);175176    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');177    const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner);178179    const [seller] = await helper.arrange.createAccounts([600n], donor);180    const sellerCross = helper.ethCrossAccount.fromKeyringPair(seller);181    const result = await collection.methods.mintCross(sellerCross, []).send();182    const tokenId = result.events.Transfer.returnValues.tokenId;183    await helper.nft.approveToken(seller, collectionId, tokenId, {Ethereum: market.options.address}, 1n);184185    await helper.eth.sendEVM(seller, market.options.address, market.methods.put(collectionId, tokenId, PRICE, 1, sellerCross).encodeABI(), '0');186    let ownerCross = await collection.methods.ownerOfCross(tokenId).call();187    expect(ownerCross.eth).to.be.eq(sellerCross.eth);188    expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(sellerCross.sub, web3));189190    const [buyer] = await helper.arrange.createAccounts([600n], donor);191    const buyerMirror = helper.address.substrateToEth(buyer.address);192    const buyerCross = helper.ethCrossAccount.fromKeyringPair(buyer);193    await helper.eth.transferBalanceFromSubstrate(donor, buyerMirror, 1n);194    const sellerBalance = BigInt(await helper.balance.getSubstrate(seller.address));195    await helper.eth.sendEVM(buyer, market.options.address, market.methods.buy(collectionId, tokenId, 1, buyerCross).encodeABI(), PRICE.toString());196    const sellerBalanceAfterBuy = BigInt(await helper.balance.getSubstrate(seller.address));197    ownerCross = await collection.methods.ownerOfCross(tokenId).call();198    expect(ownerCross.eth).to.be.eq(buyerCross.eth);199    expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(buyerCross.sub, web3));200    expect(sellerBalance + PRICE).to.be.equal(sellerBalanceAfterBuy);201  });202});