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

difftreelog

Test for market sponsoring

Andy Smith2023-06-26parent: #71175e3.patch.diff
in: master

3 files changed

modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -47,6 +47,7 @@
     "testEthNesting": "yarn _test './**/eth/nesting/**/*.*test.ts'",
     "testEthFractionalizer": "yarn _test './**/eth/fractionalizer/**/*.*test.ts'",
     "testEthMarketplace": "yarn _test './**/eth/marketplace/**/*.*test.ts'",
+    "testEthMarket": "yarn _test './**/eth/marketplace-v2/**/*.*test.ts'",
     "testSub": "yarn _test './**/sub/**/*.*test.ts'",
     "testSubNesting": "yarn _test './**/sub/nesting/**/*.*test.ts'",
     "testEvent": "yarn _test ./src/check-event/*.*test.ts",
modifiedtests/src/eth/marketplace-v2/Market.soldiffbeforeafterboth
--- a/tests/src/eth/marketplace-v2/Market.sol
+++ b/tests/src/eth/marketplace-v2/Market.sol
@@ -1,14 +1,16 @@
 // SPDX-License-Identifier: UNLICENSED
 pragma solidity 0.8.17;
 
+import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
 import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
 import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
+import "@openzeppelin/contracts/access/Ownable.sol";
 import { UniqueNFT, CrossAddress } from "@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol";
 import { UniqueFungible, CrossAddress as CrossAddressF } from "@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol";
 import "@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol";
 import "./royalty/UniqueRoyaltyHelper.sol";
 
