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: UNLICENSED2pragma solidity 0.8.17;34import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";5import "@openzeppelin/contracts/token/ERC721/IERC721.sol";6import { UniqueNFT, CrossAddress } from "@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol";7import { UniqueFungible, CrossAddress as CrossAddressF } from "@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol";8import "@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol";9import "./royalty/UniqueRoyaltyHelper.sol";1011contract Market {12 using ERC165Checker for address;1314 struct Order {15 uint32 id;16 uint32 collectionId;17 uint32 tokenId;18 uint32 amount;19 uint256 price;20 CrossAddress seller;21 }2223 uint32 public constant version = 0;24 uint32 public constant buildVersion = 1;25 bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;26 bytes4 private constant InterfaceId_ERC165 = 0x5755c3f2;27 CollectionHelpers private constant collectionHelpers =28 CollectionHelpers(0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F);2930 mapping(uint32 => mapping(uint32 => Order)) orders;31 uint32 private idCount = 1;32 uint32 public marketFee;33 uint64 public ctime;34 address selfAddress;35 address public ownerAddress;36 mapping(address => bool) public admins;3738 event TokenIsUpForSale(uint32 version, Order item);39 event TokenRevoke(uint32 version, Order item, uint32 amount);40 event TokenIsApproved(uint32 version, Order item);41 event TokenIsPurchased(42 uint32 version,43 Order item,44 uint32 salesAmount,45 CrossAddress buyer,46 RoyaltyAmount[] royalties47 );48 event Log(string message);4950 error InvalidArgument(string info);51 error InvalidMarketFee();52 error SellerIsNotOwner();53 error TokenIsAlreadyOnSale();54 error TokenIsNotApproved();55 error CollectionNotFound();56 error CollectionNotSupportedERC721();57 error OrderNotFound();58 error TooManyAmountRequested();59 error NotEnoughMoneyError();60 error FailTransferToken(string reason);6162 modifier onlyOwner() {63 require(msg.sender == ownerAddress, "Only owner can");64 _;65 }6667 modifier onlyAdmin() {68 require(msg.sender == ownerAddress || admins[msg.sender], "Only admin can");69 _;70 }7172 modifier validCrossAddress(address eth, uint256 sub) {73 if (eth == address(0) && sub == 0) {74 revert InvalidArgument("Ethereum and Substrate addresses cannot be null at the same time");75 }7677 if (eth != address(0) && sub != 0) {78 revert InvalidArgument("Ethereum and Substrate addresses cannot be not null at the same time");79 }8081 _;82 }8384 constructor(uint32 fee, uint64 timestamp) {85 marketFee = fee;86 ctime = timestamp;8788 if (marketFee == 0 || marketFee >= 100) {89 revert InvalidMarketFee();90 }9192 ownerAddress = msg.sender;93 selfAddress = address(this);94 }9596 function getErc721(uint32 collectionId) private view returns (IERC721) {97 address collectionAddress = collectionHelpers.collectionAddress(98 collectionId99 );100101 uint size;102 assembly {103 size := extcodesize(collectionAddress)104 }105106 if (size == 0) {107 revert CollectionNotFound();108 }109110 if (!collectionAddress.supportsInterface(InterfaceId_ERC721)) {111 revert CollectionNotSupportedERC721();112 }113114 return IERC721(collectionAddress);115 }116117 // ################################################################118 // Set new contract owner #119 // ################################################################120121 function setOwner() public onlyOwner {122 ownerAddress = msg.sender;123 }124125 // ################################################################126 // Add new admin #127 // ################################################################128129 function addAdmin(address admin) public onlyAdmin {130 admins[admin] = true;131 }132133 // ################################################################134 // Remove admin #135 // ################################################################136137 function removeAdmin(address admin) public onlyAdmin {138 delete admins[admin];139 }140141 // ################################################################142 // Place a token for sale #143 // ################################################################144145 function put(146 uint32 collectionId,147 uint32 tokenId,148 uint256 price,149 uint32 amount,150 CrossAddress memory seller151 ) public validCrossAddress(seller.eth, seller.sub) {152 if (price == 0) {153 revert InvalidArgument("price must not be zero");154 }155 if (amount == 0) {156 revert InvalidArgument("amount must not be zero");157 }158159 if (orders[collectionId][tokenId].price > 0) {160 revert TokenIsAlreadyOnSale();161 }162163 IERC721 erc721 = getErc721(collectionId);164165 if (erc721.ownerOf(tokenId) != msg.sender) {166 revert SellerIsNotOwner();167 }168169 if (erc721.getApproved(tokenId) != selfAddress) {170 revert TokenIsNotApproved();171 }172173 Order memory order = Order(174 0,175 collectionId,176 tokenId,177 amount,178 price,179 seller180 );181182 order.id = idCount++;183 orders[collectionId][tokenId] = order;184185 emit TokenIsUpForSale(version, order);186 }187188 // ################################################################189 // Get order #190 // ################################################################191192 function getOrder(193 uint32 collectionId,194 uint32 tokenId195 ) external view returns (Order memory) {196 return orders[collectionId][tokenId];197 }198199 // ################################################################200 // Revoke the token from the sale #201 // ################################################################202203 function revoke(204 uint32 collectionId,205 uint32 tokenId,206 uint32 amount207 ) external {208 if (amount == 0) {209 revert InvalidArgument("amount must not be zero");210 }211212 Order memory order = orders[collectionId][tokenId];213214 if (order.price == 0) {215 revert OrderNotFound();216 }217218 if (amount > order.amount) {219 revert TooManyAmountRequested();220 }221222 IERC721 erc721 = getErc721(collectionId);223224 address ethAddress;225 if (order.seller.eth != address(0)) {226 ethAddress = order.seller.eth;227 } else {228 ethAddress = payable(address(uint160(order.seller.sub >> 96)));229 }230 if (erc721.ownerOf(tokenId) != ethAddress) {231 revert SellerIsNotOwner();232 }233234 order.amount -= amount;235 if (order.amount == 0) {236 delete orders[collectionId][tokenId];237 } else {238 orders[collectionId][tokenId] = order;239 }240241 emit TokenRevoke(version, order, amount);242 }243244 // ################################################################245 // Check approved #246 // ################################################################247248 function checkApproved(uint32 collectionId, uint32 tokenId) public onlyAdmin {249 Order memory order = orders[collectionId][tokenId];250 if (order.price == 0) {251 revert OrderNotFound();252 }253254 IERC721 erc721 = getErc721(collectionId);255256 if (erc721.getApproved(tokenId) != selfAddress || erc721.ownerOf(tokenId) != getAddressFromCrossAccount(order.seller)) {257 uint32 amount = order.amount;258 order.amount = 0;259 emit TokenRevoke(version, order, amount);260261 delete orders[collectionId][tokenId];262 } else {263 emit TokenIsApproved(version, order);264 }265 }266267 function getAddressFromCrossAccount(CrossAddress memory account) private pure returns (address) {268 if (account.eth != address(0)) {269 return account.eth;270 } else {271 return address(uint160(account.sub >> 96));272 }273 }274275 function revokeAdmin(uint32 collectionId, uint32 tokenId) public onlyAdmin {276 Order memory order = orders[collectionId][tokenId];277 if (order.price == 0) {278 revert OrderNotFound();279 }280281 uint32 amount = order.amount;282 order.amount = 0;283 emit TokenRevoke(version, order, amount);284285 delete orders[collectionId][tokenId];286 }287288 // ################################################################289 // Buy a token #290 // ################################################################291292 function buy(293 uint32 collectionId,294 uint32 tokenId,295 uint32 amount,296 CrossAddress memory buyer297 ) public payable validCrossAddress(buyer.eth, buyer.sub) {298 if (msg.value == 0) {299 revert InvalidArgument("msg.value must not be zero");300 }301 if (amount == 0) {302 revert InvalidArgument("amount must not be zero");303 }304305 Order memory order = orders[collectionId][tokenId];306 if (order.price == 0) {307 revert OrderNotFound();308 }309310 if (amount > order.amount) {311 revert TooManyAmountRequested();312 }313314 uint256 totalValue = order.price * amount;315 uint256 feeValue = (totalValue * marketFee) / 100;316317 if (msg.value < totalValue) {318 revert NotEnoughMoneyError();319 }320321 IERC721 erc721 = getErc721(order.collectionId);322 if (erc721.getApproved(tokenId) != selfAddress) {323 revert TokenIsNotApproved();324 }325326 order.amount -= amount;327 if (order.amount == 0) {328 delete orders[collectionId][tokenId];329 } else {330 orders[collectionId][tokenId] = order;331 }332333 address collectionAddress = collectionHelpers.collectionAddress(collectionId);334 UniqueNFT nft = UniqueNFT(collectionAddress);335336 nft.transferFromCross(337 order.seller,338 buyer,339 order.tokenId340 );341342 (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue);343344 sendMoney(order.seller, totalValue - feeValue - totalRoyalty);345346 if (msg.value > totalValue) {347 // todo, send money to signer or buyer ?348 payable(msg.sender).transfer(msg.value - totalValue);349 }350351 emit TokenIsPurchased(version, order, amount, buyer, royalties);352 }353354 function sendMoney(CrossAddress memory to, uint256 money) private {355 address collectionAddress = collectionHelpers.collectionAddress(0);356357 UniqueFungible fungible = UniqueFungible(collectionAddress);358359 CrossAddressF memory fromF = CrossAddressF(selfAddress, 0);360 CrossAddressF memory toF = CrossAddressF(to.eth, to.sub);361362 fungible.transferFromCross(fromF, toF, money);363 }364365 function sendRoyalties(address collection, uint tokenId, uint sellPrice) private returns (uint256, RoyaltyAmount[] memory) {366 RoyaltyAmount[] memory royalties = UniqueRoyaltyHelper.calculate(collection, tokenId, sellPrice);367368 uint256 totalRoyalty = 0;369370 for (uint256 i=0; i<royalties.length; i++) {371 RoyaltyAmount memory royalty = royalties[i];372373 totalRoyalty += royalty.amount;374375 sendMoney(royalty.crossAddress, royalty.amount);376 }377378 return (totalRoyalty, royalties);379 }380381 function withdraw(address transferTo) public onlyOwner {382 uint256 balance = selfAddress.balance;383384 if (balance > 0) {385 payable(transferTo).transfer(balance);386 }387 }388}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);