difftreelog
Test for market sponsoring
in: master
3 files changed
tests/package.jsondiffbeforeafterboth47 "testEthNesting": "yarn _test './**/eth/nesting/**/*.*test.ts'",47 "testEthNesting": "yarn _test './**/eth/nesting/**/*.*test.ts'",48 "testEthFractionalizer": "yarn _test './**/eth/fractionalizer/**/*.*test.ts'",48 "testEthFractionalizer": "yarn _test './**/eth/fractionalizer/**/*.*test.ts'",49 "testEthMarketplace": "yarn _test './**/eth/marketplace/**/*.*test.ts'",49 "testEthMarketplace": "yarn _test './**/eth/marketplace/**/*.*test.ts'",50 "testEthMarket": "yarn _test './**/eth/marketplace-v2/**/*.*test.ts'",50 "testSub": "yarn _test './**/sub/**/*.*test.ts'",51 "testSub": "yarn _test './**/sub/**/*.*test.ts'",51 "testSubNesting": "yarn _test './**/sub/nesting/**/*.*test.ts'",52 "testSubNesting": "yarn _test './**/sub/nesting/**/*.*test.ts'",52 "testEvent": "yarn _test ./src/check-event/*.*test.ts",53 "testEvent": "yarn _test ./src/check-event/*.*test.ts",tests/src/eth/marketplace-v2/Market.soldiffbeforeafterboth1// SPDX-License-Identifier: UNLICENSED1// SPDX-License-Identifier: UNLICENSED2pragma solidity 0.8.17;2pragma solidity 0.8.17;334import "@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";101211contract Market {13contract Market is Ownable, ReentrancyGuard {12 using ERC165Checker for address;14 using ERC165Checker for address;131514 struct Order {16 struct Order {21 }23 }222423 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;373857 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);6162 modifier onlyOwner() {63 require(msg.sender == ownerAddress, "Only owner can");64 _;65 }666367 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 }716885 marketFee = fee;82 marketFee = fee;86 ctime = timestamp;83 ctime = timestamp;878488 if (marketFee == 0 || marketFee >= 100) {85 if (marketFee >= 100) {89 revert InvalidMarketFee();86 revert InvalidMarketFee();90 }87 }9192 ownerAddress = msg.sender;93 selfAddress = address(this);94 }88 }958996 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 }116110117 // ################################################################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 add121 function setOwner() public onlyOwner {115 */122 ownerAddress = msg.sender;123 }124125 // ################################################################126 // Add new admin #127 // ################################################################128129 function addAdmin(address admin) public onlyAdmin {116 function addAdmin(address admin) public onlyAdmin {130 admins[admin] = true;117 admins[admin] = true;131 }118 }132119133 // ################################################################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 add124 */137 function removeAdmin(address admin) public onlyAdmin {125 function removeAdmin(address admin) public onlyAdmin {138 delete admins[admin];126 delete admins[admin];139 }127 }140128141 // ################################################################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 collection133 * @param tokenId: ID of the token134 * @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 }168161169 if (erc721.getApproved(tokenId) != selfAddress) {162 if (erc721.getApproved(tokenId) != address(this)) {170 revert TokenIsNotApproved();163 revert TokenIsNotApproved();171 }164 }172165185 emit TokenIsUpForSale(version, order);178 emit TokenIsUpForSale(version, order);186 }179 }187180188 // ################################################################181 /**189 // Get order #182 * Get information about the listed token order190 // ################################################################183 *191184 * @param collectionId: ID of the token collection185 * @param tokenId: ID of the token186 * @return The order information187 */192 function getOrder(188 function getOrder(193 uint32 collectionId,189 uint32 collectionId,194 uint32 tokenId190 uint32 tokenId195 ) external view returns (Order memory) {191 ) external view returns (Order memory) {196 return orders[collectionId][tokenId];192 return orders[collectionId][tokenId];197 }193 }198194199 // ################################################################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 collection199 * @param tokenId: ID of the token200 * @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 }243242244 // ################################################################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 collection247 * @param tokenId: ID of the token248 */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) {253254254 IERC721 erc721 = getErc721(collectionId);255 IERC721 erc721 = getErc721(collectionId);255256256 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 }274275276 /**277 * Revoke the token from the sale. Only the contract admin can use this method.278 *279 * @param collectionId: ID of the token collection280 * @param tokenId: ID of the token281 */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 }287294288 // ################################################################295 /**289 // Buy a token #296 * Buy a token (partially for an RFT).290 // ################################################################297 *291298 * @param collectionId: ID of the token collection299 * @param tokenId: ID of the token300 * @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 address302 */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 buyer297 ) 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 }320331321 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 }325336339 order.tokenId350 order.tokenId340 );351 );341352342 (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue);353 (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue - feeValue);354355 if (totalRoyalty >= totalValue - feeValue) {356 revert InvalidRoyaltiesError(totalRoyalty);357 }343358344 sendMoney(order.seller, totalValue - feeValue - totalRoyalty);359 sendMoney(order.seller, totalValue - feeValue - totalRoyalty);345360346 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 }350364351 emit TokenIsPurchased(version, order, amount, buyer, royalties);365 emit TokenIsPurchased(version, order, amount, buyer, royalties);356370357 UniqueFungible fungible = UniqueFungible(collectionAddress);371 UniqueFungible fungible = UniqueFungible(collectionAddress);358372359 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);361375362 fungible.transferFromCross(fromF, toF, money);376 fungible.transferFromCross(fromF, toF, money);379 }393 }380394381 function withdraw(address transferTo) public onlyOwner {395 function withdraw(address transferTo) public onlyOwner {382 uint256 balance = selfAddress.balance;396 uint256 balance = address(this).balance;383397384 if (balance > 0) {398 if (balance > 0) {385 payable(transferTo).transfer(balance);399 payable(transferTo).transfer(balance);tests/src/eth/marketplace-v2/marketplace.test.tsdiffbeforeafterboth161617import {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 });9510796 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 UNQ97 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);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);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});99123100 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});102128103 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 sponsored135 const sellerBalance = await helper.balance.getEthereum(sellerCross.eth);136 expect(sellerBalance).to.be.eq(0n);107137108 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_000140 });109 expect(putResult.events.TokenIsUpForSale).is.not.undefined;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 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);113150114 const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 600n);151 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)157115 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 sponsoring162 const buyerBalanceAfter = await helper.balance.getEthereum(buyerCross.eth);163 expect(buyerBalanceAfter).to.be.eq(10n * ONE_TOKEN - PRICE);164117 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);