difftreelog
feat update MarketV2 contract
in: master
3 files changed
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/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
@@ -43,6 +43,10 @@
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`,
},
@@ -125,7 +129,6 @@
const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner);
const [seller] = await helper.arrange.createAccounts([600n], donor);
- const sellerMirror = helper.address.substrateToEth(seller.address);
const sellerCross = helper.ethCrossAccount.fromKeyringPair(seller);
const result = await collection.methods.mintCross(sellerCross, []).send();
const tokenId = result.events.Transfer.returnValues.tokenId;
@@ -140,10 +143,9 @@
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));
+ const sellerBalance = BigInt(await helper.balance.getSubstrate(seller.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 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));
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',