difftreelog
Merge pull request #186 from UniqueNetwork/test/evm-marketplace
in: master
EVM matcher contract test
13 files changed
crates/evm-coder/tests/a.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/a.rs
+++ b/crates/evm-coder/tests/a.rs
@@ -2,6 +2,7 @@
use evm_coder::{solidity_interface, types::*, ToLog, execution::Result};
use evm_coder_macros::solidity;
+use std as sp_std;
struct Impls;
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -1399,6 +1399,11 @@
item_id: TokenId,
amount: u128,
) -> DispatchResult {
+ if sender == from {
+ // Transfer by `from`, because it is either equal to sender, or derived from him
+ return Self::transfer_internal(from, recipient, collection, item_id, amount);
+ }
+
// Check approval
collection.consume_sload()?;
let approval: u128 =
pallets/nft/src/mock.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -129,8 +129,11 @@
fn as_sub(&self) -> &u64 {
&self.0
}
- fn from_eth(_eth: sp_core::H160) -> Self {
- unimplemented!()
+ fn from_eth(eth: sp_core::H160) -> Self {
+ let mut sub_raw = [0; 8];
+ sub_raw.copy_from_slice(ð.0[0..8]);
+ let sub = u64::from_be_bytes(sub_raw);
+ Self(sub, eth)
}
fn as_eth(&self) -> &sp_core::H160 {
&self.1
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -24,8 +24,8 @@
"lint": "eslint --ext .ts,.js src/",
"fix": "eslint --ext .ts,.js src/ --fix",
"test": "mocha --timeout 9999999 -r ts-node/register './**/*.test.ts'",
- "testEth": "mocha --timeout 9999999 -r ts-node/register ./**/eth/**/*.test.ts",
- "load": "mocha --timeout 9999999 -r ts-node/register ./**/*.load.ts",
+ "testEth": "mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.test.ts'",
+ "load": "mocha --timeout 9999999 -r ts-node/register './**/*.load.ts'",
"loadTransfer": "ts-node src/transfer.nload.ts",
"testCollision": "mocha --timeout 9999999 -r ts-node/register ./src/collision-tests/*.test.ts",
"testAddCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/addCollectionAdmin.test.ts",
@@ -85,4 +85,4 @@
"artifacts"
]
}
-}
\ No newline at end of file
+}
tests/src/eth/marketplace/MarketPlaceKSM.abidiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/marketplace/MarketPlaceKSM.abi
@@ -0,0 +1 @@
+[{"inputs":[{"internalType":"address","name":"_escrow","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"asks","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"asksbySeller","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"balanceKSM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_idCollection","type":"address"},{"internalType":"uint256","name":"_idNFT","type":"uint256"}],"name":"buy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint256","name":"_currencyCode","type":"uint256"},{"internalType":"address","name":"_sender","type":"address"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_currencyCode","type":"uint256"},{"internalType":"address","name":"_sender","type":"address"}],"name":"escrowBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"offers","outputs":[{"internalType":"uint256","name":"idNFT","type":"uint256"},{"internalType":"uint256","name":"currencyCode","type":"uint256"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint256","name":"time","type":"uint256"},{"internalType":"address","name":"idCollection","type":"address"},{"internalType":"address","name":"userAddr","type":"address"},{"internalType":"uint8","name":"flagActive","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_price","type":"uint256"},{"internalType":"uint256","name":"_currencyCode","type":"uint256"},{"internalType":"address","name":"_idCollection","type":"address"},{"internalType":"uint256","name":"_idNFT","type":"uint256"},{"internalType":"uint8","name":"_active","type":"uint8"}],"name":"setAsk","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newEscrow","type":"address"}],"name":"setEscrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newEscrow","type":"address"}],"name":"setowner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint256","name":"_currencyCode","type":"uint256"},{"internalType":"address","name":"_sender","type":"address"}],"name":"withdraw","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]
\ No newline at end of file
tests/src/eth/marketplace/MarketPlaceKSM.bindiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/marketplace/MarketPlaceKSM.bin
@@ -0,0 +1 @@
+608060405234801561001057600080fd5b50604051610e27380380610e2783398101604081905261002f9161005d565b600480546001600160a01b039092166001600160a01b0319928316179055600580549091163317905561008d565b60006020828403121561006f57600080fd5b81516001600160a01b038116811461008657600080fd5b9392505050565b610d8b8061009c6000396000f3fe608060405234801561001057600080fd5b50600436106100a95760003560e01c806399f2d4eb1161007157806399f2d4eb1461018e5780639df55f52146101a1578063c10c35461461010f578063cce7ec13146101b4578063db87db52146101c7578063e22d4f7d146101fa57600080fd5b80630ad58d2f146100ae57806310a5ff17146100d6578063592bd7051461010f5780638a72ea6a146101245780638dbdbe6d1461017b575b600080fd5b6100c16100bc366004610c4d565b610225565b60405190151581526020015b60405180910390f35b6101016100e4366004610bd8565b600160209081526000928352604080842090915290825290205481565b6040519081526020016100cd565b61012261011d366004610b97565b6102d8565b005b610137610132366004610c04565b610345565b6040805197885260208801969096529486019390935260608501919091526001600160a01b0390811660808501521660a083015260ff1660c082015260e0016100cd565b610122610189366004610c4d565b6103a4565b61010161019c366004610bd8565b610449565b6101226101af366004610c86565b61047a565b6101226101c2366004610bd8565b610984565b6101016101d5366004610c1d565b6001600160a01b03166000908152600160209081526040808320938352929052205490565b610101610208366004610bd8565b600260209081526000928352604080842090915290825290205481565b6004546000906001600160a01b031633146102795760405162461bcd60e51b815260206004820152600f60248201526e27b7363c9032b9b1b937bb9031b0b760891b60448201526064015b60405180910390fd5b6001600160a01b03821660009081526001602090815260408083208684529091529020546102a8908590610cfa565b6001600160a01b039290921660009081526001602081815260408084209684529590529390209190915550919050565b6005546001600160a01b031633146103235760405162461bcd60e51b815260206004820152600e60248201526d27b7363c9037bbb732b91031b0b760911b6044820152606401610270565b600480546001600160a01b0319166001600160a01b0392909216919091179055565b6000818154811061035557600080fd5b6000918252602090912060069091020180546001820154600283015460038401546004850154600590950154939550919390926001600160a01b0391821691811690600160a01b900460ff1687565b6004546001600160a01b031633146103f05760405162461bcd60e51b815260206004820152600f60248201526e27b7363c9032b9b1b937bb9031b0b760891b6044820152606401610270565b6001600160a01b038116600090815260016020908152604080832085845290915290205461041f908490610ce2565b6001600160a01b039091166000908152600160209081526040808320948352939052919091205550565b6003602052816000526040600020818154811061046557600080fd5b90600052602060002001600091509150505481565b6040516331a9108f60e11b81526004810183905233906001600160a01b03851690636352211e9060240160206040518083038186803b1580156104bc57600080fd5b505afa1580156104d0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104f49190610bbb565b6001600160a01b0316146105425760405162461bcd60e51b81526020600482015260156024820152742737ba103934b3b43a103a37b5b2b71037bbb732b960591b6044820152606401610270565b6001600160a01b0383166000908152600260209081526040808320858452909152812054905415806105ac575060006001600160a01b03166000828154811061058d5761058d610d27565b60009182526020909120600460069092020101546001600160a01b0316145b15610793576040805160e0810182528481526020810187815291810188815242606083019081526001600160a01b03808916608085019081523360a0860190815260ff808a1660c088019081526000805460018181018355828052995160069091027f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56381019190915599517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5648b015596517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5658a015594517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56689015591517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e567880180549185166001600160a01b0319909216919091179055517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56890960180549351909116600160a01b026001600160a81b031990931695909116949094171790925590546107399190610cfa565b6001600160a01b038516600090815260026020908152604080832087845282528083209390935533825260039052908120905461077890600190610cfa565b81546001810183556000928352602090922090910155610916565b6040805160e0810182526001600160a01b03861660009081526002602090815283822087835290529182205482549192839290919081106107d6576107d6610d27565b60009182526020808320600690920290910154835282810189905260408084018b90524260608501526001600160a01b0389168352600282528083208884529091528120548154608090930192811061083157610831610d27565b60009182526020808320600460069093020191909101546001600160a01b039081168452338483015260ff871660409485015288168252600281528282208783529052908120548154811061088857610888610d27565b60009182526020918290208351600690920201908155908201516001820155604082015160028201556060820151600382015560808201516004820180546001600160a01b039283166001600160a01b031990911617905560a08301516005909201805460c09094015160ff16600160a01b026001600160a81b031990941692909116919091179190911790555b6040516323b872dd60e01b8152336004820152306024820152604481018490526001600160a01b038516906323b872dd90606401600060405180830381600087803b15801561096457600080fd5b505af1158015610978573d6000803e3d6000fd5b50505050505050505050565b6001600160a01b0382166000908152600260209081526040808320848452909152812054815482919081106109bb576109bb610d27565b600091825260208083206040805160e0810182526006949094029091018054845260018082015485850190815260028301548685018190526003840154606088015260048401546001600160a01b03908116608089015260059094015493841660a0880152600160a01b90930460ff1660c08701523387529084528286209051865290925290922054909250610a519190610cfa565b33600090815260016020818152604080842086830180518652908352818520959095558581015160a08701516001600160a01b031685529282528084209451845293905291902054610aa39190610ce2565b60a08201516001600160a01b0390811660009081526001602090815260408083208287015184528252808320949094559186168152600282528281208582529091529081205481548291908110610afc57610afc610d27565b60009182526020909120600560069092020101805460ff92909216600160a01b0260ff60a01b199092169190911790556040516323b872dd60e01b8152306004820152336024820152604481018390526001600160a01b038416906323b872dd90606401600060405180830381600087803b158015610b7a57600080fd5b505af1158015610b8e573d6000803e3d6000fd5b50505050505050565b600060208284031215610ba957600080fd5b8135610bb481610d3d565b9392505050565b600060208284031215610bcd57600080fd5b8151610bb481610d3d565b60008060408385031215610beb57600080fd5b8235610bf681610d3d565b946020939093013593505050565b600060208284031215610c1657600080fd5b5035919050565b60008060408385031215610c3057600080fd5b823591506020830135610c4281610d3d565b809150509250929050565b600080600060608486031215610c6257600080fd5b83359250602084013591506040840135610c7b81610d3d565b809150509250925092565b600080600080600060a08688031215610c9e57600080fd5b85359450602086013593506040860135610cb781610d3d565b925060608601359150608086013560ff81168114610cd457600080fd5b809150509295509295909350565b60008219821115610cf557610cf5610d11565b500190565b600082821015610d0c57610d0c610d11565b500390565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b6001600160a01b0381168114610d5257600080fd5b5056fea2646970667358221220d098ae4e0cc7bdbb7de1061c03402a667836f903122c1c606ca2c65db1ab78e964736f6c63430008070033
\ No newline at end of file
tests/src/eth/marketplace/MarketPlaceKSM.soldiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/marketplace/MarketPlaceKSM.sol
@@ -0,0 +1,179 @@
+// SPDX-License-Identifier: Apache License
+pragma solidity >=0.8.0;
+
+interface IERC721 {
+ event Transfer(
+ address indexed from,
+ address indexed to,
+ uint256 indexed tokenId
+ );
+ event Approval(
+ address indexed owner,
+ address indexed approved,
+ uint256 indexed tokenId
+ );
+
+ function ownerOf(uint256 tokenId) external view returns (address owner);
+
+ function transferFrom(
+ address from,
+ address to,
+ uint256 tokenId
+ ) external;
+
+ function debug(string memory value) external;
+}
+
+interface IERC20 {
+ event Transfer(address indexed from, address indexed to, uint256 value);
+ event Approval(
+ address indexed owner,
+ address indexed spender,
+ uint256 value
+ );
+
+ function transfer(address recipient, uint256 amount)
+ external
+ returns (bool);
+
+ function transferFrom(
+ address sender,
+ address recipient,
+ uint256 amount
+ ) external returns (bool);
+}
+
+contract MarketPlaceKSM {
+ struct Offer {
+ uint256 idNFT;
+ uint256 currencyCode;
+ uint256 price;
+ uint256 time;
+ address idCollection;
+ address userAddr;
+ uint8 flagActive;
+ }
+ Offer[] public offers;
+
+ mapping(address => mapping(uint256 => uint256)) public balanceKSM; // [userAddr] => [KSMs]
+ mapping(address => mapping(uint256 => uint256)) public asks; // [buyer][idCollection][idNFT] => idOffer
+
+ mapping(address => uint256[]) public asksbySeller; // [addressSeller] =>idOffer
+
+ address escrow;
+ address owner;
+
+ constructor(address _escrow) {
+ escrow = _escrow;
+ owner = msg.sender;
+ }
+
+ function setowner(address _newEscrow) public onlyOwner {
+ escrow = _newEscrow;
+ }
+
+ function setEscrow(address _newEscrow) public onlyOwner {
+ escrow = _newEscrow;
+ }
+
+ modifier onlyEscrow() {
+ require(msg.sender == escrow, "Only escrow can");
+ _;
+ }
+
+ modifier onlyOwner() {
+ require(msg.sender == owner, "Only owner can");
+ _;
+ }
+
+ /**
+ * Make bids (offers) to sell NFTs
+ */
+ function setAsk(
+ uint256 _price,
+ uint256 _currencyCode,
+ address _idCollection,
+ uint256 _idNFT,
+ uint8 _active
+ ) public {
+ require(
+ IERC721(_idCollection).ownerOf(_idNFT) == msg.sender,
+ "Not right token owner"
+ );
+ uint256 offerID = asks[_idCollection][_idNFT];
+ if (offers.length == 0 || offers[offerID].idCollection == address(0)) {
+ offers.push(
+ Offer(
+ _idNFT,
+ _currencyCode,
+ _price,
+ block.timestamp,
+ _idCollection,
+ msg.sender,
+ _active
+ )
+ );
+ asks[_idCollection][_idNFT] = offers.length - 1;
+ asksbySeller[msg.sender].push(offers.length - 1);
+ }
+ //edit existing offer
+ else {
+ offers[asks[_idCollection][_idNFT]] = Offer(
+ offers[asks[_idCollection][_idNFT]].idNFT,
+ _currencyCode,
+ _price,
+ block.timestamp,
+ offers[asks[_idCollection][_idNFT]].idCollection,
+ msg.sender,
+ _active
+ );
+ }
+
+ IERC721(_idCollection).transferFrom(msg.sender, address(this), _idNFT);
+ }
+
+ function deposit(
+ uint256 _amount,
+ uint256 _currencyCode,
+ address _sender
+ ) public onlyEscrow {
+ balanceKSM[_sender][_currencyCode] =
+ balanceKSM[_sender][_currencyCode] +
+ _amount;
+ }
+
+ function buy(address _idCollection, uint256 _idNFT) public {
+ Offer memory offer = offers[asks[_idCollection][_idNFT]];
+ // 1. reduce balance
+ balanceKSM[msg.sender][offer.currencyCode] =
+ balanceKSM[msg.sender][offer.currencyCode] -
+ offer.price;
+ // 2. increase balance
+ balanceKSM[offer.userAddr][offer.currencyCode] =
+ balanceKSM[offer.userAddr][offer.currencyCode] +
+ offer.price;
+ // 3. close offer
+ offers[asks[_idCollection][_idNFT]].flagActive = 0;
+ // 4. transfer NFT to buyer
+ IERC721(_idCollection).transferFrom(address(this), msg.sender, _idNFT);
+ }
+
+ function withdraw(
+ uint256 _amount,
+ uint256 _currencyCode,
+ address _sender
+ ) public onlyEscrow returns (bool) {
+ balanceKSM[_sender][_currencyCode] =
+ balanceKSM[_sender][_currencyCode] -
+ _amount;
+ return true;
+ }
+
+ function escrowBalance(uint256 _currencyCode, address _sender)
+ public
+ view
+ returns (uint256)
+ {
+ return balanceKSM[_sender][_currencyCode];
+ }
+}
tests/src/eth/marketplace/MarketPlaceUNQ.abidiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/marketplace/MarketPlaceUNQ.abi
@@ -0,0 +1 @@
+[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"asks","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"asksbySeller","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_idCollection","type":"address"},{"internalType":"uint256","name":"_idNFT","type":"uint256"},{"internalType":"address","name":"_currencyCode","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"buy","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"_idCollection","type":"address"},{"internalType":"uint256","name":"_idNFT","type":"uint256"}],"name":"buy","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"offers","outputs":[{"internalType":"uint256","name":"idNFT","type":"uint256"},{"internalType":"address","name":"currencyCode","type":"address"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint256","name":"time","type":"uint256"},{"internalType":"address","name":"idCollection","type":"address"},{"internalType":"address","name":"userAddr","type":"address"},{"internalType":"uint8","name":"flagActive","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_price","type":"uint256"},{"internalType":"address","name":"_currencyCode","type":"address"},{"internalType":"address","name":"_idCollection","type":"address"},{"internalType":"uint256","name":"_idNFT","type":"uint256"},{"internalType":"uint8","name":"_active","type":"uint8"}],"name":"setAsk","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newOwner","type":"address"}],"name":"setowner","outputs":[],"stateMutability":"nonpayable","type":"function"}]
\ No newline at end of file
tests/src/eth/marketplace/MarketPlaceUNQ.bindiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/marketplace/MarketPlaceUNQ.bin
@@ -0,0 +1 @@
+608060405234801561001057600080fd5b50600380546001600160a01b03191633179055610f2d806100326000396000f3fe6080604052600436106100705760003560e01c806399f2d4eb1161004e57806399f2d4eb14610120578063b3ffb7601461014e578063cce7ec1314610161578063e22d4f7d1461017457600080fd5b8063592bd705146100755780637b1d6001146100975780638a72ea6a146100b7575b600080fd5b34801561008157600080fd5b50610095610090366004610d2b565b6101ac565b005b3480156100a357600080fd5b506100956100b2366004610e1b565b61021e565b3480156100c357600080fd5b506100d76100d2366004610e02565b61073d565b604080519788526001600160a01b03968716602089015287019490945260608601929092528316608085015290911660a083015260ff1660c082015260e0015b60405180910390f35b34801561012c57600080fd5b5061014061013b366004610d6c565b6107a0565b604051908152602001610117565b61009561015c366004610d98565b6107d1565b61009561016f366004610d6c565b610b0b565b34801561018057600080fd5b5061014061018f366004610d6c565b600160209081526000928352604080842090915290825290205481565b6003546001600160a01b031633146101fc5760405162461bcd60e51b815260206004820152600e60248201526d27b7363c9037bbb732b91031b0b760911b60448201526064015b60405180910390fd5b600380546001600160a01b0319166001600160a01b0392909216919091179055565b6040516331a9108f60e11b81526004810183905233906001600160a01b03851690636352211e9060240160206040518083038186803b15801561026057600080fd5b505afa158015610274573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102989190610d4f565b6001600160a01b0316146102e65760405162461bcd60e51b81526020600482015260156024820152742737ba103934b3b43a103a37b5b2b71037bbb732b960591b60448201526064016101f3565b6001600160a01b038316600090815260016020908152604080832085845290915281205490541580610350575060006001600160a01b03166000828154811061033157610331610ec9565b60009182526020909120600460069092020101546001600160a01b0316145b15610542576040805160e0810182528481526001600160a01b03878116602083019081529282018981524260608401908152888316608085019081523360a0860190815260ff89811660c08801908152600080546001808201835582805299517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56360069092029182015599517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5648b0180546001600160a01b0319908116928b1692909217905596517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5658b015594517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5668a015592517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5678901805490961690871617909455517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56890960180549151969094166001600160a81b031990911617600160a01b959092169490940217905590546104e99190610ea4565b6001600160a01b0385166000908152600160208181526040808420888552825280842094909455338352600290529181209054909161052791610ea4565b815460018101835560009283526020909220909101556106d3565b6040805160e0810182526001600160a01b038616600090815260016020908152838220878352905291822054825491928392909190811061058557610585610ec9565b6000918252602080832060069092029091015483526001600160a01b03808a168483015260408085018c9052426060860152908916835260018252808320888452909152812054815460809093019281106105e2576105e2610ec9565b60009182526020808320600460069093020191909101546001600160a01b039081168452338483015260ff871660409485015288168252600181528282208783529052908120548154811061063957610639610ec9565b60009182526020918290208351600690920201908155908201516001820180546001600160a01b039283166001600160a01b031991821617909155604084015160028401556060840151600384015560808401516004840180549184169190921617905560a08301516005909201805460c09094015160ff16600160a01b026001600160a81b031990941692909116919091179190911790555b6040516323b872dd60e01b81526001600160a01b038516906323b872dd9061070390339030908890600401610e80565b600060405180830381600087803b15801561071d57600080fd5b505af1158015610731573d6000803e3d6000fd5b50505050505050505050565b6000818154811061074d57600080fd5b60009182526020909120600690910201805460018201546002830154600384015460048501546005909501549395506001600160a01b03928316949193909291821691811690600160a01b900460ff1687565b600260205281600052604060002081815481106107bc57600080fd5b90600052602060002001600091509150505481565b6001600160a01b03841660009081526001602090815260408083208684529091528120548154829190811061080857610808610ec9565b60009182526020918290206040805160e0810182526006939093029091018054835260018101546001600160a01b03908116948401949094526002810154918301829052600381015460608401526004810154841660808401526005015492831660a0830152600160a01b90920460ff1660c08201529150821480156108a35750826001600160a01b031681602001516001600160a01b0316145b6109245760405162461bcd60e51b815260206004820152604660248201527f4e6f7420726967687420616d6f756e74206f722063757272656e63792073656e60448201527f742c206861766520746f20626520657175616c2063757272656e637920616e6460648201526520707269636560d01b608482015260a4016101f3565b80602001516001600160a01b03166323b872dd333084604001516040518463ffffffff1660e01b815260040161095c93929190610e80565b602060405180830381600087803b15801561097657600080fd5b505af115801561098a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109ae9190610de0565b50602081015160a0820151604080840151905163a9059cbb60e01b81526001600160a01b039283166004820152602481019190915291169063a9059cbb90604401602060405180830381600087803b158015610a0957600080fd5b505af1158015610a1d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a419190610de0565b506001600160a01b038516600090815260016020908152604080832087845290915281205481548291908110610a7957610a79610ec9565b906000526020600020906006020160050160146101000a81548160ff021916908360ff160217905550846001600160a01b03166323b872dd3033876040518463ffffffff1660e01b8152600401610ad293929190610e80565b600060405180830381600087803b158015610aec57600080fd5b505af1158015610b00573d6000803e3d6000fd5b505050505050505050565b6001600160a01b038216600090815260016020908152604080832084845290915281205481548291908110610b4257610b42610ec9565b60009182526020918290206040805160e0810182526006939093029091018054835260018101546001600160a01b03908116948401949094526002810154918301829052600381015460608401526004810154841660808401526005015492831660a0830152600160a01b90920460ff1660c082015291503414610c225760405162461bcd60e51b815260206004820152603160248201527f4e6f7420726967687420616d6f756e7420554e512073656e742c206861766520604482015270746f20626520657175616c20707269636560781b60648201526084016101f3565b8060a001516001600160a01b03166108fc82604001519081150290604051600060405180830381858888f19350505050158015610c63573d6000803e3d6000fd5b506001600160a01b038316600090815260016020908152604080832085845290915281205481548291908110610c9b57610c9b610ec9565b906000526020600020906006020160050160146101000a81548160ff021916908360ff160217905550826001600160a01b03166323b872dd3033856040518463ffffffff1660e01b8152600401610cf493929190610e80565b600060405180830381600087803b158015610d0e57600080fd5b505af1158015610d22573d6000803e3d6000fd5b50505050505050565b600060208284031215610d3d57600080fd5b8135610d4881610edf565b9392505050565b600060208284031215610d6157600080fd5b8151610d4881610edf565b60008060408385031215610d7f57600080fd5b8235610d8a81610edf565b946020939093013593505050565b60008060008060808587031215610dae57600080fd5b8435610db981610edf565b9350602085013592506040850135610dd081610edf565b9396929550929360600135925050565b600060208284031215610df257600080fd5b81518015158114610d4857600080fd5b600060208284031215610e1457600080fd5b5035919050565b600080600080600060a08688031215610e3357600080fd5b853594506020860135610e4581610edf565b93506040860135610e5581610edf565b925060608601359150608086013560ff81168114610e7257600080fd5b809150509295509295909350565b6001600160a01b039384168152919092166020820152604081019190915260600190565b600082821015610ec457634e487b7160e01b600052601160045260246000fd5b500390565b634e487b7160e01b600052603260045260246000fd5b6001600160a01b0381168114610ef457600080fd5b5056fea2646970667358221220fbf33eb1e471c428b86ad6d948b8699fd08a127b923d5fe27ec1e1ec5f59627564736f6c63430008070033
\ No newline at end of file
tests/src/eth/marketplace/MarketPlaceUNQ.soldiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/marketplace/MarketPlaceUNQ.sol
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: Apache License
+pragma solidity >=0.8.0;
+
+interface IERC721 {
+ event Transfer(
+ address indexed from,
+ address indexed to,
+ uint256 indexed tokenId
+ );
+ event Approval(
+ address indexed owner,
+ address indexed approved,
+ uint256 indexed tokenId
+ );
+
+ function ownerOf(uint256 tokenId) external view returns (address owner);
+
+ function transferFrom(
+ address from,
+ address to,
+ uint256 tokenId
+ ) external;
+
+ function debug(string memory value) external;
+}
+
+interface IERC20 {
+ event Transfer(address indexed from, address indexed to, uint256 value);
+ event Approval(
+ address indexed owner,
+ address indexed spender,
+ uint256 value
+ );
+
+ function transfer(address recipient, uint256 amount)
+ external
+ returns (bool);
+
+ function transferFrom(
+ address sender,
+ address recipient,
+ uint256 amount
+ ) external returns (bool);
+}
+
+contract MarketPlaceUNQ {
+ struct Offer {
+ uint256 idNFT;
+ address currencyCode; //address of currency token, = address(0) for UNQ
+ uint256 price;
+ uint256 time;
+ address idCollection;
+ address userAddr;
+ uint8 flagActive;
+ }
+ Offer[] public offers;
+
+ mapping(address => mapping(uint256 => uint256)) public asks; // [idCollection][idNFT] => idOffer
+
+ mapping(address => uint256[]) public asksbySeller; // [addressSeller] =>idOffer
+
+ address owner;
+
+ constructor() {
+ owner = msg.sender;
+ }
+
+ function setowner(address _newOwner) public onlyOwner {
+ owner = _newOwner;
+ }
+
+ modifier onlyOwner() {
+ require(msg.sender == owner, "Only owner can");
+ _;
+ }
+
+ /**
+ * Make bids (offers) to sell NFTs
+ */
+ function setAsk(
+ uint256 _price,
+ address _currencyCode,
+ address _idCollection,
+ uint256 _idNFT,
+ uint8 _active
+ ) public {
+ require(
+ IERC721(_idCollection).ownerOf(_idNFT) == msg.sender,
+ "Not right token owner"
+ );
+ uint256 offerID = asks[_idCollection][_idNFT];
+ if (offers.length == 0 || offers[offerID].idCollection == address(0)) {
+ offers.push(
+ Offer(
+ _idNFT,
+ _currencyCode,
+ _price,
+ block.timestamp,
+ _idCollection,
+ msg.sender,
+ _active
+ )
+ );
+ asks[_idCollection][_idNFT] = offers.length - 1;
+ asksbySeller[msg.sender].push(offers.length - 1);
+ }
+ //edit existing offer
+ else {
+ offers[asks[_idCollection][_idNFT]] = Offer(
+ offers[asks[_idCollection][_idNFT]].idNFT,
+ _currencyCode,
+ _price,
+ block.timestamp,
+ offers[asks[_idCollection][_idNFT]].idCollection,
+ msg.sender,
+ _active
+ );
+ }
+
+ IERC721(_idCollection).transferFrom(msg.sender, address(this), _idNFT);
+ }
+
+ function buy(address _idCollection, uint256 _idNFT) public payable {
+ //buing for UNQ like as ethers
+ Offer memory offer = offers[asks[_idCollection][_idNFT]];
+ //1. check sent amount and send to seller
+ require(
+ msg.value == offer.price,
+ "Not right amount UNQ sent, have to be equal price"
+ );
+ payable(offer.userAddr).transfer(offer.price);
+ // 2. close offer
+ offers[asks[_idCollection][_idNFT]].flagActive = 0;
+ // 3. transfer NFT to buyer
+ IERC721(_idCollection).transferFrom(address(this), msg.sender, _idNFT);
+ }
+
+ function buy(
+ address _idCollection,
+ uint256 _idNFT,
+ address _currencyCode,
+ uint256 _amount
+ ) public payable {
+ Offer memory offer = offers[asks[_idCollection][_idNFT]];
+ //1. check sent amount and transfer from buyer to seller
+ require(
+ offer.price == _amount && offer.currencyCode == _currencyCode,
+ "Not right amount or currency sent, have to be equal currency and price"
+ );
+ // !!! transfer have to be approved to marketplace!
+ IERC20(offer.currencyCode).transferFrom(
+ msg.sender,
+ address(this),
+ offer.price
+ );
+ //to not disclojure buyer's address
+ IERC20(offer.currencyCode).transfer(offer.userAddr, offer.price);
+ // 2. close offer
+ offers[asks[_idCollection][_idNFT]].flagActive = 0;
+ // 3. transfer NFT to buyer
+ IERC721(_idCollection).transferFrom(address(this), msg.sender, _idNFT);
+ }
+}
tests/src/eth/marketplace/marketplace.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/marketplace/marketplace.test.ts
@@ -0,0 +1,198 @@
+import { readFile } from 'fs/promises';
+import { getBalanceSingle, transferBalanceExpectSuccess } from '../../substrate/get-balance';
+import privateKey from '../../substrate/privateKey';
+import { createCollectionExpectSuccess, createFungibleItemExpectSuccess, createItemExpectSuccess, queryNftOwner, transferExpectSuccess, transferFromExpectSuccess } from '../../util/helpers';
+import { collectionIdToAddress, createEthAccountWithBalance, executeEthTxOnSub, GAS_ARGS, itWeb3, subToEth, subToEthLowercase } from '../util/helpers';
+import { evmToAddress } from '@polkadot/util-crypto';
+import nonFungibleAbi from '../nonFungibleAbi.json';
+import fungibleAbi from '../fungibleAbi.json';
+import waitNewBlocks from '../../substrate/wait-new-blocks';
+import { expect } from 'chai';
+
+const PRICE = 2000n;
+
+describe('Matcher contract usage', () => {
+ itWeb3('With UNQ', async ({api, web3}) => {
+ const matcherOwner = await createEthAccountWithBalance(api, web3);
+ const Matcher = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/MarketPlaceUNQ.abi`)).toString()), undefined, {
+ from: matcherOwner,
+ ...GAS_ARGS,
+ });
+ const matcher = await Matcher.deploy({ data: (await readFile(`${__dirname}/MarketPlaceUNQ.bin`)).toString() }).send({ from: matcherOwner });
+
+ const alice = privateKey('//Alice');
+ const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId), { from: matcherOwner });
+
+ const seller = privateKey('//Bob');
+
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', seller.address);
+
+ // To transfer item to matcher it first needs to be transfered to EVM account of bob
+ await transferExpectSuccess(collectionId, tokenId, seller, {ethereum: subToEth(seller.address)});
+ // Fees will be paid from EVM account, so we should have some balance here
+ await transferBalanceExpectSuccess(api, seller, evmToAddress(subToEth(seller.address)), 10n ** 18n);
+ await transferBalanceExpectSuccess(api, alice, evmToAddress(subToEth(alice.address)), 10n ** 18n);
+ await waitNewBlocks(api, 1);
+
+ // Token is owned by seller initially
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ ethereum: subToEthLowercase(seller.address) });
+
+ // Ask
+ {
+ await executeEthTxOnSub(api, seller, evmCollection, m => m.approve(matcher.options.address, tokenId));
+ await executeEthTxOnSub(api, seller, matcher, m => m.setAsk(PRICE, '0x0000000000000000000000000000000000000000', evmCollection.options.address, tokenId, 1));
+ }
+
+ // Token is transferred to matcher
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ ethereum: matcher.options.address.toLowerCase() });
+
+ // Buy
+ {
+ const sellerBalanceBeforePurchase = await getBalanceSingle(api, seller.address);
+ // There is two functions named 'buy', so we should provide full signature
+ await executeEthTxOnSub(api, alice, matcher, m => m['buy(address,uint256)'](evmCollection.options.address, tokenId), { value: PRICE });
+ expect(await getBalanceSingle(api, seller.address) - sellerBalanceBeforePurchase === PRICE);
+ }
+
+ // Token is transferred to evm account of alice
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ ethereum: subToEthLowercase(alice.address) });
+
+
+ // Transfer token to substrate side of alice
+ await transferFromExpectSuccess(collectionId, tokenId, alice, { ethereum: subToEth(alice.address) }, { substrate: alice.address });
+
+ // Token is transferred to substrate account of alice, seller received funds
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ substrate: alice.address });
+ });
+
+ itWeb3('With custom ERC20', async ({api, web3}) => {
+ const matcherOwner = await createEthAccountWithBalance(api, web3);
+ const Matcher = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/MarketPlaceUNQ.abi`)).toString()), undefined, {
+ from: matcherOwner,
+ ...GAS_ARGS,
+ });
+ const matcher = await Matcher.deploy({ data: (await readFile(`${__dirname}/MarketPlaceUNQ.bin`)).toString() }).send({ from: matcherOwner });
+
+ const alice = privateKey('//Alice');
+ const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId), { from: matcherOwner });
+
+ const fungibleId = await createCollectionExpectSuccess({ mode: { type: 'Fungible', decimalPoints: 0 } });
+ const evmFungible = new web3.eth.Contract(fungibleAbi as any, collectionIdToAddress(fungibleId), { from: matcherOwner, ...GAS_ARGS });
+ await createFungibleItemExpectSuccess(alice, fungibleId, { Value: PRICE }, { ethereum: subToEth(alice.address) });
+
+ const seller = privateKey('//Bob');
+
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', seller.address);
+
+ // To transfer item to matcher it first needs to be transfered to EVM account of bob
+ await transferExpectSuccess(collectionId, tokenId, seller, {ethereum: subToEth(seller.address)});
+ // Fees will be paid from EVM account, so we should have some balance here
+ await transferBalanceExpectSuccess(api, seller, evmToAddress(subToEth(seller.address)), 10n ** 18n);
+ await transferBalanceExpectSuccess(api, alice, evmToAddress(subToEth(alice.address)), 10n ** 18n);
+ await waitNewBlocks(api, 1);
+
+ // Token is owned by seller initially
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ ethereum: subToEthLowercase(seller.address) });
+
+ // Ask
+ {
+ await executeEthTxOnSub(api, seller, evmCollection, m => m.approve(matcher.options.address, tokenId));
+ await executeEthTxOnSub(api, seller, matcher, m => m.setAsk(PRICE, evmFungible.options.address, evmCollection.options.address, tokenId, 1));
+ }
+
+ // Token is transferred to matcher
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ ethereum: matcher.options.address.toLowerCase() });
+
+ // Buy
+ {
+ const sellerBalanceBeforePurchase = BigInt(await evmFungible.methods.balanceOf(subToEth(seller.address)).call());
+ const buyerBalanceBeforePurchase = BigInt(await evmFungible.methods.balanceOf(subToEth(alice.address)).call());
+
+ await executeEthTxOnSub(api, alice, evmFungible, m => m.approve(matcher.options.address, PRICE));
+ // There is two functions named 'buy', so we should provide full signature
+ await executeEthTxOnSub(api, alice, matcher, m =>
+ m['buy(address,uint256,address,uint256)'](evmCollection.options.address, tokenId, evmFungible.options.address, PRICE));
+
+ // Approved price is removed from buyer balance, and added to seller
+ expect(BigInt(await evmFungible.methods.balanceOf(subToEth(seller.address)).call()) - sellerBalanceBeforePurchase === PRICE);
+ expect(buyerBalanceBeforePurchase - BigInt(await evmFungible.methods.balanceOf(subToEth(alice.address)).call()) === PRICE);
+ }
+
+ // Token is transferred to evm account of alice
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ ethereum: subToEthLowercase(alice.address) });
+
+
+ // Transfer token to substrate side of alice
+ await transferFromExpectSuccess(collectionId, tokenId, alice, { ethereum: subToEth(alice.address) }, { substrate: alice.address });
+
+ // Token is transferred to substrate account of alice
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ substrate: alice.address });
+ });
+
+ itWeb3('With escrow', async ({ api, web3 }) => {
+ const matcherOwner = await createEthAccountWithBalance(api, web3);
+ const escrow = await createEthAccountWithBalance(api, web3);
+ const Matcher = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/MarketPlaceKSM.abi`)).toString()), undefined, {
+ from: matcherOwner,
+ ...GAS_ARGS,
+ });
+ const matcher = await Matcher.deploy({ data: (await readFile(`${__dirname}/MarketPlaceKSM.bin`)).toString(), arguments: [escrow] }).send({ from: matcherOwner });
+
+ const ksmToken = 11;
+
+ const alice = privateKey('//Alice');
+ const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId), { from: matcherOwner });
+
+ const seller = privateKey('//Bob');
+
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', seller.address);
+
+ // To transfer item to matcher it first needs to be transfered to EVM account of bob
+ await transferExpectSuccess(collectionId, tokenId, seller, {ethereum: subToEth(seller.address)});
+ // Fees will be paid from EVM account, so we should have some balance here
+ await transferBalanceExpectSuccess(api, seller, evmToAddress(subToEth(seller.address)), 10n ** 18n);
+ await transferBalanceExpectSuccess(api, alice, evmToAddress(subToEth(alice.address)), 10n ** 18n);
+ await waitNewBlocks(api, 1);
+
+ // Token is owned by seller initially
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ ethereum: subToEthLowercase(seller.address) });
+
+ // Ask
+ {
+ await executeEthTxOnSub(api, seller, evmCollection, m => m.approve(matcher.options.address, tokenId));
+ await executeEthTxOnSub(api, seller, matcher, m => m.setAsk(PRICE, ksmToken, evmCollection.options.address, tokenId, 1));
+ }
+
+ // Token is transferred to matcher
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ ethereum: matcher.options.address.toLowerCase() });
+
+ // Give buyer KSM
+ await matcher.methods.deposit(PRICE, ksmToken, subToEth(alice.address)).send({ from: escrow });
+ await waitNewBlocks(api, 1);
+
+ // Buy
+ {
+ expect(await matcher.methods.escrowBalance(ksmToken, subToEth(seller.address)).call()).to.be.equal('0');
+ expect(await matcher.methods.escrowBalance(ksmToken, subToEth(alice.address)).call()).to.be.equal(PRICE.toString());
+
+ await executeEthTxOnSub(api, alice, matcher, m => m.buy(evmCollection.options.address, tokenId));
+ await waitNewBlocks(api, 1);
+
+ // Price is removed from buyer balance, and added to seller
+ expect(await matcher.methods.escrowBalance(ksmToken, subToEth(alice.address)).call()).to.be.equal('0');
+ expect(await matcher.methods.escrowBalance(ksmToken, subToEth(seller.address)).call()).to.be.equal(PRICE.toString());
+ }
+
+ // Token is transferred to evm account of alice
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ ethereum: subToEthLowercase(alice.address) });
+
+ // Transfer token to substrate side of alice
+ await transferFromExpectSuccess(collectionId, tokenId, alice, { ethereum: subToEth(alice.address) }, { substrate: alice.address });
+
+ // Token is transferred to substrate account of alice, seller received funds
+ expect(await queryNftOwner(api, collectionId, tokenId)).to.be.deep.equal({ substrate: alice.address });
+ });
+});
tests/src/eth/util/helpers.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -143,10 +143,13 @@
return normalizeEvents(out);
}
+export function subToEthLowercase(eth: string): string {
+ const bytes = addressToEvm(eth);
+ return '0x' + Buffer.from(bytes).toString('hex');
+}
+
export function subToEth(eth: string): string {
- const bytes = addressToEvm(eth);
- const string = '0x' + Buffer.from(bytes).toString('hex');
- return Web3.utils.toChecksumAddress(string);
+ return Web3.utils.toChecksumAddress(subToEthLowercase(eth));
}
export function compileContract(name: string, src: string) {
@@ -236,6 +239,20 @@
return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});
}
+export async function executeEthTxOnSub(api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, { value = 0 }: {value?: bigint | number} = { }) {
+ const tx = api.tx.evm.call(
+ subToEth(from.address),
+ to.options.address,
+ mkTx(to.methods).encodeABI(),
+ value,
+ GAS_ARGS.gas,
+ GAS_ARGS.gasPrice,
+ null,
+ );
+ const events = await submitTransactionAsync(from, tx);
+ expect(events.find(({ event: {section, method}})=>section === 'evm' && method === 'Executed')).to.be.not.undefined;
+}
+
export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {
return (await getBalance(api, [evmToAddress(address)]))[0];
}
tests/src/util/helpers.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import { IKeyringPair } from '@polkadot/types/types';9import { evmToAddress } from '@polkadot/util-crypto';10import { BigNumber } from 'bignumber.js';11import BN from 'bn.js';12import chai from 'chai';13import chaiAsPromised from 'chai-as-promised';14import { alicesPublicKey } from '../accounts';15import privateKey from '../substrate/privateKey';16import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';17import { ICollectionInterface } from '../types';18import { hexToStr, strToUTF16, utf16ToStr } from './util';1920chai.use(chaiAsPromised);21const expect = chai.expect;2223export type CrossAccountId = {24 substrate: string,25} | {26 ethereum: string,27};28export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {29 if (typeof input === 'string')30 return { substrate: input };31 if ('address' in input) {32 return { substrate: input.address };33 }34 if ('ethereum' in input) {35 input.ethereum = input.ethereum.toLowerCase();36 return input;37 }38 if ('substrate' in input) {39 return input;40 }4142 // AccountId43 return {substrate: input.toString()};44}45export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {46 input = normalizeAccountId(input);47 if ('substrate' in input) {48 return input.substrate;49 } else {50 return evmToAddress(input.ethereum);51 }52}5354export const U128_MAX = (1n << 128n) - 1n;5556const MICROUNIQUE = 1_000_000_000n;57const MILLIUNIQUE = 1_000n * MICROUNIQUE;58const CENTIUNIQUE = 10n * MILLIUNIQUE;59export const UNIQUE = 100n * CENTIUNIQUE;6061type GenericResult = {62 success: boolean,63};6465interface CreateCollectionResult {66 success: boolean;67 collectionId: number;68}6970interface CreateItemResult {71 success: boolean;72 collectionId: number;73 itemId: number;74 recipient?: CrossAccountId;75}7677interface TransferResult {78 success: boolean;79 collectionId: number;80 itemId: number;81 sender?: CrossAccountId;82 recipient?: CrossAccountId;83 value: bigint;84}8586interface IReFungibleOwner {87 Fraction: BN;88 Owner: number[];89}9091interface ITokenDataType {92 Owner: IKeyringPair;93 ConstData: number[];94 VariableData: number[];95}9697interface IGetMessage {98 checkMsgNftMethod: string;99 checkMsgTrsMethod: string;100 checkMsgSysMethod: string;101}102103export interface IFungibleTokenDataType {104 Value: number;105}106107export interface IChainLimits {108 CollectionNumbersLimit: number;109 AccountTokenOwnershipLimit: number;110 CollectionsAdminsLimit: number;111 CustomDataLimit: number;112 NftSponsorTransferTimeout: number;113 FungibleSponsorTransferTimeout: number;114 RefungibleSponsorTransferTimeout: number;115 OffchainSchemaLimit: number;116 VariableOnChainSchemaLimit: number;117 ConstOnChainSchemaLimit: number;118}119120export interface IReFungibleTokenDataType {121 Owner: IReFungibleOwner[];122 ConstData: number[];123 VariableData: number[];124}125126export function nftEventMessage(events: EventRecord[]): IGetMessage {127 let checkMsgNftMethod = '';128 let checkMsgTrsMethod = '';129 let checkMsgSysMethod = '';130 events.forEach(({ event: { method, section } }) => {131 if (section === 'nft') {132 checkMsgNftMethod = method;133 } else if (section === 'treasury') {134 checkMsgTrsMethod = method;135 } else if (section === 'system') {136 checkMsgSysMethod = method;137 } else { return null; }138 });139 const result: IGetMessage = {140 checkMsgNftMethod,141 checkMsgTrsMethod,142 checkMsgSysMethod,143 };144 return result;145}146147export function getGenericResult(events: EventRecord[]): GenericResult {148 const result: GenericResult = {149 success: false,150 };151 events.forEach(({ event: { method } }) => {152 // console.log(` ${phase}: ${section}.${method}:: ${data}`);153 if (method === 'ExtrinsicSuccess') {154 result.success = true;155 }156 });157 return result;158}159160161162export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {163 let success = false;164 let collectionId = 0;165 events.forEach(({ event: { data, method, section } }) => {166 // console.log(` ${phase}: ${section}.${method}:: ${data}`);167 if (method == 'ExtrinsicSuccess') {168 success = true;169 } else if ((section == 'nft') && (method == 'CollectionCreated')) {170 collectionId = parseInt(data[0].toString());171 }172 });173 const result: CreateCollectionResult = {174 success,175 collectionId,176 };177 return result;178}179180export function getCreateItemResult(events: EventRecord[]): CreateItemResult {181 let success = false;182 let collectionId = 0;183 let itemId = 0;184 let recipient;185 events.forEach(({ event: { data, method, section } }) => {186 // console.log(` ${phase}: ${section}.${method}:: ${data}`);187 if (method == 'ExtrinsicSuccess') {188 success = true;189 } else if ((section == 'nft') && (method == 'ItemCreated')) {190 collectionId = parseInt(data[0].toString());191 itemId = parseInt(data[1].toString());192 recipient = data[2].toJSON();193 }194 });195 const result: CreateItemResult = {196 success,197 collectionId,198 itemId,199 recipient,200 };201 return result;202}203204export function getTransferResult(events: EventRecord[]): TransferResult {205 const result: TransferResult = {206 success: false,207 collectionId: 0,208 itemId: 0,209 value: 0n,210 };211212 events.forEach(({ event: { data, method, section } }) => {213 if (method === 'ExtrinsicSuccess') {214 result.success = true;215 } else if (section === 'nft' && method === 'Transfer') {216 result.collectionId = +data[0].toString();217 result.itemId = +data[1].toString();218 result.sender = data[2].toJSON() as CrossAccountId;219 result.recipient = data[3].toJSON() as CrossAccountId;220 result.value = BigInt(data[4].toString());221 }222 });223224 return result;225}226227interface Invalid {228 type: 'Invalid';229}230231interface Nft {232 type: 'NFT';233}234235interface Fungible {236 type: 'Fungible';237 decimalPoints: number;238}239240interface ReFungible {241 type: 'ReFungible';242}243244type CollectionMode = Nft | Fungible | ReFungible | Invalid;245246export type CreateCollectionParams = {247 mode: CollectionMode,248 name: string,249 description: string,250 tokenPrefix: string,251};252253const defaultCreateCollectionParams: CreateCollectionParams = {254 description: 'description',255 mode: { type: 'NFT' },256 name: 'name',257 tokenPrefix: 'prefix',258};259260export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {261 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };262263 let collectionId = 0;264 await usingApi(async (api) => {265 // Get number of collections before the transaction266 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);267268 // Run the CreateCollection transaction269 const alicePrivateKey = privateKey('//Alice');270271 let modeprm = {};272 if (mode.type === 'NFT') {273 modeprm = { nft: null };274 } else if (mode.type === 'Fungible') {275 modeprm = { fungible: mode.decimalPoints };276 } else if (mode.type === 'ReFungible') {277 modeprm = { refungible: null };278 } else if (mode.type === 'Invalid') {279 modeprm = { invalid: null };280 }281282 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);283 const events = await submitTransactionAsync(alicePrivateKey, tx);284 const result = getCreateCollectionResult(events);285286 // Get number of collections after the transaction287 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);288289 // Get the collection290 const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();291292 // What to expect293 // tslint:disable-next-line:no-unused-expression294 expect(result.success).to.be.true;295 expect(result.collectionId).to.be.equal(BcollectionCount);296 // tslint:disable-next-line:no-unused-expression297 expect(collection).to.be.not.null;298 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');299 expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));300 expect(utf16ToStr(collection.Name)).to.be.equal(name);301 expect(utf16ToStr(collection.Description)).to.be.equal(description);302 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);303304 collectionId = result.collectionId;305 });306307 return collectionId;308}309310export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {311 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };312313 let modeprm = {};314 if (mode.type === 'NFT') {315 modeprm = { nft: null };316 } else if (mode.type === 'Fungible') {317 modeprm = { fungible: mode.decimalPoints };318 } else if (mode.type === 'ReFungible') {319 modeprm = { refungible: null };320 } else if (mode.type === 'Invalid') {321 modeprm = { invalid: null };322 }323324 await usingApi(async (api) => {325 // Get number of collections before the transaction326 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());327328 // Run the CreateCollection transaction329 const alicePrivateKey = privateKey('//Alice');330 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);331 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;332 const result = getCreateCollectionResult(events);333334 // Get number of collections after the transaction335 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());336337 // What to expect338 // tslint:disable-next-line:no-unused-expression339 expect(result.success).to.be.false;340 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');341 });342}343344export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {345 let bal = new BigNumber(0);346 let unused;347 do {348 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;349 const keyring = new Keyring({ type: 'sr25519' });350 unused = keyring.addFromUri(`//${randomSeed}`);351 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());352 } while (bal.toFixed() != '0');353 return unused;354}355356export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {357 return await usingApi(async (api) => {358 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;359 return BigInt(bn.toString());360 });361}362363export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {364 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));365}366367export async function findNotExistingCollection(api: ApiPromise): Promise<number> {368 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;369 const newCollection: number = totalNumber + 1;370 return newCollection;371}372373function getDestroyResult(events: EventRecord[]): boolean {374 let success = false;375 events.forEach(({ event: { method } }) => {376 if (method == 'ExtrinsicSuccess') {377 success = true;378 }379 });380 return success;381}382383export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {384 await usingApi(async (api) => {385 // Run the DestroyCollection transaction386 const alicePrivateKey = privateKey(senderSeed);387 const tx = api.tx.nft.destroyCollection(collectionId);388 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;389 });390}391392export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {393 await usingApi(async (api) => {394 // Run the DestroyCollection transaction395 const alicePrivateKey = privateKey(senderSeed);396 const tx = api.tx.nft.destroyCollection(collectionId);397 const events = await submitTransactionAsync(alicePrivateKey, tx);398 const result = getDestroyResult(events);399400 // Get the collection401 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();402403 // What to expect404 expect(result).to.be.true;405 expect(collection).to.be.null;406 });407}408409export async function queryCollectionLimits(collectionId: number) {410 return await usingApi(async (api) => {411 return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;412 });413}414415export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {416 await usingApi(async (api) => {417 const oldLimits = await queryCollectionLimits(collectionId);418 const newLimits = { ...oldLimits as any, ...limits };419 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);420 const events = await submitTransactionAsync(sender, tx);421 const result = getGenericResult(events);422423 expect(result.success).to.be.true;424 });425}426427export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {428 await usingApi(async (api) => {429 const oldLimits = await queryCollectionLimits(collectionId);430 const newLimits = { ...oldLimits as any, ...limits };431 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);432 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;433 const result = getGenericResult(events);434435 expect(result.success).to.be.false;436 });437}438439export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {440 await usingApi(async (api) => {441442 // Run the transaction443 const senderPrivateKey = privateKey(sender);444 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);445 const events = await submitTransactionAsync(senderPrivateKey, tx);446 const result = getGenericResult(events);447448 // Get the collection449 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();450451 // What to expect452 expect(result.success).to.be.true;453 expect(collection.Sponsorship).to.deep.equal({454 unconfirmed: sponsor,455 });456 });457}458459export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {460 await usingApi(async (api) => {461462 // Run the transaction463 const alicePrivateKey = privateKey(sender);464 const tx = api.tx.nft.removeCollectionSponsor(collectionId);465 const events = await submitTransactionAsync(alicePrivateKey, tx);466 const result = getGenericResult(events);467468 // Get the collection469 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();470471 // What to expect472 expect(result.success).to.be.true;473 expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });474 });475}476477export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {478 await usingApi(async (api) => {479480 // Run the transaction481 const alicePrivateKey = privateKey(senderSeed);482 const tx = api.tx.nft.removeCollectionSponsor(collectionId);483 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;484 });485}486487export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {488 await usingApi(async (api) => {489490 // Run the transaction491 const alicePrivateKey = privateKey(senderSeed);492 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);493 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;494 });495}496497export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {498 await usingApi(async (api) => {499500 // Run the transaction501 const sender = privateKey(senderSeed);502 const tx = api.tx.nft.confirmSponsorship(collectionId);503 const events = await submitTransactionAsync(sender, tx);504 const result = getGenericResult(events);505506 // Get the collection507 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();508509 // What to expect510 expect(result.success).to.be.true;511 expect(collection.Sponsorship).to.be.deep.equal({512 confirmed: sender.address,513 });514 });515}516517518export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {519 await usingApi(async (api) => {520521 // Run the transaction522 const sender = privateKey(senderSeed);523 const tx = api.tx.nft.confirmSponsorship(collectionId);524 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;525 });526}527528export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {529 await usingApi(async (api) => {530 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);531 const events = await submitTransactionAsync(sender, tx);532 const result = getGenericResult(events);533534 expect(result.success).to.be.true;535 });536}537538export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {539 await usingApi(async (api) => {540 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);541 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;542 const result = getGenericResult(events);543544 expect(result.success).to.be.false;545 });546}547548export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {549550 await usingApi(async (api) => {551552 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);553 const events = await submitTransactionAsync(sender, tx);554 const result = getGenericResult(events);555556 expect(result.success).to.be.true;557 }); 558}559560export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {561562 await usingApi(async (api) => {563564 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);565 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;566 const result = getGenericResult(events);567568 expect(result.success).to.be.false;569 }); 570}571572export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {573 await usingApi(async (api) => {574 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);575 const events = await submitTransactionAsync(sender, tx);576 const result = getGenericResult(events);577578 expect(result.success).to.be.true;579 });580}581582export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {583 await usingApi(async (api) => {584 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);585 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;586 const result = getGenericResult(events);587588 expect(result.success).to.be.false;589 });590}591592export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {593 await usingApi(async (api) => {594 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);595 const events = await submitTransactionAsync(sender, tx);596 const result = getGenericResult(events);597598 expect(result.success).to.be.true;599 });600}601602export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {603 let whitelisted = false;604 await usingApi(async (api) => {605 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;606 });607 return whitelisted;608}609610export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {611 await usingApi(async (api) => {612 const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());613 const events = await submitTransactionAsync(sender, tx);614 const result = getGenericResult(events);615616 expect(result.success).to.be.true;617 });618}619620export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {621 await usingApi(async (api) => {622 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());623 const events = await submitTransactionAsync(sender, tx);624 const result = getGenericResult(events);625626 expect(result.success).to.be.true;627 });628}629630export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {631 await usingApi(async (api) => {632 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());633 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;634 const result = getGenericResult(events);635636 expect(result.success).to.be.false;637 });638}639640export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {641 await usingApi(async (api) => {642 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));643 const events = await submitTransactionAsync(sender, tx);644 const result = getGenericResult(events);645646 expect(result.success).to.be.true;647 });648}649650export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {651 await usingApi(async (api) => {652 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));653 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;654 });655}656657export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {658 await usingApi(async (api) => {659 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));660 const events = await submitTransactionAsync(sender, tx);661 const result = getGenericResult(events);662663 expect(result.success).to.be.true;664 });665}666667export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {668 await usingApi(async (api) => {669 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));670 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;671 });672}673674export interface CreateFungibleData {675 readonly Value: bigint;676}677678export interface CreateReFungibleData { }679export interface CreateNftData { }680681export type CreateItemData = {682 NFT: CreateNftData;683} | {684 Fungible: CreateFungibleData;685} | {686 ReFungible: CreateReFungibleData;687};688689export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {690 await usingApi(async (api) => {691 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);692 const events = await submitTransactionAsync(owner, tx);693 const result = getGenericResult(events);694 // Get the item695 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();696 // What to expect697 // tslint:disable-next-line:no-unused-expression698 expect(result.success).to.be.true;699 // tslint:disable-next-line:no-unused-expression700 expect(item).to.be.null;701 });702}703704export async function705approveExpectSuccess(706 collectionId: number,707 tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1,708) {709 await usingApi(async (api: ApiPromise) => {710 approved = normalizeAccountId(approved);711 const allowanceBefore =712 await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;713 const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);714 const events = await submitTransactionAsync(owner, approveNftTx);715 const result = getCreateItemResult(events);716 // tslint:disable-next-line:no-unused-expression717 expect(result.success).to.be.true;718 const allowanceAfter =719 await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;720 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());721 });722}723724export async function725transferFromExpectSuccess(726 collectionId: number,727 tokenId: number,728 accountApproved: IKeyringPair,729 accountFrom: IKeyringPair | CrossAccountId,730 accountTo: IKeyringPair | CrossAccountId,731 value: number | bigint = 1,732 type = 'NFT',733) {734 await usingApi(async (api: ApiPromise) => {735 const to = normalizeAccountId(accountTo);736 let balanceBefore = new BN(0);737 if (type === 'Fungible') {738 balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;739 }740 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);741 const events = await submitTransactionAsync(accountApproved, transferFromTx);742 const result = getCreateItemResult(events);743 // tslint:disable-next-line:no-unused-expression744 expect(result.success).to.be.true;745 if (type === 'NFT') {746 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;747 expect(nftItemData.Owner).to.be.deep.equal(to);748 }749 if (type === 'Fungible') {750 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;751 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());752 }753 if (type === 'ReFungible') {754 const nftItemData =755 (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;756 expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));757 expect(nftItemData.Owner[0].Fraction).to.be.equal(value);758 }759 });760}761762export async function763transferFromExpectFail(764 collectionId: number,765 tokenId: number,766 accountApproved: IKeyringPair,767 accountFrom: IKeyringPair,768 accountTo: IKeyringPair,769 value: number | bigint = 1,770) {771 await usingApi(async (api: ApiPromise) => {772 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);773 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;774 const result = getCreateCollectionResult(events);775 // tslint:disable-next-line:no-unused-expression776 expect(result.success).to.be.false;777 });778}779780/* eslint no-async-promise-executor: "off" */781async function getBlockNumber(api: ApiPromise): Promise<number> {782 return new Promise<number>(async (resolve) => {783 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {784 unsubscribe();785 resolve(head.number.toNumber());786 });787 });788}789790export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: IKeyringPair) {791 await usingApi(async (api) => {792 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(address.address));793 const events = await submitTransactionAsync(sender, changeAdminTx);794 const result = getCreateCollectionResult(events);795 expect(result.success).to.be.true;796 });797}798799export async function800scheduleTransferExpectSuccess(801 collectionId: number,802 tokenId: number,803 sender: IKeyringPair,804 recipient: IKeyringPair,805 value: number | bigint = 1,806 blockTimeMs: number,807 blockSchedule: number,808) {809 await usingApi(async (api: ApiPromise) => {810 const blockNumber: number | undefined = await getBlockNumber(api);811 const expectedBlockNumber = blockNumber + blockSchedule;812813 expect(blockNumber).to.be.greaterThan(0);814 const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value); 815 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);816817 await submitTransactionAsync(sender, scheduleTx);818819 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());820821 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as any as ITokenDataType;822 expect(toSubstrateAddress(nftItemDataBefore.Owner)).to.be.equal(sender.address);823824 // sleep for 4 blocks825 await new Promise(resolve => setTimeout(resolve, blockTimeMs * (blockSchedule + 1)));826827 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());828829 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;830 expect(toSubstrateAddress(nftItemData.Owner)).to.be.equal(recipient.address);831 expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());832 });833}834835836export async function837transferExpectSuccess(838 collectionId: number,839 tokenId: number,840 sender: IKeyringPair,841 recipient: IKeyringPair | CrossAccountId,842 value: number | bigint = 1,843 type = 'NFT',844) {845 await usingApi(async (api: ApiPromise) => {846 const to = normalizeAccountId(recipient);847848 let balanceBefore = new BN(0);849 if (type === 'Fungible') {850 balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;851 }852 const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);853 const events = await submitTransactionAsync(sender, transferTx);854 const result = getTransferResult(events);855 // tslint:disable-next-line:no-unused-expression856 expect(result.success).to.be.true;857 expect(result.collectionId).to.be.equal(collectionId);858 expect(result.itemId).to.be.equal(tokenId);859 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));860 expect(result.recipient).to.be.deep.equal(to);861 expect(result.value.toString()).to.be.equal(value.toString());862 if (type === 'NFT') {863 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;864 expect(nftItemData.Owner).to.be.deep.equal(to);865 }866 if (type === 'Fungible') {867 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;868 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());869 }870 if (type === 'ReFungible') {871 const nftItemData =872 (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;873 expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);874 expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());875 }876 });877}878879export async function880transferExpectFailure(881 collectionId: number,882 tokenId: number,883 sender: IKeyringPair,884 recipient: IKeyringPair,885 value: number | bigint = 1,886) {887 await usingApi(async (api: ApiPromise) => {888 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);889 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;890 if (events && Array.isArray(events)) {891 const result = getCreateCollectionResult(events);892 // tslint:disable-next-line:no-unused-expression893 expect(result.success).to.be.false;894 }895 });896}897898export async function899approveExpectFail(900 collectionId: number,901 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,902) {903 await usingApi(async (api: ApiPromise) => {904 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);905 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;906 const result = getCreateCollectionResult(events);907 // tslint:disable-next-line:no-unused-expression908 expect(result.success).to.be.false;909 });910}911912export async function getFungibleBalance(913 collectionId: number,914 owner: string,915) {916 return await usingApi(async (api) => {917 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };918 return BigInt(response.Value);919 });920}921922export async function createFungibleItemExpectSuccess(923 sender: IKeyringPair,924 collectionId: number,925 data: CreateFungibleData,926 owner: CrossAccountId | string = sender.address,927) {928 return await usingApi(async (api) => {929 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });930931 const events = await submitTransactionAsync(sender, tx);932 const result = getCreateItemResult(events);933934 expect(result.success).to.be.true;935 return result.itemId;936 });937}938939export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {940 let newItemId = 0;941 await usingApi(async (api) => {942 const to = normalizeAccountId(owner);943 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);944 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();945 const AItemBalance = new BigNumber(Aitem.Value);946947 let tx;948 if (createMode === 'Fungible') {949 const createData = { fungible: { value: 10 } };950 tx = api.tx.nft.createItem(collectionId, to, createData);951 } else if (createMode === 'ReFungible') {952 const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };953 tx = api.tx.nft.createItem(collectionId, to, createData);954 } else {955 const createData = { nft: { const_data: [], variable_data: [] } };956 tx = api.tx.nft.createItem(collectionId, to, createData);957 }958959 const events = await submitTransactionAsync(sender, tx);960 const result = getCreateItemResult(events);961962 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);963 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();964 const BItemBalance = new BigNumber(Bitem.Value);965966 // What to expect967 // tslint:disable-next-line:no-unused-expression968 expect(result.success).to.be.true;969 if (createMode === 'Fungible') {970 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);971 } else {972 expect(BItemCount).to.be.equal(AItemCount + 1);973 }974 expect(collectionId).to.be.equal(result.collectionId);975 expect(BItemCount.toString()).to.be.equal(result.itemId.toString());976 expect(to).to.be.deep.equal(result.recipient);977 newItemId = result.itemId;978 });979 return newItemId;980}981982export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {983 await usingApi(async (api) => {984 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);985 986 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;987 const result = getCreateItemResult(events);988989 expect(result.success).to.be.false;990 });991}992993export async function setPublicAccessModeExpectSuccess(994 sender: IKeyringPair, collectionId: number,995 accessMode: 'Normal' | 'WhiteList',996) {997 await usingApi(async (api) => {998999 // Run the transaction1000 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1001 const events = await submitTransactionAsync(sender, tx);1002 const result = getGenericResult(events);10031004 // Get the collection1005 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10061007 // What to expect1008 // tslint:disable-next-line:no-unused-expression1009 expect(result.success).to.be.true;1010 expect(collection.Access).to.be.equal(accessMode);1011 });1012}10131014export async function setPublicAccessModeExpectFail(1015 sender: IKeyringPair, collectionId: number,1016 accessMode: 'Normal' | 'WhiteList',1017) {1018 await usingApi(async (api) => {10191020 // Run the transaction1021 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1022 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1023 const result = getGenericResult(events);10241025 // What to expect1026 // tslint:disable-next-line:no-unused-expression1027 expect(result.success).to.be.false;1028 });1029}10301031export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1032 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');1033}10341035export async function enableWhiteListExpectFail(sender: IKeyringPair, collectionId: number) {1036 await setPublicAccessModeExpectFail(sender, collectionId, 'WhiteList');1037}10381039export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1040 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1041}10421043export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1044 await usingApi(async (api) => {10451046 // Run the transaction1047 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1048 const events = await submitTransactionAsync(sender, tx);1049 const result = getGenericResult(events);10501051 // Get the collection1052 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10531054 // What to expect1055 // tslint:disable-next-line:no-unused-expression1056 expect(result.success).to.be.true;1057 expect(collection.MintMode).to.be.equal(enabled);1058 });1059}10601061export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1062 await setMintPermissionExpectSuccess(sender, collectionId, true);1063}10641065export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1066 await usingApi(async (api) => {1067 // Run the transaction1068 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1069 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1070 const result = getCreateCollectionResult(events);1071 // tslint:disable-next-line:no-unused-expression1072 expect(result.success).to.be.false;1073 });1074}10751076export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1077 await usingApi(async (api) => {1078 // Run the transaction1079 const tx = api.tx.nft.setChainLimits(limits);1080 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1081 const result = getCreateCollectionResult(events);1082 // tslint:disable-next-line:no-unused-expression1083 expect(result.success).to.be.false;1084 });1085}10861087export async function isWhitelisted(collectionId: number, address: string) {1088 let whitelisted = false;1089 await usingApi(async (api) => {1090 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1091 });1092 return whitelisted;1093}10941095export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1096 await usingApi(async (api) => {10971098 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();10991100 // Run the transaction1101 const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1102 const events = await submitTransactionAsync(sender, tx);1103 const result = getGenericResult(events);11041105 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();11061107 // What to expect1108 // tslint:disable-next-line:no-unused-expression1109 expect(result.success).to.be.true;1110 // tslint:disable-next-line: no-unused-expression1111 expect(whiteListedBefore).to.be.false;1112 // tslint:disable-next-line: no-unused-expression1113 expect(whiteListedAfter).to.be.true;1114 });1115}11161117export async function addToWhiteListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1118 await usingApi(async (api) => {1119 // Run the transaction1120 const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1121 const events = await expect(submitTransactionAsync(sender, tx)).to.be.rejected;1122 const result = getGenericResult(events);11231124 // What to expect1125 // tslint:disable-next-line:no-unused-expression1126 expect(result.success).to.be.false;1127 });1128}11291130export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1131 await usingApi(async (api) => {1132 // Run the transaction1133 const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1134 const events = await submitTransactionAsync(sender, tx);1135 const result = getGenericResult(events);11361137 // What to expect1138 // tslint:disable-next-line:no-unused-expression1139 expect(result.success).to.be.true;1140 });1141}11421143export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1144 await usingApi(async (api) => {1145 // Run the transaction1146 const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1147 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1148 const result = getGenericResult(events);11491150 // What to expect1151 // tslint:disable-next-line:no-unused-expression1152 expect(result.success).to.be.false;1153 });1154}11551156export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1157 : Promise<ICollectionInterface | null> => {1158 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1159};11601161export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1162 // set global object - collectionsCount1163 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1164};11651166export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1167 return await usingApi(async (api) => {1168 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1169 });1170}1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import { IKeyringPair } from '@polkadot/types/types';9import { evmToAddress } from '@polkadot/util-crypto';10import { BigNumber } from 'bignumber.js';11import BN from 'bn.js';12import chai from 'chai';13import chaiAsPromised from 'chai-as-promised';14import { alicesPublicKey } from '../accounts';15import privateKey from '../substrate/privateKey';16import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';17import { ICollectionInterface } from '../types';18import { hexToStr, strToUTF16, utf16ToStr } from './util';1920chai.use(chaiAsPromised);21const expect = chai.expect;2223export type CrossAccountId = {24 substrate: string,25} | {26 ethereum: string,27};28export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {29 if (typeof input === 'string')30 return { substrate: input };31 if ('address' in input) {32 return { substrate: input.address };33 }34 if ('ethereum' in input) {35 input.ethereum = input.ethereum.toLowerCase();36 return input;37 }38 if ('substrate' in input) {39 return input;40 }4142 // AccountId43 return {substrate: input.toString()};44}45export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {46 input = normalizeAccountId(input);47 if ('substrate' in input) {48 return input.substrate;49 } else {50 return evmToAddress(input.ethereum);51 }52}5354export const U128_MAX = (1n << 128n) - 1n;5556const MICROUNIQUE = 1_000_000_000n;57const MILLIUNIQUE = 1_000n * MICROUNIQUE;58const CENTIUNIQUE = 10n * MILLIUNIQUE;59export const UNIQUE = 100n * CENTIUNIQUE;6061type GenericResult = {62 success: boolean,63};6465interface CreateCollectionResult {66 success: boolean;67 collectionId: number;68}6970interface CreateItemResult {71 success: boolean;72 collectionId: number;73 itemId: number;74 recipient?: CrossAccountId;75}7677interface TransferResult {78 success: boolean;79 collectionId: number;80 itemId: number;81 sender?: CrossAccountId;82 recipient?: CrossAccountId;83 value: bigint;84}8586interface IReFungibleOwner {87 Fraction: BN;88 Owner: number[];89}9091interface ITokenDataType {92 Owner: IKeyringPair;93 ConstData: number[];94 VariableData: number[];95}9697interface IGetMessage {98 checkMsgNftMethod: string;99 checkMsgTrsMethod: string;100 checkMsgSysMethod: string;101}102103export interface IFungibleTokenDataType {104 Value: number;105}106107export interface IChainLimits {108 CollectionNumbersLimit: number;109 AccountTokenOwnershipLimit: number;110 CollectionsAdminsLimit: number;111 CustomDataLimit: number;112 NftSponsorTransferTimeout: number;113 FungibleSponsorTransferTimeout: number;114 RefungibleSponsorTransferTimeout: number;115 OffchainSchemaLimit: number;116 VariableOnChainSchemaLimit: number;117 ConstOnChainSchemaLimit: number;118}119120export interface IReFungibleTokenDataType {121 Owner: IReFungibleOwner[];122 ConstData: number[];123 VariableData: number[];124}125126export function nftEventMessage(events: EventRecord[]): IGetMessage {127 let checkMsgNftMethod = '';128 let checkMsgTrsMethod = '';129 let checkMsgSysMethod = '';130 events.forEach(({ event: { method, section } }) => {131 if (section === 'nft') {132 checkMsgNftMethod = method;133 } else if (section === 'treasury') {134 checkMsgTrsMethod = method;135 } else if (section === 'system') {136 checkMsgSysMethod = method;137 } else { return null; }138 });139 const result: IGetMessage = {140 checkMsgNftMethod,141 checkMsgTrsMethod,142 checkMsgSysMethod,143 };144 return result;145}146147export function getGenericResult(events: EventRecord[]): GenericResult {148 const result: GenericResult = {149 success: false,150 };151 events.forEach(({ event: { method } }) => {152 // console.log(` ${phase}: ${section}.${method}:: ${data}`);153 if (method === 'ExtrinsicSuccess') {154 result.success = true;155 }156 });157 return result;158}159160161162export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {163 let success = false;164 let collectionId = 0;165 events.forEach(({ event: { data, method, section } }) => {166 // console.log(` ${phase}: ${section}.${method}:: ${data}`);167 if (method == 'ExtrinsicSuccess') {168 success = true;169 } else if ((section == 'nft') && (method == 'CollectionCreated')) {170 collectionId = parseInt(data[0].toString());171 }172 });173 const result: CreateCollectionResult = {174 success,175 collectionId,176 };177 return result;178}179180export function getCreateItemResult(events: EventRecord[]): CreateItemResult {181 let success = false;182 let collectionId = 0;183 let itemId = 0;184 let recipient;185 events.forEach(({ event: { data, method, section } }) => {186 // console.log(` ${phase}: ${section}.${method}:: ${data}`);187 if (method == 'ExtrinsicSuccess') {188 success = true;189 } else if ((section == 'nft') && (method == 'ItemCreated')) {190 collectionId = parseInt(data[0].toString());191 itemId = parseInt(data[1].toString());192 recipient = data[2].toJSON();193 }194 });195 const result: CreateItemResult = {196 success,197 collectionId,198 itemId,199 recipient,200 };201 return result;202}203204export function getTransferResult(events: EventRecord[]): TransferResult {205 const result: TransferResult = {206 success: false,207 collectionId: 0,208 itemId: 0,209 value: 0n,210 };211212 events.forEach(({ event: { data, method, section } }) => {213 if (method === 'ExtrinsicSuccess') {214 result.success = true;215 } else if (section === 'nft' && method === 'Transfer') {216 result.collectionId = +data[0].toString();217 result.itemId = +data[1].toString();218 result.sender = data[2].toJSON() as CrossAccountId;219 result.recipient = data[3].toJSON() as CrossAccountId;220 result.value = BigInt(data[4].toString());221 }222 });223224 return result;225}226227interface Invalid {228 type: 'Invalid';229}230231interface Nft {232 type: 'NFT';233}234235interface Fungible {236 type: 'Fungible';237 decimalPoints: number;238}239240interface ReFungible {241 type: 'ReFungible';242}243244type CollectionMode = Nft | Fungible | ReFungible | Invalid;245246export type CreateCollectionParams = {247 mode: CollectionMode,248 name: string,249 description: string,250 tokenPrefix: string,251};252253const defaultCreateCollectionParams: CreateCollectionParams = {254 description: 'description',255 mode: { type: 'NFT' },256 name: 'name',257 tokenPrefix: 'prefix',258};259260export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {261 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };262263 let collectionId = 0;264 await usingApi(async (api) => {265 // Get number of collections before the transaction266 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);267268 // Run the CreateCollection transaction269 const alicePrivateKey = privateKey('//Alice');270271 let modeprm = {};272 if (mode.type === 'NFT') {273 modeprm = { nft: null };274 } else if (mode.type === 'Fungible') {275 modeprm = { fungible: mode.decimalPoints };276 } else if (mode.type === 'ReFungible') {277 modeprm = { refungible: null };278 } else if (mode.type === 'Invalid') {279 modeprm = { invalid: null };280 }281282 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);283 const events = await submitTransactionAsync(alicePrivateKey, tx);284 const result = getCreateCollectionResult(events);285286 // Get number of collections after the transaction287 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);288289 // Get the collection290 const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();291292 // What to expect293 // tslint:disable-next-line:no-unused-expression294 expect(result.success).to.be.true;295 expect(result.collectionId).to.be.equal(BcollectionCount);296 // tslint:disable-next-line:no-unused-expression297 expect(collection).to.be.not.null;298 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');299 expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));300 expect(utf16ToStr(collection.Name)).to.be.equal(name);301 expect(utf16ToStr(collection.Description)).to.be.equal(description);302 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);303304 collectionId = result.collectionId;305 });306307 return collectionId;308}309310export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {311 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };312313 let modeprm = {};314 if (mode.type === 'NFT') {315 modeprm = { nft: null };316 } else if (mode.type === 'Fungible') {317 modeprm = { fungible: mode.decimalPoints };318 } else if (mode.type === 'ReFungible') {319 modeprm = { refungible: null };320 } else if (mode.type === 'Invalid') {321 modeprm = { invalid: null };322 }323324 await usingApi(async (api) => {325 // Get number of collections before the transaction326 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());327328 // Run the CreateCollection transaction329 const alicePrivateKey = privateKey('//Alice');330 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);331 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;332 const result = getCreateCollectionResult(events);333334 // Get number of collections after the transaction335 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());336337 // What to expect338 // tslint:disable-next-line:no-unused-expression339 expect(result.success).to.be.false;340 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');341 });342}343344export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {345 let bal = new BigNumber(0);346 let unused;347 do {348 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;349 const keyring = new Keyring({ type: 'sr25519' });350 unused = keyring.addFromUri(`//${randomSeed}`);351 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());352 } while (bal.toFixed() != '0');353 return unused;354}355356export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {357 return await usingApi(async (api) => {358 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;359 return BigInt(bn.toString());360 });361}362363export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {364 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));365}366367export async function findNotExistingCollection(api: ApiPromise): Promise<number> {368 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;369 const newCollection: number = totalNumber + 1;370 return newCollection;371}372373function getDestroyResult(events: EventRecord[]): boolean {374 let success = false;375 events.forEach(({ event: { method } }) => {376 if (method == 'ExtrinsicSuccess') {377 success = true;378 }379 });380 return success;381}382383export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {384 await usingApi(async (api) => {385 // Run the DestroyCollection transaction386 const alicePrivateKey = privateKey(senderSeed);387 const tx = api.tx.nft.destroyCollection(collectionId);388 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;389 });390}391392export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {393 await usingApi(async (api) => {394 // Run the DestroyCollection transaction395 const alicePrivateKey = privateKey(senderSeed);396 const tx = api.tx.nft.destroyCollection(collectionId);397 const events = await submitTransactionAsync(alicePrivateKey, tx);398 const result = getDestroyResult(events);399400 // Get the collection401 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();402403 // What to expect404 expect(result).to.be.true;405 expect(collection).to.be.null;406 });407}408409export async function queryCollectionLimits(collectionId: number) {410 return await usingApi(async (api) => {411 return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;412 });413}414415export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {416 await usingApi(async (api) => {417 const oldLimits = await queryCollectionLimits(collectionId);418 const newLimits = { ...oldLimits as any, ...limits };419 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);420 const events = await submitTransactionAsync(sender, tx);421 const result = getGenericResult(events);422423 expect(result.success).to.be.true;424 });425}426427export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {428 await usingApi(async (api) => {429 const oldLimits = await queryCollectionLimits(collectionId);430 const newLimits = { ...oldLimits as any, ...limits };431 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);432 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;433 const result = getGenericResult(events);434435 expect(result.success).to.be.false;436 });437}438439export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {440 await usingApi(async (api) => {441442 // Run the transaction443 const senderPrivateKey = privateKey(sender);444 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);445 const events = await submitTransactionAsync(senderPrivateKey, tx);446 const result = getGenericResult(events);447448 // Get the collection449 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();450451 // What to expect452 expect(result.success).to.be.true;453 expect(collection.Sponsorship).to.deep.equal({454 unconfirmed: sponsor,455 });456 });457}458459export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {460 await usingApi(async (api) => {461462 // Run the transaction463 const alicePrivateKey = privateKey(sender);464 const tx = api.tx.nft.removeCollectionSponsor(collectionId);465 const events = await submitTransactionAsync(alicePrivateKey, tx);466 const result = getGenericResult(events);467468 // Get the collection469 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();470471 // What to expect472 expect(result.success).to.be.true;473 expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });474 });475}476477export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {478 await usingApi(async (api) => {479480 // Run the transaction481 const alicePrivateKey = privateKey(senderSeed);482 const tx = api.tx.nft.removeCollectionSponsor(collectionId);483 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;484 });485}486487export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {488 await usingApi(async (api) => {489490 // Run the transaction491 const alicePrivateKey = privateKey(senderSeed);492 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);493 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;494 });495}496497export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {498 await usingApi(async (api) => {499500 // Run the transaction501 const sender = privateKey(senderSeed);502 const tx = api.tx.nft.confirmSponsorship(collectionId);503 const events = await submitTransactionAsync(sender, tx);504 const result = getGenericResult(events);505506 // Get the collection507 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();508509 // What to expect510 expect(result.success).to.be.true;511 expect(collection.Sponsorship).to.be.deep.equal({512 confirmed: sender.address,513 });514 });515}516517518export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {519 await usingApi(async (api) => {520521 // Run the transaction522 const sender = privateKey(senderSeed);523 const tx = api.tx.nft.confirmSponsorship(collectionId);524 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;525 });526}527528export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {529 await usingApi(async (api) => {530 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);531 const events = await submitTransactionAsync(sender, tx);532 const result = getGenericResult(events);533534 expect(result.success).to.be.true;535 });536}537538export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {539 await usingApi(async (api) => {540 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);541 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;542 const result = getGenericResult(events);543544 expect(result.success).to.be.false;545 });546}547548export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {549550 await usingApi(async (api) => {551552 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);553 const events = await submitTransactionAsync(sender, tx);554 const result = getGenericResult(events);555556 expect(result.success).to.be.true;557 }); 558}559560export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {561562 await usingApi(async (api) => {563564 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);565 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;566 const result = getGenericResult(events);567568 expect(result.success).to.be.false;569 }); 570}571572export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {573 await usingApi(async (api) => {574 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);575 const events = await submitTransactionAsync(sender, tx);576 const result = getGenericResult(events);577578 expect(result.success).to.be.true;579 });580}581582export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {583 await usingApi(async (api) => {584 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);585 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;586 const result = getGenericResult(events);587588 expect(result.success).to.be.false;589 });590}591592export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {593 await usingApi(async (api) => {594 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);595 const events = await submitTransactionAsync(sender, tx);596 const result = getGenericResult(events);597598 expect(result.success).to.be.true;599 });600}601602export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {603 let whitelisted = false;604 await usingApi(async (api) => {605 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;606 });607 return whitelisted;608}609610export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {611 await usingApi(async (api) => {612 const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());613 const events = await submitTransactionAsync(sender, tx);614 const result = getGenericResult(events);615616 expect(result.success).to.be.true;617 });618}619620export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {621 await usingApi(async (api) => {622 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());623 const events = await submitTransactionAsync(sender, tx);624 const result = getGenericResult(events);625626 expect(result.success).to.be.true;627 });628}629630export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {631 await usingApi(async (api) => {632 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());633 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;634 const result = getGenericResult(events);635636 expect(result.success).to.be.false;637 });638}639640export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {641 await usingApi(async (api) => {642 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));643 const events = await submitTransactionAsync(sender, tx);644 const result = getGenericResult(events);645646 expect(result.success).to.be.true;647 });648}649650export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {651 await usingApi(async (api) => {652 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));653 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;654 });655}656657export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {658 await usingApi(async (api) => {659 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));660 const events = await submitTransactionAsync(sender, tx);661 const result = getGenericResult(events);662663 expect(result.success).to.be.true;664 });665}666667export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {668 await usingApi(async (api) => {669 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));670 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;671 });672}673674export interface CreateFungibleData {675 readonly Value: bigint;676}677678export interface CreateReFungibleData { }679export interface CreateNftData { }680681export type CreateItemData = {682 NFT: CreateNftData;683} | {684 Fungible: CreateFungibleData;685} | {686 ReFungible: CreateReFungibleData;687};688689export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {690 await usingApi(async (api) => {691 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);692 const events = await submitTransactionAsync(owner, tx);693 const result = getGenericResult(events);694 // Get the item695 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();696 // What to expect697 // tslint:disable-next-line:no-unused-expression698 expect(result.success).to.be.true;699 // tslint:disable-next-line:no-unused-expression700 expect(item).to.be.null;701 });702}703704export async function705approveExpectSuccess(706 collectionId: number,707 tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1,708) {709 await usingApi(async (api: ApiPromise) => {710 approved = normalizeAccountId(approved);711 const allowanceBefore =712 await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;713 const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);714 const events = await submitTransactionAsync(owner, approveNftTx);715 const result = getCreateItemResult(events);716 // tslint:disable-next-line:no-unused-expression717 expect(result.success).to.be.true;718 const allowanceAfter =719 await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;720 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());721 });722}723724export async function725transferFromExpectSuccess(726 collectionId: number,727 tokenId: number,728 accountApproved: IKeyringPair,729 accountFrom: IKeyringPair | CrossAccountId,730 accountTo: IKeyringPair | CrossAccountId,731 value: number | bigint = 1,732 type = 'NFT',733) {734 await usingApi(async (api: ApiPromise) => {735 const to = normalizeAccountId(accountTo);736 let balanceBefore = new BN(0);737 if (type === 'Fungible') {738 balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;739 }740 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);741 const events = await submitTransactionAsync(accountApproved, transferFromTx);742 const result = getCreateItemResult(events);743 // tslint:disable-next-line:no-unused-expression744 expect(result.success).to.be.true;745 if (type === 'NFT') {746 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;747 expect(nftItemData.Owner).to.be.deep.equal(to);748 }749 if (type === 'Fungible') {750 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;751 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());752 }753 if (type === 'ReFungible') {754 const nftItemData =755 (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;756 expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));757 expect(nftItemData.Owner[0].Fraction).to.be.equal(value);758 }759 });760}761762export async function763transferFromExpectFail(764 collectionId: number,765 tokenId: number,766 accountApproved: IKeyringPair,767 accountFrom: IKeyringPair,768 accountTo: IKeyringPair,769 value: number | bigint = 1,770) {771 await usingApi(async (api: ApiPromise) => {772 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);773 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;774 const result = getCreateCollectionResult(events);775 // tslint:disable-next-line:no-unused-expression776 expect(result.success).to.be.false;777 });778}779780/* eslint no-async-promise-executor: "off" */781async function getBlockNumber(api: ApiPromise): Promise<number> {782 return new Promise<number>(async (resolve) => {783 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {784 unsubscribe();785 resolve(head.number.toNumber());786 });787 });788}789790export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: IKeyringPair) {791 await usingApi(async (api) => {792 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(address.address));793 const events = await submitTransactionAsync(sender, changeAdminTx);794 const result = getCreateCollectionResult(events);795 expect(result.success).to.be.true;796 });797}798799export async function800scheduleTransferExpectSuccess(801 collectionId: number,802 tokenId: number,803 sender: IKeyringPair,804 recipient: IKeyringPair,805 value: number | bigint = 1,806 blockTimeMs: number,807 blockSchedule: number,808) {809 await usingApi(async (api: ApiPromise) => {810 const blockNumber: number | undefined = await getBlockNumber(api);811 const expectedBlockNumber = blockNumber + blockSchedule;812813 expect(blockNumber).to.be.greaterThan(0);814 const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value); 815 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);816817 await submitTransactionAsync(sender, scheduleTx);818819 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());820821 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as any as ITokenDataType;822 expect(toSubstrateAddress(nftItemDataBefore.Owner)).to.be.equal(sender.address);823824 // sleep for 4 blocks825 await new Promise(resolve => setTimeout(resolve, blockTimeMs * (blockSchedule + 1)));826827 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());828829 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;830 expect(toSubstrateAddress(nftItemData.Owner)).to.be.equal(recipient.address);831 expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());832 });833}834835836export async function837transferExpectSuccess(838 collectionId: number,839 tokenId: number,840 sender: IKeyringPair,841 recipient: IKeyringPair | CrossAccountId,842 value: number | bigint = 1,843 type = 'NFT',844) {845 await usingApi(async (api: ApiPromise) => {846 const to = normalizeAccountId(recipient);847848 let balanceBefore = new BN(0);849 if (type === 'Fungible') {850 balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;851 }852 const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);853 const events = await submitTransactionAsync(sender, transferTx);854 const result = getTransferResult(events);855 // tslint:disable-next-line:no-unused-expression856 expect(result.success).to.be.true;857 expect(result.collectionId).to.be.equal(collectionId);858 expect(result.itemId).to.be.equal(tokenId);859 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));860 expect(result.recipient).to.be.deep.equal(to);861 expect(result.value.toString()).to.be.equal(value.toString());862 if (type === 'NFT') {863 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;864 expect(nftItemData.Owner).to.be.deep.equal(to);865 }866 if (type === 'Fungible') {867 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;868 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());869 }870 if (type === 'ReFungible') {871 const nftItemData =872 (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;873 expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);874 expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());875 }876 });877}878879export async function880transferExpectFailure(881 collectionId: number,882 tokenId: number,883 sender: IKeyringPair,884 recipient: IKeyringPair,885 value: number | bigint = 1,886) {887 await usingApi(async (api: ApiPromise) => {888 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);889 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;890 if (events && Array.isArray(events)) {891 const result = getCreateCollectionResult(events);892 // tslint:disable-next-line:no-unused-expression893 expect(result.success).to.be.false;894 }895 });896}897898export async function899approveExpectFail(900 collectionId: number,901 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,902) {903 await usingApi(async (api: ApiPromise) => {904 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);905 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;906 const result = getCreateCollectionResult(events);907 // tslint:disable-next-line:no-unused-expression908 expect(result.success).to.be.false;909 });910}911912export async function getFungibleBalance(913 collectionId: number,914 owner: string,915) {916 return await usingApi(async (api) => {917 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };918 return BigInt(response.Value);919 });920}921922export async function createFungibleItemExpectSuccess(923 sender: IKeyringPair,924 collectionId: number,925 data: CreateFungibleData,926 owner: CrossAccountId | string = sender.address,927) {928 return await usingApi(async (api) => {929 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });930931 const events = await submitTransactionAsync(sender, tx);932 const result = getCreateItemResult(events);933934 expect(result.success).to.be.true;935 return result.itemId;936 });937}938939export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {940 let newItemId = 0;941 await usingApi(async (api) => {942 const to = normalizeAccountId(owner);943 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);944 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();945 const AItemBalance = new BigNumber(Aitem.Value);946947 let tx;948 if (createMode === 'Fungible') {949 const createData = { fungible: { value: 10 } };950 tx = api.tx.nft.createItem(collectionId, to, createData);951 } else if (createMode === 'ReFungible') {952 const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };953 tx = api.tx.nft.createItem(collectionId, to, createData);954 } else {955 const createData = { nft: { const_data: [], variable_data: [] } };956 tx = api.tx.nft.createItem(collectionId, to, createData);957 }958959 const events = await submitTransactionAsync(sender, tx);960 const result = getCreateItemResult(events);961962 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);963 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();964 const BItemBalance = new BigNumber(Bitem.Value);965966 // What to expect967 // tslint:disable-next-line:no-unused-expression968 expect(result.success).to.be.true;969 if (createMode === 'Fungible') {970 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);971 } else {972 expect(BItemCount).to.be.equal(AItemCount + 1);973 }974 expect(collectionId).to.be.equal(result.collectionId);975 expect(BItemCount.toString()).to.be.equal(result.itemId.toString());976 expect(to).to.be.deep.equal(result.recipient);977 newItemId = result.itemId;978 });979 return newItemId;980}981982export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {983 await usingApi(async (api) => {984 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);985 986 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;987 const result = getCreateItemResult(events);988989 expect(result.success).to.be.false;990 });991}992993export async function setPublicAccessModeExpectSuccess(994 sender: IKeyringPair, collectionId: number,995 accessMode: 'Normal' | 'WhiteList',996) {997 await usingApi(async (api) => {998999 // Run the transaction1000 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1001 const events = await submitTransactionAsync(sender, tx);1002 const result = getGenericResult(events);10031004 // Get the collection1005 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10061007 // What to expect1008 // tslint:disable-next-line:no-unused-expression1009 expect(result.success).to.be.true;1010 expect(collection.Access).to.be.equal(accessMode);1011 });1012}10131014export async function setPublicAccessModeExpectFail(1015 sender: IKeyringPair, collectionId: number,1016 accessMode: 'Normal' | 'WhiteList',1017) {1018 await usingApi(async (api) => {10191020 // Run the transaction1021 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1022 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1023 const result = getGenericResult(events);10241025 // What to expect1026 // tslint:disable-next-line:no-unused-expression1027 expect(result.success).to.be.false;1028 });1029}10301031export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1032 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');1033}10341035export async function enableWhiteListExpectFail(sender: IKeyringPair, collectionId: number) {1036 await setPublicAccessModeExpectFail(sender, collectionId, 'WhiteList');1037}10381039export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1040 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1041}10421043export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1044 await usingApi(async (api) => {10451046 // Run the transaction1047 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1048 const events = await submitTransactionAsync(sender, tx);1049 const result = getGenericResult(events);10501051 // Get the collection1052 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10531054 // What to expect1055 // tslint:disable-next-line:no-unused-expression1056 expect(result.success).to.be.true;1057 expect(collection.MintMode).to.be.equal(enabled);1058 });1059}10601061export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1062 await setMintPermissionExpectSuccess(sender, collectionId, true);1063}10641065export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1066 await usingApi(async (api) => {1067 // Run the transaction1068 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1069 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1070 const result = getCreateCollectionResult(events);1071 // tslint:disable-next-line:no-unused-expression1072 expect(result.success).to.be.false;1073 });1074}10751076export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1077 await usingApi(async (api) => {1078 // Run the transaction1079 const tx = api.tx.nft.setChainLimits(limits);1080 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1081 const result = getCreateCollectionResult(events);1082 // tslint:disable-next-line:no-unused-expression1083 expect(result.success).to.be.false;1084 });1085}10861087export async function isWhitelisted(collectionId: number, address: string) {1088 let whitelisted = false;1089 await usingApi(async (api) => {1090 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1091 });1092 return whitelisted;1093}10941095export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1096 await usingApi(async (api) => {10971098 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();10991100 // Run the transaction1101 const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1102 const events = await submitTransactionAsync(sender, tx);1103 const result = getGenericResult(events);11041105 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();11061107 // What to expect1108 // tslint:disable-next-line:no-unused-expression1109 expect(result.success).to.be.true;1110 // tslint:disable-next-line: no-unused-expression1111 expect(whiteListedBefore).to.be.false;1112 // tslint:disable-next-line: no-unused-expression1113 expect(whiteListedAfter).to.be.true;1114 });1115}11161117export async function addToWhiteListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1118 await usingApi(async (api) => {1119 // Run the transaction1120 const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1121 const events = await expect(submitTransactionAsync(sender, tx)).to.be.rejected;1122 const result = getGenericResult(events);11231124 // What to expect1125 // tslint:disable-next-line:no-unused-expression1126 expect(result.success).to.be.false;1127 });1128}11291130export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1131 await usingApi(async (api) => {1132 // Run the transaction1133 const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1134 const events = await submitTransactionAsync(sender, tx);1135 const result = getGenericResult(events);11361137 // What to expect1138 // tslint:disable-next-line:no-unused-expression1139 expect(result.success).to.be.true;1140 });1141}11421143export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1144 await usingApi(async (api) => {1145 // Run the transaction1146 const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1147 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1148 const result = getGenericResult(events);11491150 // What to expect1151 // tslint:disable-next-line:no-unused-expression1152 expect(result.success).to.be.false;1153 });1154}11551156export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1157 : Promise<ICollectionInterface | null> => {1158 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1159};11601161export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1162 // set global object - collectionsCount1163 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1164};11651166export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1167 return await usingApi(async (api) => {1168 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1169 });1170}11711172export async function queryNftOwner(api: ApiPromise, collectionId: number, tokenId: number): Promise<CrossAccountId> {1173 return normalizeAccountId((await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON().Owner);1174}