difftreelog
Update market + substrate sponsoring example
in: master
2 files changed
tests/src/eth/marketplace-v2/Market.soldiffbeforeafterboth1// 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 function getErc721(uint32 collectionId) private view returns (IERC721) {91 address collectionAddress = collectionHelpers.collectionAddress(92 collectionId93 );9495 uint size;96 assembly {97 size := extcodesize(collectionAddress)98 }99100 if (size == 0) {101 revert CollectionNotFound();102 }103104 if (!collectionAddress.supportsInterface(InterfaceId_ERC721)) {105 revert CollectionNotSupportedERC721();106 }107108 return IERC721(collectionAddress);109 }110111 /**112 * Add new admin. Only owner or an existing admin can add admins.113 *114 * @param admin: Address of a new admin to add115 */116 function addAdmin(address admin) public onlyAdmin {117 admins[admin] = true;118 }119120 /**121 * Remove an admin. Only owner or an existing admin can remove admins.122 *123 * @param admin: Address of a new admin to add124 */125 function removeAdmin(address admin) public onlyAdmin {126 delete admins[admin];127 }128129 /**130 * Place an NFT or RFT token for sale. It must be pre-approved for transfers by this contract address.131 *132 * @param collectionId: ID of the token collection133 * @param tokenId: ID of the token134 * @param price: Price (with proper network currency decimals)135 * @param amount: Number of token fractions to list (must always be 1 for NFT)136 * @param seller: The seller cross-address (the beneficiary account to receive payment, may be different from transaction sender)137 */138 function put(139 uint32 collectionId,140 uint32 tokenId,141 uint256 price,142 uint32 amount,143 CrossAddress memory seller144 ) public validCrossAddress(seller.eth, seller.sub) {145 if (price == 0) {146 revert InvalidArgument("price must not be zero");147 }148 if (amount == 0) {149 revert InvalidArgument("amount must not be zero");150 }151152 if (orders[collectionId][tokenId].price > 0) {153 revert TokenIsAlreadyOnSale();154 }155156 IERC721 erc721 = getErc721(collectionId);157158 if (erc721.ownerOf(tokenId) != msg.sender) {159 revert SellerIsNotOwner();160 }161162 if (erc721.getApproved(tokenId) != address(this)) {163 revert TokenIsNotApproved();164 }165166 Order memory order = Order(167 0,168 collectionId,169 tokenId,170 amount,171 price,172 seller173 );174175 order.id = idCount++;176 orders[collectionId][tokenId] = order;177178 emit TokenIsUpForSale(version, order);179 }180181 /**182 * Get information about the listed token order183 *184 * @param collectionId: ID of the token collection185 * @param tokenId: ID of the token186 * @return The order information187 */188 function getOrder(189 uint32 collectionId,190 uint32 tokenId191 ) external view returns (Order memory) {192 return orders[collectionId][tokenId];193 }194195 /**196 * Revoke the token from the sale. Only the original lister can use this method.197 *198 * @param collectionId: ID of the token collection199 * @param tokenId: ID of the token200 * @param amount: Number of token fractions to de-list (must always be 1 for NFT)201 */202 function revoke(203 uint32 collectionId,204 uint32 tokenId,205 uint32 amount206 ) external {207 if (amount == 0) {208 revert InvalidArgument("amount must not be zero");209 }210211 Order memory order = orders[collectionId][tokenId];212213 if (order.price == 0) {214 revert OrderNotFound();215 }216217 if (amount > order.amount) {218 revert TooManyAmountRequested();219 }220221 IERC721 erc721 = getErc721(collectionId);222223 address ethAddress;224 if (order.seller.eth != address(0)) {225 ethAddress = order.seller.eth;226 } else {227 ethAddress = payable(address(uint160(order.seller.sub >> 96)));228 }229 if (erc721.ownerOf(tokenId) != ethAddress) {230 revert SellerIsNotOwner();231 }232233 order.amount -= amount;234 if (order.amount == 0) {235 delete orders[collectionId][tokenId];236 } else {237 orders[collectionId][tokenId] = order;238 }239240 emit TokenRevoke(version, order, amount);241 }242243 /**244 * Test if the token is still approved to be transferred by this contract and delete the order if not.245 *246 * @param collectionId: ID of the token collection247 * @param tokenId: ID of the token248 */249 function checkApproved(uint32 collectionId, uint32 tokenId) public onlyAdmin {250 Order memory order = orders[collectionId][tokenId];251 if (order.price == 0) {252 revert OrderNotFound();253 }254255 IERC721 erc721 = getErc721(collectionId);256257 if (erc721.getApproved(tokenId) != address(this) || erc721.ownerOf(tokenId) != getAddressFromCrossAccount(order.seller)) {258 uint32 amount = order.amount;259 order.amount = 0;260 emit TokenRevoke(version, order, amount);261262 delete orders[collectionId][tokenId];263 } else {264 emit TokenIsApproved(version, order);265 }266 }267268 function getAddressFromCrossAccount(CrossAddress memory account) private pure returns (address) {269 if (account.eth != address(0)) {270 return account.eth;271 } else {272 return address(uint160(account.sub >> 96));273 }274 }275276 /**277 * Revoke the token from the sale. Only the contract admin can use this method.278 *279 * @param collectionId: ID of the token collection280 * @param tokenId: ID of the token281 */282 function revokeAdmin(uint32 collectionId, uint32 tokenId) public onlyAdmin {283 Order memory order = orders[collectionId][tokenId];284 if (order.price == 0) {285 revert OrderNotFound();286 }287288 uint32 amount = order.amount;289 order.amount = 0;290 emit TokenRevoke(version, order, amount);291292 delete orders[collectionId][tokenId];293 }294295 /**296 * Buy a token (partially for an RFT).297 *298 * @param collectionId: ID of the token collection299 * @param tokenId: ID of the token300 * @param amount: Number of token fractions to buy (must always be 1 for NFT)301 * @param buyer: Cross-address of the buyer, eth part must be equal to the transaction signer address302 */303 function buy(304 uint32 collectionId,305 uint32 tokenId,306 uint32 amount,307 CrossAddress memory buyer308 ) public payable validCrossAddress(buyer.eth, buyer.sub) nonReentrant {309 if (msg.value == 0) {310 revert InvalidArgument("msg.value must not be zero");311 }312 if (amount == 0) {313 revert InvalidArgument("amount must not be zero");314 }315316 Order memory order = orders[collectionId][tokenId];317 if (order.price == 0) {318 revert OrderNotFound();319 }320321 if (amount > order.amount) {322 revert TooManyAmountRequested();323 }324325 uint256 totalValue = order.price * amount;326 uint256 feeValue = (totalValue * marketFee) / 100;327328 if (msg.value < totalValue) {329 revert NotEnoughMoneyError();330 }331332 IERC721 erc721 = getErc721(order.collectionId);333 if (erc721.getApproved(tokenId) != address(this)) {334 revert TokenIsNotApproved();335 }336337 order.amount -= amount;338 if (order.amount == 0) {339 delete orders[collectionId][tokenId];340 } else {341 orders[collectionId][tokenId] = order;342 }343344 address collectionAddress = collectionHelpers.collectionAddress(collectionId);345 UniqueNFT nft = UniqueNFT(collectionAddress);346347 nft.transferFromCross(348 order.seller,349 buyer,350 order.tokenId351 );352353 (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue - feeValue);354355 if (totalRoyalty >= totalValue - feeValue) {356 revert InvalidRoyaltiesError(totalRoyalty);357 }358359 sendMoney(order.seller, totalValue - feeValue - totalRoyalty);360361 if (msg.value > totalValue) {362 sendMoney(buyer, msg.value - totalValue);363 }364365 emit TokenIsPurchased(version, order, amount, buyer, royalties);366 }367368 function sendMoney(CrossAddress memory to, uint256 money) private {369 address collectionAddress = collectionHelpers.collectionAddress(0);370371 UniqueFungible fungible = UniqueFungible(collectionAddress);372373 CrossAddressF memory fromF = CrossAddressF(address(this), 0);374 CrossAddressF memory toF = CrossAddressF(to.eth, to.sub);375376 fungible.transferFromCross(fromF, toF, money);377 }378379 function sendRoyalties(address collection, uint tokenId, uint sellPrice) private returns (uint256, RoyaltyAmount[] memory) {380 RoyaltyAmount[] memory royalties = UniqueRoyaltyHelper.calculate(collection, tokenId, sellPrice);381382 uint256 totalRoyalty = 0;383384 for (uint256 i=0; i<royalties.length; i++) {385 RoyaltyAmount memory royalty = royalties[i];386387 totalRoyalty += royalty.amount;388389 sendMoney(royalty.crossAddress, royalty.amount);390 }391392 return (totalRoyalty, royalties);393 }394395 function withdraw(address transferTo) public onlyOwner {396 uint256 balance = address(this).balance;397398 if (balance > 0) {399 payable(transferTo).transfer(balance);400 }401 }402}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
@@ -23,6 +23,8 @@
const {dirname} = makeNames(import.meta.url);
+const MARKET_FEE = 1;
+
describe('Market V2 Contract', () => {
let donor: IKeyringPair;
@@ -88,7 +90,7 @@
},
],
15000000,
- [1, 0],
+ [MARKET_FEE, 0],
);
}
@@ -111,18 +113,19 @@
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!
+ // 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 = 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});
@@ -130,20 +133,20 @@
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, PRICE.toString(), 1, sellerCross).send({
- from: sellerCross.eth, gasLimit: 1_000_000
+ 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);
@@ -153,11 +156,11 @@
// Buyer has only 10 UNQ
const buyerBalance = await helper.balance.getEthereum(buyerCross.eth);
- expect(buyerBalance).to.be.eq(10n * ONE_TOKEN)
+ 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);
@@ -168,35 +171,73 @@
});
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);
- const [seller] = await helper.arrange.createAccounts([600n], donor);
+ // Set collection sponsoring
+ await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});
+ await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});
+
+ 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);
- const sellerBalance = BigInt(await helper.balance.getSubstrate(seller.address));
+ 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 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);
});
});