difftreelog
Merge pull request #954 from UniqueNetwork/feature/update_market_v2_contract
in: master
4 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 "@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol";8import "./royalty/UniqueRoyaltyHelper.sol";910contract Market {11 using ERC165Checker for address;1213 struct Order {14 uint32 id;15 uint32 collectionId;16 uint32 tokenId;17 uint32 amount;18 uint256 price;19 CrossAddress seller;20 }2122 uint32 public constant version = 0;23 bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;24 bytes4 private constant InterfaceId_ERC165 = 0x5755c3f2;25 CollectionHelpers private constant collectionHelpers =26 CollectionHelpers(0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F);2728 mapping(uint32 => mapping(uint32 => Order)) orders;29 uint32 private idCount = 1;30 uint32 public marketFee;31 uint64 public ctime;32 address selfAddress;33 address public ownerAddress;34 mapping(address => bool) public admins;3536 event TokenIsUpForSale(uint32 version, Order item);37 event TokenRevoke(uint32 version, Order item, uint32 amount);38 event TokenIsApproved(uint32 version, Order item);39 event TokenIsPurchased(40 uint32 version,41 Order item,42 uint32 salesAmount,43 CrossAddress buyer,44 RoyaltyAmount[] royalties45 );46 event Log(string message);4748 error InvalidArgument(string info);49 error InvalidMarketFee();50 error SellerIsNotOwner();51 error TokenIsAlreadyOnSale();52 error TokenIsNotApproved();53 error CollectionNotFound();54 error CollectionNotSupportedERC721();55 error OrderNotFound();56 error TooManyAmountRequested();57 error NotEnoughMoneyError();58 error FailTransferToken(string reason);5960 modifier onlyOwner() {61 require(msg.sender == ownerAddress, "Only owner can");62 _;63 }6465 modifier onlyAdmin() {66 require(msg.sender == ownerAddress || admins[msg.sender], "Only admin can");67 _;68 }6970 modifier validCrossAddress(address eth, uint256 sub) {71 if (eth == address(0) && sub == 0) {72 revert InvalidArgument("Ethereum and Substrate addresses cannot be null at the same time");73 }7475 if (eth != address(0) && sub != 0) {76 revert InvalidArgument("Ethereum and Substrate addresses cannot be not null at the same time");77 }7879 _;80 }8182 constructor(uint32 fee, uint64 timestamp) {83 marketFee = fee;84 ctime = timestamp;8586 if (marketFee == 0 || marketFee >= 100) {87 revert InvalidMarketFee();88 }8990 ownerAddress = msg.sender;91 selfAddress = address(this);92 }9394 function getErc721(uint32 collectionId) private view returns (IERC721) {95 address collectionAddress = collectionHelpers.collectionAddress(96 collectionId97 );9899 uint size;100 assembly {101 size := extcodesize(collectionAddress)102 }103104 if (size == 0) {105 revert CollectionNotFound();106 }107108 if (!collectionAddress.supportsInterface(InterfaceId_ERC721)) {109 revert CollectionNotSupportedERC721();110 }111112 return IERC721(collectionAddress);113 }114115 // ################################################################116 // Set new contract owner #117 // ################################################################118119 function setOwner() public onlyOwner {120 ownerAddress = msg.sender;121 }122123 // ################################################################124 // Add new admin #125 // ################################################################126127 function addAdmin(address admin) public onlyAdmin {128 admins[admin] = true;129 }130131 // ################################################################132 // Remove admin #133 // ################################################################134135 function removeAdmin(address admin) public onlyAdmin {136 delete admins[admin];137 }138139 // ################################################################140 // Place a token for sale #141 // ################################################################142143 function put(144 uint32 collectionId,145 uint32 tokenId,146 uint256 price,147 uint32 amount,148 CrossAddress memory seller149 ) public validCrossAddress(seller.eth, seller.sub) {150 if (price == 0) {151 revert InvalidArgument("price must not be zero");152 }153 if (amount == 0) {154 revert InvalidArgument("amount must not be zero");155 }156157 if (orders[collectionId][tokenId].price > 0) {158 revert TokenIsAlreadyOnSale();159 }160161 IERC721 erc721 = getErc721(collectionId);162163 if (erc721.ownerOf(tokenId) != msg.sender) {164 revert SellerIsNotOwner();165 }166167 if (erc721.getApproved(tokenId) != selfAddress) {168 revert TokenIsNotApproved();169 }170171 Order memory order = Order(172 0,173 collectionId,174 tokenId,175 amount,176 price,177 seller178 );179180 order.id = idCount++;181 orders[collectionId][tokenId] = order;182183 emit TokenIsUpForSale(version, order);184 }185186 // ################################################################187 // Get order #188 // ################################################################189190 function getOrder(191 uint32 collectionId,192 uint32 tokenId193 ) external view returns (Order memory) {194 return orders[collectionId][tokenId];195 }196197 // ################################################################198 // Revoke the token from the sale #199 // ################################################################200201 function revoke(202 uint32 collectionId,203 uint32 tokenId,204 uint32 amount205 ) external {206 if (amount == 0) {207 revert InvalidArgument("amount must not be zero");208 }209210 Order memory order = orders[collectionId][tokenId];211212 if (order.price == 0) {213 revert OrderNotFound();214 }215216 if (amount > order.amount) {217 revert TooManyAmountRequested();218 }219220 IERC721 erc721 = getErc721(collectionId);221222 address ethAddress;223 if (order.seller.eth != address(0)) {224 ethAddress = order.seller.eth;225 } else {226 ethAddress = payable(address(uint160(order.seller.sub >> 96)));227 }228 if (erc721.ownerOf(tokenId) != ethAddress) {229 revert SellerIsNotOwner();230 }231232 order.amount -= amount;233 if (order.amount == 0) {234 delete orders[collectionId][tokenId];235 } else {236 orders[collectionId][tokenId] = order;237 }238239 emit TokenRevoke(version, order, amount);240 }241242 // ################################################################243 // Check approved #244 // ################################################################245246 function checkApproved(uint32 collectionId, uint32 tokenId) public onlyAdmin {247 Order memory order = orders[collectionId][tokenId];248 if (order.price == 0) {249 revert OrderNotFound();250 }251252 IERC721 erc721 = getErc721(collectionId);253254 if (erc721.getApproved(tokenId) != selfAddress) {255 uint32 amount = order.amount;256 order.amount = 0;257 emit TokenRevoke(version, order, amount);258259 delete orders[collectionId][tokenId];260 } else {261 emit TokenIsApproved(version, order);262 }263 }264265 // ################################################################266 // Buy a token #267 // ################################################################268269 function buy(270 uint32 collectionId,271 uint32 tokenId,272 uint32 amount,273 CrossAddress memory buyer274 ) public payable validCrossAddress(buyer.eth, buyer.sub) {275 if (msg.value == 0) {276 revert InvalidArgument("msg.value must not be zero");277 }278 if (amount == 0) {279 revert InvalidArgument("amount must not be zero");280 }281282 Order memory order = orders[collectionId][tokenId];283 if (order.price == 0) {284 revert OrderNotFound();285 }286287 if (amount > order.amount) {288 revert TooManyAmountRequested();289 }290291 uint256 totalValue = order.price * amount;292 uint256 feeValue = (totalValue * marketFee) / 100;293294 if (msg.value < totalValue) {295 revert NotEnoughMoneyError();296 }297298 IERC721 erc721 = getErc721(order.collectionId);299 if (erc721.getApproved(tokenId) != selfAddress) {300 revert TokenIsNotApproved();301 }302303 order.amount -= amount;304 if (order.amount == 0) {305 delete orders[collectionId][tokenId];306 } else {307 orders[collectionId][tokenId] = order;308 }309310 address collectionAddress = collectionHelpers.collectionAddress(collectionId);311 UniqueNFT nft = UniqueNFT(collectionAddress);312313 nft.transferFromCross(314 order.seller,315 buyer,316 order.tokenId317 );318319 (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue);320321 sendMoney(order.seller, totalValue - feeValue - totalRoyalty);322323 if (msg.value > totalValue) {324 // todo, send money to signer or buyer ?325 payable(msg.sender).transfer(msg.value - totalValue);326 }327328 emit TokenIsPurchased(version, order, amount, buyer, royalties);329 }330331 function sendMoney(CrossAddress memory to, uint256 money) private {332 address payable eth;333 if (to.eth != address(0)) {334 eth = payable(to.eth);335 } else {336 eth = payable(address(uint160(to.sub >> 96)));337 }338 eth.transfer(money);339 }340341 function sendRoyalties(address collection, uint tokenId, uint sellPrice) private returns (uint256, RoyaltyAmount[] memory) {342 RoyaltyAmount[] memory royalties = UniqueRoyaltyHelper.calculate(collection, tokenId, sellPrice);343344 uint256 totalRoyalty = 0;345346 for (uint256 i=0; i<royalties.length; i++) {347 RoyaltyAmount memory royalty = royalties[i];348349 totalRoyalty += royalty.amount;350351 sendMoney(royalty.crossAddress, royalty.amount);352 }353354 return (totalRoyalty, royalties);355 }356357 function withdraw(address transferTo) public onlyOwner {358 uint256 balance = selfAddress.balance;359360 if (balance > 0) {361 payable(transferTo).transfer(balance);362 }363 }364}1// SPDX-License-Identifier: UNLICENSED2pragma solidity 0.8.17;34import "@openzeppelin/contracts/security/ReentrancyGuard.sol";5import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";6import "@openzeppelin/contracts/token/ERC721/IERC721.sol";7import "@openzeppelin/contracts/access/Ownable.sol";8import { UniqueNFT, CrossAddress } from "@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol";9import { UniqueFungible, CrossAddress as CrossAddressF } from "@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol";10import "@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol";11import "./royalty/UniqueRoyaltyHelper.sol";1213contract Market is Ownable, ReentrancyGuard {14 using ERC165Checker for address;1516 struct Order {17 uint32 id;18 uint32 collectionId;19 uint32 tokenId;20 uint32 amount;21 uint256 price;22 CrossAddress seller;23 }2425 uint32 public constant version = 0;26 uint32 public constant buildVersion = 3;27 bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;28 bytes4 private constant InterfaceId_ERC165 = 0x5755c3f2;29 CollectionHelpers private constant collectionHelpers =30 CollectionHelpers(0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F);3132 mapping(uint32 => mapping(uint32 => Order)) orders;33 uint32 private idCount = 1;34 uint32 public marketFee;35 uint64 public ctime;36 address public ownerAddress;37 mapping(address => bool) public admins;3839 event TokenIsUpForSale(uint32 version, Order item);40 event TokenRevoke(uint32 version, Order item, uint32 amount);41 event TokenIsApproved(uint32 version, Order item);42 event TokenIsPurchased(43 uint32 version,44 Order item,45 uint32 salesAmount,46 CrossAddress buyer,47 RoyaltyAmount[] royalties48 );49 event Log(string message);5051 error InvalidArgument(string info);52 error InvalidMarketFee();53 error SellerIsNotOwner();54 error TokenIsAlreadyOnSale();55 error TokenIsNotApproved();56 error CollectionNotFound();57 error CollectionNotSupportedERC721();58 error OrderNotFound();59 error TooManyAmountRequested();60 error NotEnoughMoneyError();61 error InvalidRoyaltiesError(uint256 totalRoyalty);62 error FailTransferToken(string reason);6364 modifier onlyAdmin() {65 require(msg.sender == this.owner() || admins[msg.sender], "Only admin can");66 _;67 }6869 modifier validCrossAddress(address eth, uint256 sub) {70 if (eth == address(0) && sub == 0) {71 revert InvalidArgument("Ethereum and Substrate addresses cannot be null at the same time");72 }7374 if (eth != address(0) && sub != 0) {75 revert InvalidArgument("Ethereum and Substrate addresses cannot be not null at the same time");76 }7778 _;79 }8081 constructor(uint32 fee, uint64 timestamp) {82 marketFee = fee;83 ctime = timestamp;8485 if (marketFee >= 100) {86 revert InvalidMarketFee();87 }88 }8990 /**91 * Fallback that allows this contract to receive native token.92 * We need this for self-sponsoring93 */94 fallback() external payable {}9596 /**97 * Receive also allows this contract to receive native token.98 * We need this for self-sponsoring99 */100 receive() external payable {}101102 function getErc721(uint32 collectionId) private view returns (IERC721) {103 address collectionAddress = collectionHelpers.collectionAddress(104 collectionId105 );106107 uint size;108 assembly {109 size := extcodesize(collectionAddress)110 }111112 if (size == 0) {113 revert CollectionNotFound();114 }115116 if (!collectionAddress.supportsInterface(InterfaceId_ERC721)) {117 revert CollectionNotSupportedERC721();118 }119120 return IERC721(collectionAddress);121 }122123 /**124 * Add new admin. Only owner or an existing admin can add admins.125 *126 * @param admin: Address of a new admin to add127 */128 function addAdmin(address admin) public onlyAdmin {129 admins[admin] = true;130 }131132 /**133 * Remove an admin. Only owner or an existing admin can remove admins.134 *135 * @param admin: Address of a new admin to add136 */137 function removeAdmin(address admin) public onlyAdmin {138 delete admins[admin];139 }140141 /**142 * Place an NFT or RFT token for sale. It must be pre-approved for transfers by this contract address.143 *144 * @param collectionId: ID of the token collection145 * @param tokenId: ID of the token146 * @param price: Price (with proper network currency decimals)147 * @param amount: Number of token fractions to list (must always be 1 for NFT)148 * @param seller: The seller cross-address (the beneficiary account to receive payment, may be different from transaction sender)149 */150 function put(151 uint32 collectionId,152 uint32 tokenId,153 uint256 price,154 uint32 amount,155 CrossAddress memory seller156 ) public validCrossAddress(seller.eth, seller.sub) {157 if (price == 0) {158 revert InvalidArgument("price must not be zero");159 }160 if (amount == 0) {161 revert InvalidArgument("amount must not be zero");162 }163164 if (orders[collectionId][tokenId].price > 0) {165 revert TokenIsAlreadyOnSale();166 }167168 IERC721 erc721 = getErc721(collectionId);169170 if (erc721.ownerOf(tokenId) != msg.sender) {171 revert SellerIsNotOwner();172 }173174 if (erc721.getApproved(tokenId) != address(this)) {175 revert TokenIsNotApproved();176 }177178 Order memory order = Order(179 0,180 collectionId,181 tokenId,182 amount,183 price,184 seller185 );186187 order.id = idCount++;188 orders[collectionId][tokenId] = order;189190 emit TokenIsUpForSale(version, order);191 }192193 /**194 * Get information about the listed token order195 *196 * @param collectionId: ID of the token collection197 * @param tokenId: ID of the token198 * @return The order information199 */200 function getOrder(201 uint32 collectionId,202 uint32 tokenId203 ) external view returns (Order memory) {204 return orders[collectionId][tokenId];205 }206207 /**208 * Revoke the token from the sale. Only the original lister can use this method.209 *210 * @param collectionId: ID of the token collection211 * @param tokenId: ID of the token212 * @param amount: Number of token fractions to de-list (must always be 1 for NFT)213 */214 function revoke(215 uint32 collectionId,216 uint32 tokenId,217 uint32 amount218 ) external {219 if (amount == 0) {220 revert InvalidArgument("amount must not be zero");221 }222223 Order memory order = orders[collectionId][tokenId];224225 if (order.price == 0) {226 revert OrderNotFound();227 }228229 if (amount > order.amount) {230 revert TooManyAmountRequested();231 }232233 IERC721 erc721 = getErc721(collectionId);234235 address ethAddress;236 if (order.seller.eth != address(0)) {237 ethAddress = order.seller.eth;238 } else {239 ethAddress = payable(address(uint160(order.seller.sub >> 96)));240 }241 if (erc721.ownerOf(tokenId) != ethAddress) {242 revert SellerIsNotOwner();243 }244245 order.amount -= amount;246 if (order.amount == 0) {247 delete orders[collectionId][tokenId];248 } else {249 orders[collectionId][tokenId] = order;250 }251252 emit TokenRevoke(version, order, amount);253 }254255 /**256 * Test if the token is still approved to be transferred by this contract and delete the order if not.257 *258 * @param collectionId: ID of the token collection259 * @param tokenId: ID of the token260 */261 function checkApproved(uint32 collectionId, uint32 tokenId) public onlyAdmin {262 Order memory order = orders[collectionId][tokenId];263 if (order.price == 0) {264 revert OrderNotFound();265 }266267 IERC721 erc721 = getErc721(collectionId);268269 if (erc721.getApproved(tokenId) != address(this) || erc721.ownerOf(tokenId) != getAddressFromCrossAccount(order.seller)) {270 uint32 amount = order.amount;271 order.amount = 0;272 emit TokenRevoke(version, order, amount);273274 delete orders[collectionId][tokenId];275 } else {276 emit TokenIsApproved(version, order);277 }278 }279280 function getAddressFromCrossAccount(CrossAddress memory account) private pure returns (address) {281 if (account.eth != address(0)) {282 return account.eth;283 } else {284 return address(uint160(account.sub >> 96));285 }286 }287288 /**289 * Revoke the token from the sale. Only the contract admin can use this method.290 *291 * @param collectionId: ID of the token collection292 * @param tokenId: ID of the token293 */294 function revokeAdmin(uint32 collectionId, uint32 tokenId) public onlyAdmin {295 Order memory order = orders[collectionId][tokenId];296 if (order.price == 0) {297 revert OrderNotFound();298 }299300 uint32 amount = order.amount;301 order.amount = 0;302 emit TokenRevoke(version, order, amount);303304 delete orders[collectionId][tokenId];305 }306307 /**308 * Buy a token (partially for an RFT).309 *310 * @param collectionId: ID of the token collection311 * @param tokenId: ID of the token312 * @param amount: Number of token fractions to buy (must always be 1 for NFT)313 * @param buyer: Cross-address of the buyer, eth part must be equal to the transaction signer address314 */315 function buy(316 uint32 collectionId,317 uint32 tokenId,318 uint32 amount,319 CrossAddress memory buyer320 ) public payable validCrossAddress(buyer.eth, buyer.sub) nonReentrant {321 if (msg.value == 0) {322 revert InvalidArgument("msg.value must not be zero");323 }324 if (amount == 0) {325 revert InvalidArgument("amount must not be zero");326 }327328 Order memory order = orders[collectionId][tokenId];329 if (order.price == 0) {330 revert OrderNotFound();331 }332333 if (amount > order.amount) {334 revert TooManyAmountRequested();335 }336337 uint256 totalValue = order.price * amount;338 uint256 feeValue = (totalValue * marketFee) / 100;339340 if (msg.value < totalValue) {341 revert NotEnoughMoneyError();342 }343344 IERC721 erc721 = getErc721(order.collectionId);345 if (erc721.getApproved(tokenId) != address(this)) {346 revert TokenIsNotApproved();347 }348349 order.amount -= amount;350 if (order.amount == 0) {351 delete orders[collectionId][tokenId];352 } else {353 orders[collectionId][tokenId] = order;354 }355356 address collectionAddress = collectionHelpers.collectionAddress(collectionId);357 UniqueNFT nft = UniqueNFT(collectionAddress);358359 nft.transferFromCross(360 order.seller,361 buyer,362 order.tokenId363 );364365 (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue - feeValue);366367 if (totalRoyalty >= totalValue - feeValue) {368 revert InvalidRoyaltiesError(totalRoyalty);369 }370371 sendMoney(order.seller, totalValue - feeValue - totalRoyalty);372373 if (msg.value > totalValue) {374 sendMoney(buyer, msg.value - totalValue);375 }376377 emit TokenIsPurchased(version, order, amount, buyer, royalties);378 }379380 function sendMoney(CrossAddress memory to, uint256 money) private {381 address collectionAddress = collectionHelpers.collectionAddress(0);382383 UniqueFungible fungible = UniqueFungible(collectionAddress);384385 CrossAddressF memory fromF = CrossAddressF(address(this), 0);386 CrossAddressF memory toF = CrossAddressF(to.eth, to.sub);387388 fungible.transferFromCross(fromF, toF, money);389 }390391 function sendRoyalties(address collection, uint tokenId, uint sellPrice) private returns (uint256, RoyaltyAmount[] memory) {392 RoyaltyAmount[] memory royalties = UniqueRoyaltyHelper.calculate(collection, tokenId, sellPrice);393394 uint256 totalRoyalty = 0;395396 for (uint256 i=0; i<royalties.length; i++) {397 RoyaltyAmount memory royalty = royalties[i];398399 totalRoyalty += royalty.amount;400401 sendMoney(royalty.crossAddress, royalty.amount);402 }403404 return (totalRoyalty, royalties);405 }406407 function withdraw(address transferTo) public onlyOwner {408 uint256 balance = address(this).balance;409410 if (balance > 0) {411 payable(transferTo).transfer(balance);412 }413 }414}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,13 +16,15 @@
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';
const {dirname} = makeNames(import.meta.url);
+const MARKET_FEE = 1;
+
describe('Market V2 Contract', () => {
let donor: IKeyringPair;
@@ -43,10 +45,26 @@
fsPath: `${dirname}/../api/UniqueNFT.sol`,
},
{
+ solPath: '@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol',
+ fsPath: `${dirname}/../api/UniqueFungible.sol`,
+ },
+ {
solPath: '@openzeppelin/contracts/utils/introspection/IERC165.sol',
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`,
},
@@ -72,7 +90,7 @@
},
],
15000000,
- [1, 0],
+ [MARKET_FEE, 0],
);
}
@@ -90,63 +108,135 @@
});
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);
+
+ // Set external sponsoring
+ await contractHelpers.methods.setSponsor(market.options.address, marketOwner).send({from: marketOwner});
+ await contractHelpers.methods.confirmSponsorship(market.options.address).send({from: marketOwner});
+ // Configure sponsoring
+ 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);
+
+ // Set collection sponsoring
+ 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});
- const putResult = await market.methods.put(collectionId, tokenId, 1, 1, sellerCross).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, 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);
+
+ // 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);
});
itEth('Put + Buy [sub]', async ({helper}) => {
- const PRICE = 1n;
+ const ONE_TOKEN = helper.balance.getOneTokenNominal();
+ const PRICE = 2n * ONE_TOKEN; // 2 UNQ
const web3 = helper.getWeb3();
const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);
const market = await deployMarket(helper, marketOwner);
+ const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);
+
+ // Set self sponsoring from contract balance
+ await contractHelpers.methods.selfSponsoredEnable(market.options.address).send({from: marketOwner});
+ await helper.eth.transferBalanceFromSubstrate(donor, market.options.address, 10n);
+
+ // Configure sponsoring
+ 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);
+
+ // Set collection sponsoring
+ await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});
+ await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});
- const [seller] = await helper.arrange.createAccounts([600n], donor);
- const sellerMirror = helper.address.substrateToEth(seller.address);
+ const seller = helper.util.fromSeed(`//Market-seller-${(new Date()).getTime()}`);
const sellerCross = helper.ethCrossAccount.fromKeyringPair(seller);
+
+ // Seller has no funds at all, his transactions are sponsored
+ {
+ const sellerBalance = await helper.balance.getSubstrate(seller.address);
+ expect(sellerBalance).to.be.eq(0n);
+ }
+
const result = await collection.methods.mintCross(sellerCross, []).send();
const tokenId = result.events.Transfer.returnValues.tokenId;
- await helper.nft.approveToken(seller, collectionId, tokenId, {Ethereum: market.options.address}, 1n);
+ await helper.nft.approveToken(seller, collectionId, tokenId, {Ethereum: market.options.address});
await helper.eth.sendEVM(seller, market.options.address, market.methods.put(collectionId, tokenId, PRICE, 1, sellerCross).encodeABI(), '0');
+ // Seller balance is still zero
+ {
+ const sellerBalance = await helper.balance.getSubstrate(seller.address);
+ expect(sellerBalance).to.be.eq(0n);
+ }
let ownerCross = await collection.methods.ownerOfCross(tokenId).call();
expect(ownerCross.eth).to.be.eq(sellerCross.eth);
expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(sellerCross.sub, web3));
const [buyer] = await helper.arrange.createAccounts([600n], donor);
+ // Buyer has only expected balance
+ {
+ const buyerBalance = await helper.balance.getSubstrate(buyer.address);
+ expect(buyerBalance).to.be.eq(600n * ONE_TOKEN);
+ }
const buyerMirror = helper.address.substrateToEth(buyer.address);
const buyerCross = helper.ethCrossAccount.fromKeyringPair(buyer);
- await helper.eth.transferBalanceFromSubstrate(donor, buyerMirror, 1n);
- //TODO: change balance check to helper.balance.getSubstrate when implementation of sendMoney will be fixed in contract
- const sellerBalance = BigInt(await web3.eth.getBalance(sellerMirror));
+ await helper.eth.transferBalanceFromSubstrate(donor, buyerMirror, PRICE, false);
+
+ const buyerBalanceBefore = await helper.balance.getSubstrate(buyer.address);
await helper.eth.sendEVM(buyer, market.options.address, market.methods.buy(collectionId, tokenId, 1, buyerCross).encodeABI(), PRICE.toString());
- const sellerBalanceAfterBuy = BigInt(await web3.eth.getBalance(sellerMirror));
+ const buyerBalanceAfter = await helper.balance.getSubstrate(buyer.address);
+ // Buyer balance not changed: transaction is sponsored
+ expect(buyerBalanceBefore).to.be.eq(buyerBalanceAfter);
+
+ const sellerBalanceAfterBuy = BigInt(await helper.balance.getSubstrate(seller.address));
ownerCross = await collection.methods.ownerOfCross(tokenId).call();
expect(ownerCross.eth).to.be.eq(buyerCross.eth);
expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(buyerCross.sub, web3));
- expect(sellerBalance + PRICE).to.be.equal(sellerBalanceAfterBuy);
+
+ // Seller got only PRICE - MARKET_FEE
+ expect(sellerBalanceAfterBuy).to.be.eq(PRICE * BigInt(100 - MARKET_FEE) / 100n);
});
});
tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -561,10 +561,10 @@
itEth.ifWithPallets(`[${testCase.mode}] Can't be multiple set/read for non-existent token`, testCase.requiredPallets, async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });
- const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {tokenOwner: true,
+ const properties = Array(5).fill(0).map((_, i) => ({key: `key_${i}`, value: Buffer.from(`value_${i}`)}));
+ const permissions: ITokenPropertyPermission[] = properties.map(p => ({key: p.key, permission: {tokenOwner: true,
collectionAdmin: true,
- mutable: true}}; });
+ mutable: true}}));
const collection = await helper[testCase.mode].mintCollection(alice, {
tokenPrefix: 'ethp',