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
1// SPDX-License-Identifier: UNLICENSED1// SPDX-License-Identifier: UNLICENSED
2pragma solidity 0.8.17;2pragma solidity 0.8.17;
33
4import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
4import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";5import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
5import "@openzeppelin/contracts/token/ERC721/IERC721.sol";6import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
7import "@openzeppelin/contracts/access/Ownable.sol";
6import { UniqueNFT, CrossAddress } from "@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol";8import { UniqueNFT, CrossAddress } from "@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol";
7import { UniqueFungible, CrossAddress as CrossAddressF } from "@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol";9import { UniqueFungible, CrossAddress as CrossAddressF } from "@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol";
8import "@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol";10import "@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol";
9import "./royalty/UniqueRoyaltyHelper.sol";11import "./royalty/UniqueRoyaltyHelper.sol";
1012
11contract Market {13contract Market is Ownable, ReentrancyGuard {
12 using ERC165Checker for address;14 using ERC165Checker for address;
1315
14 struct Order {16 struct Order {
21 }23 }
2224
23 uint32 public constant version = 0;25 uint32 public constant version = 0;
24 uint32 public constant buildVersion = 1;26 uint32 public constant buildVersion = 3;
25 bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;27 bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
26 bytes4 private constant InterfaceId_ERC165 = 0x5755c3f2;28 bytes4 private constant InterfaceId_ERC165 = 0x5755c3f2;
27 CollectionHelpers private constant collectionHelpers =29 CollectionHelpers private constant collectionHelpers =
31 uint32 private idCount = 1;33 uint32 private idCount = 1;
32 uint32 public marketFee;34 uint32 public marketFee;
33 uint64 public ctime;35 uint64 public ctime;
34 address selfAddress;
35 address public ownerAddress;36 address public ownerAddress;
36 mapping(address => bool) public admins;37 mapping(address => bool) public admins;
3738
57 error OrderNotFound();58 error OrderNotFound();
58 error TooManyAmountRequested();59 error TooManyAmountRequested();
59 error NotEnoughMoneyError();60 error NotEnoughMoneyError();
61 error InvalidRoyaltiesError(uint256 totalRoyalty);
60 error FailTransferToken(string reason);62 error FailTransferToken(string reason);
61
62 modifier onlyOwner() {
63 require(msg.sender == ownerAddress, "Only owner can");
64 _;
65 }
6663
67 modifier onlyAdmin() {64 modifier onlyAdmin() {
68 require(msg.sender == ownerAddress || admins[msg.sender], "Only admin can");65 require(msg.sender == this.owner() || admins[msg.sender], "Only admin can");
69 _;66 _;
70 }67 }
7168
85 marketFee = fee;82 marketFee = fee;
86 ctime = timestamp;83 ctime = timestamp;
8784
88 if (marketFee == 0 || marketFee >= 100) {85 if (marketFee >= 100) {
89 revert InvalidMarketFee();86 revert InvalidMarketFee();
90 }87 }
91
92 ownerAddress = msg.sender;
93 selfAddress = address(this);
94 }88 }
9589
96 function getErc721(uint32 collectionId) private view returns (IERC721) {90 function getErc721(uint32 collectionId) private view returns (IERC721) {
114 return IERC721(collectionAddress);108 return IERC721(collectionAddress);
115 }109 }
116110
117 // ################################################################111 /**
118 // Set new contract owner #112 * Add new admin. Only owner or an existing admin can add admins.
119 // ################################################################113 *
120114 * @param admin: Address of a new admin to add
121 function setOwner() public onlyOwner {115 */
122 ownerAddress = msg.sender;
123 }
124
125 // ################################################################
126 // Add new admin #
127 // ################################################################
128
129 function addAdmin(address admin) public onlyAdmin {116 function addAdmin(address admin) public onlyAdmin {
130 admins[admin] = true;117 admins[admin] = true;
131 }118 }
132119
133 // ################################################################120 /**
134 // Remove admin #121 * Remove an admin. Only owner or an existing admin can remove admins.
135 // ################################################################122 *
136123 * @param admin: Address of a new admin to add
124 */
137 function removeAdmin(address admin) public onlyAdmin {125 function removeAdmin(address admin) public onlyAdmin {
138 delete admins[admin];126 delete admins[admin];
139 }127 }
140128
141 // ################################################################129 /**
142 // Place a token for sale #130 * Place an NFT or RFT token for sale. It must be pre-approved for transfers by this contract address.
143 // ################################################################131 *
144132 * @param collectionId: ID of the token collection
133 * @param tokenId: ID of the token
134 * @param price: Price (with proper network currency decimals)
135 * @param amount: Number of token fractions to list (must always be 1 for NFT)
136 * @param seller: The seller cross-address (the beneficiary account to receive payment, may be different from transaction sender)
137 */
145 function put(138 function put(
146 uint32 collectionId,139 uint32 collectionId,
147 uint32 tokenId,140 uint32 tokenId,
166 revert SellerIsNotOwner();159 revert SellerIsNotOwner();
167 }160 }
168161
169 if (erc721.getApproved(tokenId) != selfAddress) {162 if (erc721.getApproved(tokenId) != address(this)) {
170 revert TokenIsNotApproved();163 revert TokenIsNotApproved();
171 }164 }
172165
185 emit TokenIsUpForSale(version, order);178 emit TokenIsUpForSale(version, order);
186 }179 }
187180
188 // ################################################################181 /**
189 // Get order #182 * Get information about the listed token order
190 // ################################################################183 *
191184 * @param collectionId: ID of the token collection
185 * @param tokenId: ID of the token
186 * @return The order information
187 */
192 function getOrder(188 function getOrder(
193 uint32 collectionId,189 uint32 collectionId,
194 uint32 tokenId190 uint32 tokenId
195 ) external view returns (Order memory) {191 ) external view returns (Order memory) {
196 return orders[collectionId][tokenId];192 return orders[collectionId][tokenId];
197 }193 }
198194
199 // ################################################################195 /**
200 // Revoke the token from the sale #196 * Revoke the token from the sale. Only the original lister can use this method.
201 // ################################################################197 *
202198 * @param collectionId: ID of the token collection
199 * @param tokenId: ID of the token
200 * @param amount: Number of token fractions to de-list (must always be 1 for NFT)
201 */
203 function revoke(202 function revoke(
204 uint32 collectionId,203 uint32 collectionId,
205 uint32 tokenId,204 uint32 tokenId,
241 emit TokenRevoke(version, order, amount);240 emit TokenRevoke(version, order, amount);
242 }241 }
243242
244 // ################################################################243 /**
245 // Check approved #244 * Test if the token is still approved to be transferred by this contract and delete the order if not.
246 // ################################################################245 *
247246 * @param collectionId: ID of the token collection
247 * @param tokenId: ID of the token
248 */
248 function checkApproved(uint32 collectionId, uint32 tokenId) public onlyAdmin {249 function checkApproved(uint32 collectionId, uint32 tokenId) public onlyAdmin {
249 Order memory order = orders[collectionId][tokenId];250 Order memory order = orders[collectionId][tokenId];
250 if (order.price == 0) {251 if (order.price == 0) {
253254
254 IERC721 erc721 = getErc721(collectionId);255 IERC721 erc721 = getErc721(collectionId);
255256
256 if (erc721.getApproved(tokenId) != selfAddress || erc721.ownerOf(tokenId) != getAddressFromCrossAccount(order.seller)) {257 if (erc721.getApproved(tokenId) != address(this) || erc721.ownerOf(tokenId) != getAddressFromCrossAccount(order.seller)) {
257 uint32 amount = order.amount;258 uint32 amount = order.amount;
258 order.amount = 0;259 order.amount = 0;
259 emit TokenRevoke(version, order, amount);260 emit TokenRevoke(version, order, amount);
272 }273 }
273 }274 }
274275
276 /**
277 * Revoke the token from the sale. Only the contract admin can use this method.
278 *
279 * @param collectionId: ID of the token collection
280 * @param tokenId: ID of the token
281 */
275 function revokeAdmin(uint32 collectionId, uint32 tokenId) public onlyAdmin {282 function revokeAdmin(uint32 collectionId, uint32 tokenId) public onlyAdmin {
276 Order memory order = orders[collectionId][tokenId];283 Order memory order = orders[collectionId][tokenId];
277 if (order.price == 0) {284 if (order.price == 0) {
285 delete orders[collectionId][tokenId];292 delete orders[collectionId][tokenId];
286 }293 }
287294
288 // ################################################################295 /**
289 // Buy a token #296 * Buy a token (partially for an RFT).
290 // ################################################################297 *
291298 * @param collectionId: ID of the token collection
299 * @param tokenId: ID of the token
300 * @param amount: Number of token fractions to buy (must always be 1 for NFT)
301 * @param buyer: Cross-address of the buyer, eth part must be equal to the transaction signer address
302 */
292 function buy(303 function buy(
293 uint32 collectionId,304 uint32 collectionId,
294 uint32 tokenId,305 uint32 tokenId,
295 uint32 amount,306 uint32 amount,
296 CrossAddress memory buyer307 CrossAddress memory buyer
297 ) public payable validCrossAddress(buyer.eth, buyer.sub) {308 ) public payable validCrossAddress(buyer.eth, buyer.sub) nonReentrant {
298 if (msg.value == 0) {309 if (msg.value == 0) {
299 revert InvalidArgument("msg.value must not be zero");310 revert InvalidArgument("msg.value must not be zero");
300 }311 }
319 }330 }
320331
321 IERC721 erc721 = getErc721(order.collectionId);332 IERC721 erc721 = getErc721(order.collectionId);
322 if (erc721.getApproved(tokenId) != selfAddress) {333 if (erc721.getApproved(tokenId) != address(this)) {
323 revert TokenIsNotApproved();334 revert TokenIsNotApproved();
324 }335 }
325336
339 order.tokenId350 order.tokenId
340 );351 );
341352
342 (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue);353 (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue - feeValue);
354
355 if (totalRoyalty >= totalValue - feeValue) {
356 revert InvalidRoyaltiesError(totalRoyalty);
357 }
343358
344 sendMoney(order.seller, totalValue - feeValue - totalRoyalty);359 sendMoney(order.seller, totalValue - feeValue - totalRoyalty);
345360
346 if (msg.value > totalValue) {361 if (msg.value > totalValue) {
347 // todo, send money to signer or buyer ?
348 payable(msg.sender).transfer(msg.value - totalValue);362 sendMoney(buyer, msg.value - totalValue);
349 }363 }
350364
351 emit TokenIsPurchased(version, order, amount, buyer, royalties);365 emit TokenIsPurchased(version, order, amount, buyer, royalties);
356370
357 UniqueFungible fungible = UniqueFungible(collectionAddress);371 UniqueFungible fungible = UniqueFungible(collectionAddress);
358372
359 CrossAddressF memory fromF = CrossAddressF(selfAddress, 0);373 CrossAddressF memory fromF = CrossAddressF(address(this), 0);
360 CrossAddressF memory toF = CrossAddressF(to.eth, to.sub);374 CrossAddressF memory toF = CrossAddressF(to.eth, to.sub);
361375
362 fungible.transferFromCross(fromF, toF, money);376 fungible.transferFromCross(fromF, toF, money);
379 }393 }
380394
381 function withdraw(address transferTo) public onlyOwner {395 function withdraw(address transferTo) public onlyOwner {
382 uint256 balance = selfAddress.balance;396 uint256 balance = address(this).balance;
383397
384 if (balance > 0) {398 if (balance > 0) {
385 payable(transferTo).transfer(balance);399 payable(transferTo).transfer(balance);
modifiedtests/src/eth/marketplace-v2/marketplace.test.tsdiffbeforeafterboth
--- a/tests/src/eth/marketplace-v2/marketplace.test.ts
+++ b/tests/src/eth/marketplace-v2/marketplace.test.ts
@@ -16,7 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {readFile} from 'fs/promises';
-import {EthUniqueHelper, itEth, usingEthPlaygrounds} from '../util';
+import {EthUniqueHelper, SponsoringMode, itEth, usingEthPlaygrounds} from '../util';
 import {makeNames} from '../../util';
 import {expect} from 'chai';
 import Web3 from 'web3';
@@ -51,6 +51,18 @@
           fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol`,
         },
         {
+          solPath: '@openzeppelin/contracts/access/Ownable.sol',
+          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/access/Ownable.sol`,
+        },
+        {
+          solPath: '@openzeppelin/contracts/utils/Context.sol',
+          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/Context.sol`,
+        },
+        {
+          solPath: '@openzeppelin/contracts/security/ReentrancyGuard.sol',
+          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol`,
+        },
+        {
           solPath: '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol',
           fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/ERC165Checker.sol`,
         },
@@ -94,26 +106,62 @@
   });
 
   itEth('Put + Buy [eth]', async ({helper}) => {
-    const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);
+    const ONE_TOKEN = helper.balance.getOneTokenNominal();
+    const PRICE = 2n * ONE_TOKEN;  // 2 UNQ
+    const marketOwner = await helper.eth.createAccountWithBalance(donor, 60000n);
     const market = await deployMarket(helper, marketOwner);
+    const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);
+    await contractHelpers.methods.selfSponsoredEnable(market.options.address).send({from: marketOwner});
+    await helper.eth.transferBalanceFromSubstrate(donor, market.options.address, 10n);
 
+    // TODO: this should work too, instead of selfSponsoring!
+    // await contractHelpers.methods.setSponsor(market.options.address, marketOwner).send({from: marketOwner})
+    // await contractHelpers.methods.confirmSponsorship(market.options.address);
+    
+    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});
+    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});
+
     const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');
-    const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner);
+    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);
+    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});
+    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});
 
-    const sellerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 600n);
+    const sellerCross = helper.ethCrossAccount.createAccount();
     const result = await collection.methods.mintCross(sellerCross, []).send();
     const tokenId = result.events.Transfer.returnValues.tokenId;
     await collection.methods.approve(market.options.address, tokenId).send({from: sellerCross.eth});
+    
+    // Seller has no funds at all, his transactions are sponsored
+    const sellerBalance = await helper.balance.getEthereum(sellerCross.eth);
+    expect(sellerBalance).to.be.eq(0n);
 
-    const putResult = await market.methods.put(collectionId, tokenId, 1, 1, sellerCross).send({from: sellerCross.eth});
+    const putResult = await market.methods.put(collectionId, tokenId, PRICE.toString(), 1, sellerCross).send({
+      from: sellerCross.eth, gasLimit: 1_000_000
+    });
     expect(putResult.events.TokenIsUpForSale).is.not.undefined;
+
+    // Seller balance are still 0
+    const sellerBalanceAfter = await helper.balance.getEthereum(sellerCross.eth);
+    expect(sellerBalanceAfter).to.be.eq(0n);
+    
     let ownerCross = await collection.methods.ownerOfCross(tokenId).call();
     expect(ownerCross.eth).to.be.eq(sellerCross.eth);
     expect(ownerCross.sub).to.be.eq(sellerCross.sub);
 
-    const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 600n);
-    const buyResult = await market.methods.buy(collectionId, tokenId, 1, buyerCross).send({from: buyerCross.eth, value: 1});
+    const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 10n);
+    console.log('before buy');
+
+    // Buyer has only 10 UNQ
+    const buyerBalance = await helper.balance.getEthereum(buyerCross.eth);
+    expect(buyerBalance).to.be.eq(10n * ONE_TOKEN)
+
+    const buyResult = await market.methods.buy(collectionId, tokenId, 1, buyerCross).send({from: buyerCross.eth, value: PRICE.toString(), gasLimit: 1_000_000});
     expect(buyResult.events.TokenIsPurchased).is.not.undefined;
+    
+    // Buyer pays only value, transaction use sponsoring
+    const buyerBalanceAfter = await helper.balance.getEthereum(buyerCross.eth);
+    expect(buyerBalanceAfter).to.be.eq(10n * ONE_TOKEN - PRICE);
+
     ownerCross = await collection.methods.ownerOfCross(tokenId).call();
     expect(ownerCross.eth).to.be.eq(buyerCross.eth);
     expect(ownerCross.sub).to.be.eq(buyerCross.sub);