-contract Market {
+contract Market is Ownable, ReentrancyGuard {
     using ERC165Checker for address;
 
     struct Order {
@@ -21,7 +23,7 @@
     }
 
     uint32 public constant version = 0;
-    uint32 public constant buildVersion = 1;
+    uint32 public constant buildVersion = 3;
     bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
     bytes4 private constant InterfaceId_ERC165 = 0x5755c3f2;
     CollectionHelpers private constant collectionHelpers =
@@ -31,7 +33,6 @@
     uint32 private idCount = 1;
     uint32 public marketFee;
     uint64 public ctime;
-    address selfAddress;
     address public ownerAddress;
     mapping(address => bool) public admins;
 
@@ -57,15 +58,11 @@
     error OrderNotFound();
     error TooManyAmountRequested();
     error NotEnoughMoneyError();
+    error InvalidRoyaltiesError(uint256 totalRoyalty);
     error FailTransferToken(string reason);
 
-    modifier onlyOwner() {
-      require(msg.sender == ownerAddress, "Only owner can");
-      _;
-    }
-
     modifier onlyAdmin() {
-      require(msg.sender == ownerAddress || admins[msg.sender], "Only admin can");
+      require(msg.sender == this.owner() || admins[msg.sender], "Only admin can");
       _;
     }
 
@@ -85,12 +82,9 @@
         marketFee = fee;
         ctime = timestamp;
 
-        if (marketFee == 0 || marketFee >= 100) {
+        if (marketFee >= 100) {
             revert InvalidMarketFee();
         }
-
-        ownerAddress = msg.sender;
-        selfAddress = address(this);
     }
 
     function getErc721(uint32 collectionId) private view returns (IERC721) {
@@ -114,34 +108,33 @@
         return IERC721(collectionAddress);
     }
 
-    // ################################################################
-    // Set new contract owner                                         #
-    // ################################################################
-
-    function setOwner() public onlyOwner {
-        ownerAddress = msg.sender;
-    }
-
-    // ################################################################
-    // Add new admin                                                  #
-    // ################################################################
-
+    /**
+     * Add new admin. Only owner or an existing admin can add admins.
+     *
+     * @param admin: Address of a new admin to add
+     */
     function addAdmin(address admin) public onlyAdmin {
       admins[admin] = true;
     }
 
-    // ################################################################
-    // Remove admin                                                  #
-    // ################################################################
-
+    /**
+     * Remove an admin. Only owner or an existing admin can remove admins.
+     *
+     * @param admin: Address of a new admin to add
+     */
     function removeAdmin(address admin) public onlyAdmin {
       delete admins[admin];
     }
 
-    // ################################################################
-    // Place a token for sale                                         #
-    // ################################################################
-
+    /**
+     * Place an NFT or RFT token for sale. It must be pre-approved for transfers by this contract address.
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     * @param price: Price (with proper network currency decimals)
+     * @param amount: Number of token fractions to list (must always be 1 for NFT)
+     * @param seller: The seller cross-address (the beneficiary account to receive payment, may be different from transaction sender)
+     */
     function put(
         uint32 collectionId,
         uint32 tokenId,
@@ -166,7 +159,7 @@
           revert SellerIsNotOwner();
         }
 
-        if (erc721.getApproved(tokenId) != selfAddress) {
+        if (erc721.getApproved(tokenId) != address(this)) {
           revert TokenIsNotApproved();
         }
 
@@ -185,10 +178,13 @@
         emit TokenIsUpForSale(version, order);
     }
 
-    // ################################################################
-    // Get order                                                      #
-    // ################################################################
-
+    /**
+     * Get information about the listed token order
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     * @return The order information
+     */
     function getOrder(
         uint32 collectionId,
         uint32 tokenId
@@ -196,10 +192,13 @@
         return orders[collectionId][tokenId];
     }
 
-    // ################################################################
-    // Revoke the token from the sale                                 #
-    // ################################################################
-
+    /**
+     * Revoke the token from the sale. Only the original lister can use this method.
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     * @param amount: Number of token fractions to de-list (must always be 1 for NFT)
+     */
     function revoke(
         uint32 collectionId,
         uint32 tokenId,
@@ -241,10 +240,12 @@
         emit TokenRevoke(version, order, amount);
     }
 
-    // ################################################################
-    // Check approved                                                 #
-    // ################################################################
-
+    /**
+     * Test if the token is still approved to be transferred by this contract and delete the order if not.
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     */
     function checkApproved(uint32 collectionId, uint32 tokenId) public onlyAdmin {
         Order memory order = orders[collectionId][tokenId];
         if (order.price == 0) {
@@ -253,7 +254,7 @@
 
         IERC721 erc721 = getErc721(collectionId);
 
-        if (erc721.getApproved(tokenId) != selfAddress || erc721.ownerOf(tokenId) != getAddressFromCrossAccount(order.seller)) {
+        if (erc721.getApproved(tokenId) != address(this) || erc721.ownerOf(tokenId) != getAddressFromCrossAccount(order.seller)) {
           uint32 amount = order.amount;
           order.amount = 0;
           emit TokenRevoke(version, order, amount);
@@ -272,6 +273,12 @@
         }
     }
 
+    /**
+     * Revoke the token from the sale. Only the contract admin can use this method.
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     */
     function revokeAdmin(uint32 collectionId, uint32 tokenId) public onlyAdmin {
         Order memory order = orders[collectionId][tokenId];
         if (order.price == 0) {
@@ -285,16 +292,20 @@
         delete orders[collectionId][tokenId];
     }
 
-    // ################################################################
-    // Buy a token                                                    #
-    // ################################################################
-
+    /**
+     * Buy a token (partially for an RFT).
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     * @param amount: Number of token fractions to buy (must always be 1 for NFT)
+     * @param buyer: Cross-address of the buyer, eth part must be equal to the transaction signer address
+     */
     function buy(
         uint32 collectionId,
         uint32 tokenId,
         uint32 amount,
         CrossAddress memory buyer
-    ) public payable validCrossAddress(buyer.eth, buyer.sub) {
+    ) public payable validCrossAddress(buyer.eth, buyer.sub) nonReentrant {
         if (msg.value == 0) {
           revert InvalidArgument("msg.value must not be zero");
         }
@@ -319,7 +330,7 @@
         }
 
         IERC721 erc721 = getErc721(order.collectionId);
-        if (erc721.getApproved(tokenId) != selfAddress) {
+        if (erc721.getApproved(tokenId) != address(this)) {
           revert TokenIsNotApproved();
         }
 
@@ -339,13 +350,16 @@
           order.tokenId
         );
 
-        (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue);
+        (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue - feeValue);
+
+        if (totalRoyalty >= totalValue - feeValue) {
+          revert InvalidRoyaltiesError(totalRoyalty);
+        }
 
         sendMoney(order.seller, totalValue - feeValue - totalRoyalty);
 
         if (msg.value > totalValue) {
-            // todo, send money to signer or buyer ?
-            payable(msg.sender).transfer(msg.value - totalValue);
+            sendMoney(buyer, msg.value - totalValue);
         }
 
         emit TokenIsPurchased(version, order, amount, buyer, royalties);
@@ -356,7 +370,7 @@
 
       UniqueFungible fungible = UniqueFungible(collectionAddress);
 
-      CrossAddressF memory fromF = CrossAddressF(selfAddress, 0);
+      CrossAddressF memory fromF = CrossAddressF(address(this), 0);
       CrossAddressF memory toF = CrossAddressF(to.eth, to.sub);
 
       fungible.transferFromCross(fromF, toF, money);
@@ -379,7 +393,7 @@
     }
 
     function withdraw(address transferTo) public onlyOwner {
-        uint256 balance = selfAddress.balance;
+        uint256 balance = address(this).balance;
 
         if (balance > 0) {
             payable(transferTo).transfer(balance);
modifiedtests/src/eth/marketplace-v2/marketplace.test.tsdiffbeforeafterboth
1616
17import {IKeyringPair} from '@polkadot/types/types';17import {IKeyringPair} from '@polkadot/types/types';
18import {readFile} from 'fs/promises';18import {readFile} from 'fs/promises';
19import {EthUniqueHelper, itEth, usingEthPlaygrounds} from '../util';19import {EthUniqueHelper, SponsoringMode, itEth, usingEthPlaygrounds} from '../util';
20import {makeNames} from '../../util';20import {makeNames} from '../../util';
21import {expect} from 'chai';21import {expect} from 'chai';
22import Web3 from 'web3';22import Web3 from 'web3';
50 solPath: '@openzeppelin/contracts/utils/introspection/IERC165.sol',50 solPath: '@openzeppelin/contracts/utils/introspection/IERC165.sol',
51 fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol`,51 fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol`,
52 },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 },
53 {65 {
54 solPath: '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol',66 solPath: '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol',
55 fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/ERC165Checker.sol`,67 fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/ERC165Checker.sol`,
94 });106 });
95107
96 itEth('Put + Buy [eth]', async ({helper}) => {108 itEth('Put + Buy [eth]', async ({helper}) => {
109 const ONE_TOKEN = helper.balance.getOneTokenNominal();
110 const PRICE = 2n * ONE_TOKEN; // 2 UNQ
97 const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);111 const marketOwner = await helper.eth.createAccountWithBalance(donor, 60000n);
98 const market = await deployMarket(helper, marketOwner);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);
116
117 // 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);
120
121 await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});
122 await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});
99123
100 const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');124 const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');
101 const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner);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});
102128
103 const sellerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 600n);129 const sellerCross = helper.ethCrossAccount.createAccount();
104 const result = await collection.methods.mintCross(sellerCross, []).send();130 const result = await collection.methods.mintCross(sellerCross, []).send();
105 const tokenId = result.events.Transfer.returnValues.tokenId;131 const tokenId = result.events.Transfer.returnValues.tokenId;
106 await collection.methods.approve(market.options.address, tokenId).send({from: sellerCross.eth});132 await collection.methods.approve(market.options.address, tokenId).send({from: sellerCross.eth});
133
134 // Seller has no funds at all, his transactions are sponsored
135 const sellerBalance = await helper.balance.getEthereum(sellerCross.eth);
136 expect(sellerBalance).to.be.eq(0n);
107137
108 const putResult = await market.methods.put(collectionId, tokenId, 1, 1, sellerCross).send({from: sellerCross.eth});138 const putResult = await market.methods.put(collectionId, tokenId, PRICE.toString(), 1, sellerCross).send({
139 from: sellerCross.eth, gasLimit: 1_000_000
140 });
109 expect(putResult.events.TokenIsUpForSale).is.not.undefined;141 expect(putResult.events.TokenIsUpForSale).is.not.undefined;
142
143 // Seller balance are still 0
144 const sellerBalanceAfter = await helper.balance.getEthereum(sellerCross.eth);
145 expect(sellerBalanceAfter).to.be.eq(0n);
146
110 let ownerCross = await collection.methods.ownerOfCross(tokenId).call();147 let ownerCross = await collection.methods.ownerOfCross(tokenId).call();
111 expect(ownerCross.eth).to.be.eq(sellerCross.eth);148 expect(ownerCross.eth).to.be.eq(sellerCross.eth);
112 expect(ownerCross.sub).to.be.eq(sellerCross.sub);149 expect(ownerCross.sub).to.be.eq(sellerCross.sub);
113150
114 const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 600n);151 const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 10n);
152 console.log('before buy');
153
154 // Buyer has only 10 UNQ
155 const buyerBalance = await helper.balance.getEthereum(buyerCross.eth);
156 expect(buyerBalance).to.be.eq(10n * ONE_TOKEN)
157
115 const buyResult = await market.methods.buy(collectionId, tokenId, 1, buyerCross).send({from: buyerCross.eth, value: 1});158 const buyResult = await market.methods.buy(collectionId, tokenId, 1, buyerCross).send({from: buyerCross.eth, value: PRICE.toString(), gasLimit: 1_000_000});
116 expect(buyResult.events.TokenIsPurchased).is.not.undefined;159 expect(buyResult.events.TokenIsPurchased).is.not.undefined;
160
161 // Buyer pays only value, transaction use sponsoring
162 const buyerBalanceAfter = await helper.balance.getEthereum(buyerCross.eth);
163 expect(buyerBalanceAfter).to.be.eq(10n * ONE_TOKEN - PRICE);
164
117 ownerCross = await collection.methods.ownerOfCross(tokenId).call();165 ownerCross = await collection.methods.ownerOfCross(tokenId).call();
118 expect(ownerCross.eth).to.be.eq(buyerCross.eth);166 expect(ownerCross.eth).to.be.eq(buyerCross.eth);