difftreelog
Test for market sponsoring
in: master
3 files changed
tests/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",
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.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);