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}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',