git.delta.rocks / unique-network / refs/commits / 4cad1ac2d3ff

difftreelog

test marketplace matcher contract

Yaroslav Bolyukin2021-08-26parent: #f911002.patch.diff
in: master

9 files changed

addedtests/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
addedtests/src/eth/marketplace/MarketPlaceKSM.bindiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/marketplace/MarketPlaceKSM.bin
@@ -0,0 +1 @@
+608060405234801561001057600080fd5b50604051610e27380380610e2783398101604081905261002f9161005d565b600480546001600160a01b039092166001600160a01b0319928316179055600580549091163317905561008d565b60006020828403121561006f57600080fd5b81516001600160a01b038116811461008657600080fd5b9392505050565b610d8b8061009c6000396000f3fe608060405234801561001057600080fd5b50600436106100a95760003560e01c806399f2d4eb1161007157806399f2d4eb1461018e5780639df55f52146101a1578063c10c35461461010f578063cce7ec13146101b4578063db87db52146101c7578063e22d4f7d146101fa57600080fd5b80630ad58d2f146100ae57806310a5ff17146100d6578063592bd7051461010f5780638a72ea6a146101245780638dbdbe6d1461017b575b600080fd5b6100c16100bc366004610c4d565b610225565b60405190151581526020015b60405180910390f35b6101016100e4366004610bd8565b600160209081526000928352604080842090915290825290205481565b6040519081526020016100cd565b61012261011d366004610b97565b6102d8565b005b610137610132366004610c04565b610345565b6040805197885260208801969096529486019390935260608501919091526001600160a01b0390811660808501521660a083015260ff1660c082015260e0016100cd565b610122610189366004610c4d565b6103a4565b61010161019c366004610bd8565b610449565b6101226101af366004610c86565b61047a565b6101226101c2366004610bd8565b610984565b6101016101d5366004610c1d565b6001600160a01b03166000908152600160209081526040808320938352929052205490565b610101610208366004610bd8565b600260209081526000928352604080842090915290825290205481565b6004546000906001600160a01b031633146102795760405162461bcd60e51b815260206004820152600f60248201526e27b7363c9032b9b1b937bb9031b0b760891b60448201526064015b60405180910390fd5b6001600160a01b03821660009081526001602090815260408083208684529091529020546102a8908590610cfa565b6001600160a01b039290921660009081526001602081815260408084209684529590529390209190915550919050565b6005546001600160a01b031633146103235760405162461bcd60e51b815260206004820152600e60248201526d27b7363c9037bbb732b91031b0b760911b6044820152606401610270565b600480546001600160a01b0319166001600160a01b0392909216919091179055565b6000818154811061035557600080fd5b6000918252602090912060069091020180546001820154600283015460038401546004850154600590950154939550919390926001600160a01b0391821691811690600160a01b900460ff1687565b6004546001600160a01b031633146103f05760405162461bcd60e51b815260206004820152600f60248201526e27b7363c9032b9b1b937bb9031b0b760891b6044820152606401610270565b6001600160a01b038116600090815260016020908152604080832085845290915290205461041f908490610ce2565b6001600160a01b039091166000908152600160209081526040808320948352939052919091205550565b6003602052816000526040600020818154811061046557600080fd5b90600052602060002001600091509150505481565b6040516331a9108f60e11b81526004810183905233906001600160a01b03851690636352211e9060240160206040518083038186803b1580156104bc57600080fd5b505afa1580156104d0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104f49190610bbb565b6001600160a01b0316146105425760405162461bcd60e51b81526020600482015260156024820152742737ba103934b3b43a103a37b5b2b71037bbb732b960591b6044820152606401610270565b6001600160a01b0383166000908152600260209081526040808320858452909152812054905415806105ac575060006001600160a01b03166000828154811061058d5761058d610d27565b60009182526020909120600460069092020101546001600160a01b0316145b15610793576040805160e0810182528481526020810187815291810188815242606083019081526001600160a01b03808916608085019081523360a0860190815260ff808a1660c088019081526000805460018181018355828052995160069091027f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56381019190915599517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5648b015596517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5658a015594517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56689015591517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e567880180549185166001600160a01b0319909216919091179055517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56890960180549351909116600160a01b026001600160a81b031990931695909116949094171790925590546107399190610cfa565b6001600160a01b038516600090815260026020908152604080832087845282528083209390935533825260039052908120905461077890600190610cfa565b81546001810183556000928352602090922090910155610916565b6040805160e0810182526001600160a01b03861660009081526002602090815283822087835290529182205482549192839290919081106107d6576107d6610d27565b60009182526020808320600690920290910154835282810189905260408084018b90524260608501526001600160a01b0389168352600282528083208884529091528120548154608090930192811061083157610831610d27565b60009182526020808320600460069093020191909101546001600160a01b039081168452338483015260ff871660409485015288168252600281528282208783529052908120548154811061088857610888610d27565b60009182526020918290208351600690920201908155908201516001820155604082015160028201556060820151600382015560808201516004820180546001600160a01b039283166001600160a01b031990911617905560a08301516005909201805460c09094015160ff16600160a01b026001600160a81b031990941692909116919091179190911790555b6040516323b872dd60e01b8152336004820152306024820152604481018490526001600160a01b038516906323b872dd90606401600060405180830381600087803b15801561096457600080fd5b505af1158015610978573d6000803e3d6000fd5b50505050505050505050565b6001600160a01b0382166000908152600260209081526040808320848452909152812054815482919081106109bb576109bb610d27565b600091825260208083206040805160e0810182526006949094029091018054845260018082015485850190815260028301548685018190526003840154606088015260048401546001600160a01b03908116608089015260059094015493841660a0880152600160a01b90930460ff1660c08701523387529084528286209051865290925290922054909250610a519190610cfa565b33600090815260016020818152604080842086830180518652908352818520959095558581015160a08701516001600160a01b031685529282528084209451845293905291902054610aa39190610ce2565b60a08201516001600160a01b0390811660009081526001602090815260408083208287015184528252808320949094559186168152600282528281208582529091529081205481548291908110610afc57610afc610d27565b60009182526020909120600560069092020101805460ff92909216600160a01b0260ff60a01b199092169190911790556040516323b872dd60e01b8152306004820152336024820152604481018390526001600160a01b038416906323b872dd90606401600060405180830381600087803b158015610b7a57600080fd5b505af1158015610b8e573d6000803e3d6000fd5b50505050505050565b600060208284031215610ba957600080fd5b8135610bb481610d3d565b9392505050565b600060208284031215610bcd57600080fd5b8151610bb481610d3d565b60008060408385031215610beb57600080fd5b8235610bf681610d3d565b946020939093013593505050565b600060208284031215610c1657600080fd5b5035919050565b60008060408385031215610c3057600080fd5b823591506020830135610c4281610d3d565b809150509250929050565b600080600060608486031215610c6257600080fd5b83359250602084013591506040840135610c7b81610d3d565b809150509250925092565b600080600080600060a08688031215610c9e57600080fd5b85359450602086013593506040860135610cb781610d3d565b925060608601359150608086013560ff81168114610cd457600080fd5b809150509295509295909350565b60008219821115610cf557610cf5610d11565b500190565b600082821015610d0c57610d0c610d11565b500390565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b6001600160a01b0381168114610d5257600080fd5b5056fea2646970667358221220d098ae4e0cc7bdbb7de1061c03402a667836f903122c1c606ca2c65db1ab78e964736f6c63430008070033
\ No newline at end of file
addedtests/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];
+    }
+}
addedtests/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
addedtests/src/eth/marketplace/MarketPlaceUNQ.bindiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/marketplace/MarketPlaceUNQ.bin
@@ -0,0 +1 @@
+608060405234801561001057600080fd5b50600380546001600160a01b03191633179055610f9a806100326000396000f3fe6080604052600436106100705760003560e01c806399f2d4eb1161004e57806399f2d4eb14610120578063b3ffb7601461014e578063cce7ec1314610161578063e22d4f7d1461017457600080fd5b8063592bd705146100755780637b1d6001146100975780638a72ea6a146100b7575b600080fd5b34801561008157600080fd5b50610095610090366004610d98565b6101ac565b005b3480156100a357600080fd5b506100956100b2366004610e88565b61021e565b3480156100c357600080fd5b506100d76100d2366004610e6f565b6107aa565b604080519788526001600160a01b03968716602089015287019490945260608601929092528316608085015290911660a083015260ff1660c082015260e0015b60405180910390f35b34801561012c57600080fd5b5061014061013b366004610dd9565b61080d565b604051908152602001610117565b61009561015c366004610e05565b61083e565b61009561016f366004610dd9565b610b78565b34801561018057600080fd5b5061014061018f366004610dd9565b600160209081526000928352604080842090915290825290205481565b6003546001600160a01b031633146101fc5760405162461bcd60e51b815260206004820152600e60248201526d27b7363c9037bbb732b91031b0b760911b60448201526064015b60405180910390fd5b600380546001600160a01b0319166001600160a01b0392909216919091179055565b6040516317a87dfd60e11b815260206004820152600360248201526261736b60e81b60448201526001600160a01b03841690632f50fbfa90606401600060405180830381600087803b15801561027357600080fd5b505af1158015610287573d6000803e3d6000fd5b50506040516331a9108f60e11b8152600481018590523392506001600160a01b0386169150636352211e9060240160206040518083038186803b1580156102cd57600080fd5b505afa1580156102e1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103059190610dbc565b6001600160a01b0316146103535760405162461bcd60e51b81526020600482015260156024820152742737ba103934b3b43a103a37b5b2b71037bbb732b960591b60448201526064016101f3565b6001600160a01b0383166000908152600160209081526040808320858452909152812054905415806103bd575060006001600160a01b03166000828154811061039e5761039e610f36565b60009182526020909120600460069092020101546001600160a01b0316145b156105af576040805160e0810182528481526001600160a01b03878116602083019081529282018981524260608401908152888316608085019081523360a0860190815260ff89811660c08801908152600080546001808201835582805299517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56360069092029182015599517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5648b0180546001600160a01b0319908116928b1692909217905596517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5658b015594517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5668a015592517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5678901805490961690871617909455517f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56890960180549151969094166001600160a81b031990911617600160a01b959092169490940217905590546105569190610f11565b6001600160a01b0385166000908152600160208181526040808420888552825280842094909455338352600290529181209054909161059491610f11565b81546001810183556000928352602090922090910155610740565b6040805160e0810182526001600160a01b03861660009081526001602090815283822087835290529182205482549192839290919081106105f2576105f2610f36565b6000918252602080832060069092029091015483526001600160a01b03808a168483015260408085018c90524260608601529089168352600182528083208884529091528120548154608090930192811061064f5761064f610f36565b60009182526020808320600460069093020191909101546001600160a01b039081168452338483015260ff87166040948501528816825260018152828220878352905290812054815481106106a6576106a6610f36565b60009182526020918290208351600690920201908155908201516001820180546001600160a01b039283166001600160a01b031991821617909155604084015160028401556060840151600384015560808401516004840180549184169190921617905560a08301516005909201805460c09094015160ff16600160a01b026001600160a81b031990941692909116919091179190911790555b6040516323b872dd60e01b81526001600160a01b038516906323b872dd9061077090339030908890600401610eed565b600060405180830381600087803b15801561078a57600080fd5b505af115801561079e573d6000803e3d6000fd5b50505050505050505050565b600081815481106107ba57600080fd5b60009182526020909120600690910201805460018201546002830154600384015460048501546005909501549395506001600160a01b03928316949193909291821691811690600160a01b900460ff1687565b6002602052816000526040600020818154811061082957600080fd5b90600052602060002001600091509150505481565b6001600160a01b03841660009081526001602090815260408083208684529091528120548154829190811061087557610875610f36565b60009182526020918290206040805160e0810182526006939093029091018054835260018101546001600160a01b03908116948401949094526002810154918301829052600381015460608401526004810154841660808401526005015492831660a0830152600160a01b90920460ff1660c08201529150821480156109105750826001600160a01b031681602001516001600160a01b0316145b6109915760405162461bcd60e51b815260206004820152604660248201527f4e6f7420726967687420616d6f756e74206f722063757272656e63792073656e60448201527f742c206861766520746f20626520657175616c2063757272656e637920616e6460648201526520707269636560d01b608482015260a4016101f3565b80602001516001600160a01b03166323b872dd333084604001516040518463ffffffff1660e01b81526004016109c993929190610eed565b602060405180830381600087803b1580156109e357600080fd5b505af11580156109f7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a1b9190610e4d565b50602081015160a0820151604080840151905163a9059cbb60e01b81526001600160a01b039283166004820152602481019190915291169063a9059cbb90604401602060405180830381600087803b158015610a7657600080fd5b505af1158015610a8a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aae9190610e4d565b506001600160a01b038516600090815260016020908152604080832087845290915281205481548291908110610ae657610ae6610f36565b906000526020600020906006020160050160146101000a81548160ff021916908360ff160217905550846001600160a01b03166323b872dd3033876040518463ffffffff1660e01b8152600401610b3f93929190610eed565b600060405180830381600087803b158015610b5957600080fd5b505af1158015610b6d573d6000803e3d6000fd5b505050505050505050565b6001600160a01b038216600090815260016020908152604080832084845290915281205481548291908110610baf57610baf610f36565b60009182526020918290206040805160e0810182526006939093029091018054835260018101546001600160a01b03908116948401949094526002810154918301829052600381015460608401526004810154841660808401526005015492831660a0830152600160a01b90920460ff1660c082015291503414610c8f5760405162461bcd60e51b815260206004820152603160248201527f4e6f7420726967687420616d6f756e7420554e512073656e742c206861766520604482015270746f20626520657175616c20707269636560781b60648201526084016101f3565b8060a001516001600160a01b03166108fc82604001519081150290604051600060405180830381858888f19350505050158015610cd0573d6000803e3d6000fd5b506001600160a01b038316600090815260016020908152604080832085845290915281205481548291908110610d0857610d08610f36565b906000526020600020906006020160050160146101000a81548160ff021916908360ff160217905550826001600160a01b03166323b872dd3033856040518463ffffffff1660e01b8152600401610d6193929190610eed565b600060405180830381600087803b158015610d7b57600080fd5b505af1158015610d8f573d6000803e3d6000fd5b50505050505050565b600060208284031215610daa57600080fd5b8135610db581610f4c565b9392505050565b600060208284031215610dce57600080fd5b8151610db581610f4c565b60008060408385031215610dec57600080fd5b8235610df781610f4c565b946020939093013593505050565b60008060008060808587031215610e1b57600080fd5b8435610e2681610f4c565b9350602085013592506040850135610e3d81610f4c565b9396929550929360600135925050565b600060208284031215610e5f57600080fd5b81518015158114610db557600080fd5b600060208284031215610e8157600080fd5b5035919050565b600080600080600060a08688031215610ea057600080fd5b853594506020860135610eb281610f4c565b93506040860135610ec281610f4c565b925060608601359150608086013560ff81168114610edf57600080fd5b809150509295509295909350565b6001600160a01b039384168152919092166020820152604081019190915260600190565b600082821015610f3157634e487b7160e01b600052601160045260246000fd5b500390565b634e487b7160e01b600052603260045260246000fd5b6001600160a01b0381168114610f6157600080fd5b5056fea2646970667358221220f1d3a989bed0f05028785628ff58624c8d96c5eba3ecf0b15a41660023e3eadf64736f6c63430008070033
\ No newline at end of file
addedtests/src/eth/marketplace/MarketPlaceUNQ.soldiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/marketplace/MarketPlaceUNQ.sol
@@ -0,0 +1,164 @@
+// 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 {
+        IERC721(_idCollection).debug("ask");
+        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);
+    }
+}
addedtests/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 });
+  });
+});
modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -141,10 +141,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) {
@@ -221,4 +224,18 @@
 
 export function contractHelpers(web3: Web3, caller: string) {
   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;
 }
\ No newline at end of file
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
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;5556type GenericResult = {57  success: boolean,58};5960interface CreateCollectionResult {61  success: boolean;62  collectionId: number;63}6465interface CreateItemResult {66  success: boolean;67  collectionId: number;68  itemId: number;69  recipient?: CrossAccountId;70}7172interface TransferResult {73  success: boolean;74  collectionId: number;75  itemId: number;76  sender?: CrossAccountId;77  recipient?: CrossAccountId;78  value: bigint;79}8081interface IReFungibleOwner {82  Fraction: BN;83  Owner: number[];84}8586interface ITokenDataType {87  Owner: IKeyringPair;88  ConstData: number[];89  VariableData: number[];90}9192interface IGetMessage {93  checkMsgNftMethod: string;94  checkMsgTrsMethod: string;95  checkMsgSysMethod: string;96}9798export interface IFungibleTokenDataType {99  Value: number;100}101102export interface IChainLimits {103  CollectionNumbersLimit: number;104	AccountTokenOwnershipLimit: number;105	CollectionsAdminsLimit: number;106	CustomDataLimit: number;107	NftSponsorTransferTimeout: number;108	FungibleSponsorTransferTimeout: number;109	RefungibleSponsorTransferTimeout: number;110	OffchainSchemaLimit: number;111	VariableOnChainSchemaLimit: number;112	ConstOnChainSchemaLimit: number;113}114115export interface IReFungibleTokenDataType {116  Owner: IReFungibleOwner[];117  ConstData: number[];118  VariableData: number[];119}120121export function nftEventMessage(events: EventRecord[]): IGetMessage {122  let checkMsgNftMethod = '';123  let checkMsgTrsMethod = '';124  let checkMsgSysMethod = '';125  events.forEach(({ event: { method, section } }) => {126    if (section === 'nft') {127      checkMsgNftMethod = method;128    } else if (section === 'treasury') {129      checkMsgTrsMethod = method;130    } else if (section === 'system') {131      checkMsgSysMethod = method;132    } else { return null; }133  });134  const result: IGetMessage = {135    checkMsgNftMethod,136    checkMsgTrsMethod,137    checkMsgSysMethod,138  };139  return result;140}141142export function getGenericResult(events: EventRecord[]): GenericResult {143  const result: GenericResult = {144    success: false,145  };146  events.forEach(({ event: { method } }) => {147    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);148    if (method === 'ExtrinsicSuccess') {149      result.success = true;150    }151  });152  return result;153}154155156157export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {158  let success = false;159  let collectionId = 0;160  events.forEach(({ event: { data, method, section } }) => {161    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);162    if (method == 'ExtrinsicSuccess') {163      success = true;164    } else if ((section == 'nft') && (method == 'CollectionCreated')) {165      collectionId = parseInt(data[0].toString());166    }167  });168  const result: CreateCollectionResult = {169    success,170    collectionId,171  };172  return result;173}174175export function getCreateItemResult(events: EventRecord[]): CreateItemResult {176  let success = false;177  let collectionId = 0;178  let itemId = 0;179  let recipient;180  events.forEach(({ event: { data, method, section } }) => {181    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);182    if (method == 'ExtrinsicSuccess') {183      success = true;184    } else if ((section == 'nft') && (method == 'ItemCreated')) {185      collectionId = parseInt(data[0].toString());186      itemId = parseInt(data[1].toString());187      recipient = data[2].toJSON();188    }189  });190  const result: CreateItemResult = {191    success,192    collectionId,193    itemId,194    recipient,195  };196  return result;197}198199export function getTransferResult(events: EventRecord[]): TransferResult {200  const result: TransferResult = {201    success: false,202    collectionId: 0,203    itemId: 0,204    value: 0n,205  };206207  events.forEach(({ event: { data, method, section } }) => {208    if (method === 'ExtrinsicSuccess') {209      result.success = true;210    } else if (section === 'nft' && method === 'Transfer') {211      result.collectionId = +data[0].toString();212      result.itemId = +data[1].toString();213      result.sender = data[2].toJSON() as CrossAccountId;214      result.recipient = data[3].toJSON() as CrossAccountId;215      result.value = BigInt(data[4].toString());216    }217  });218219  return result;220}221222interface Invalid {223  type: 'Invalid';224}225226interface Nft {227  type: 'NFT';228}229230interface Fungible {231  type: 'Fungible';232  decimalPoints: number;233}234235interface ReFungible {236  type: 'ReFungible';237}238239type CollectionMode = Nft | Fungible | ReFungible | Invalid;240241export type CreateCollectionParams = {242  mode: CollectionMode,243  name: string,244  description: string,245  tokenPrefix: string,246};247248const defaultCreateCollectionParams: CreateCollectionParams = {249  description: 'description',250  mode: { type: 'NFT' },251  name: 'name',252  tokenPrefix: 'prefix',253};254255export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {256  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };257258  let collectionId = 0;259  await usingApi(async (api) => {260    // Get number of collections before the transaction261    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);262263    // Run the CreateCollection transaction264    const alicePrivateKey = privateKey('//Alice');265266    let modeprm = {};267    if (mode.type === 'NFT') {268      modeprm = { nft: null };269    } else if (mode.type === 'Fungible') {270      modeprm = { fungible: mode.decimalPoints };271    } else if (mode.type === 'ReFungible') {272      modeprm = { refungible: null };273    } else if (mode.type === 'Invalid') {274      modeprm = { invalid: null };275    }276277    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);278    const events = await submitTransactionAsync(alicePrivateKey, tx);279    const result = getCreateCollectionResult(events);280281    // Get number of collections after the transaction282    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);283284    // Get the collection285    const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();286287    // What to expect288    // tslint:disable-next-line:no-unused-expression289    expect(result.success).to.be.true;290    expect(result.collectionId).to.be.equal(BcollectionCount);291    // tslint:disable-next-line:no-unused-expression292    expect(collection).to.be.not.null;293    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');294    expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));295    expect(utf16ToStr(collection.Name)).to.be.equal(name);296    expect(utf16ToStr(collection.Description)).to.be.equal(description);297    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);298299    collectionId = result.collectionId;300  });301302  return collectionId;303}304305export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {306  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };307308  let modeprm = {};309  if (mode.type === 'NFT') {310    modeprm = { nft: null };311  } else if (mode.type === 'Fungible') {312    modeprm = { fungible: mode.decimalPoints };313  } else if (mode.type === 'ReFungible') {314    modeprm = { refungible: null };315  } else if (mode.type === 'Invalid') {316    modeprm = { invalid: null };317  }318319  await usingApi(async (api) => {320    // Get number of collections before the transaction321    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());322323    // Run the CreateCollection transaction324    const alicePrivateKey = privateKey('//Alice');325    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);326    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;327    const result = getCreateCollectionResult(events);328329    // Get number of collections after the transaction330    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());331332    // What to expect333    // tslint:disable-next-line:no-unused-expression334    expect(result.success).to.be.false;335    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');336  });337}338339export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {340  let bal = new BigNumber(0);341  let unused;342  do {343    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;344    const keyring = new Keyring({ type: 'sr25519' });345    unused = keyring.addFromUri(`//${randomSeed}`);346    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());347  } while (bal.toFixed() != '0');348  return unused;349}350351export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {352  return await usingApi(async (api) => {353    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;354    return BigInt(bn.toString());355  });356}357358export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {359  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));360}361362export async function findNotExistingCollection(api: ApiPromise): Promise<number> {363  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;364  const newCollection: number = totalNumber + 1;365  return newCollection;366}367368function getDestroyResult(events: EventRecord[]): boolean {369  let success = false;370  events.forEach(({ event: { method } }) => {371    if (method == 'ExtrinsicSuccess') {372      success = true;373    }374  });375  return success;376}377378export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {379  await usingApi(async (api) => {380    // Run the DestroyCollection transaction381    const alicePrivateKey = privateKey(senderSeed);382    const tx = api.tx.nft.destroyCollection(collectionId);383    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;384  });385}386387export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {388  await usingApi(async (api) => {389    // Run the DestroyCollection transaction390    const alicePrivateKey = privateKey(senderSeed);391    const tx = api.tx.nft.destroyCollection(collectionId);392    const events = await submitTransactionAsync(alicePrivateKey, tx);393    const result = getDestroyResult(events);394395    // Get the collection396    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();397398    // What to expect399    expect(result).to.be.true;400    expect(collection).to.be.null;401  });402}403404export async function queryCollectionLimits(collectionId: number) {405  return await usingApi(async (api) => {406    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;407  });408}409410export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {411  await usingApi(async (api) => {412    const oldLimits = await queryCollectionLimits(collectionId);413    const newLimits = { ...oldLimits as any, ...limits };414    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);415    const events = await submitTransactionAsync(sender, tx);416    const result = getGenericResult(events);417418    expect(result.success).to.be.true;419  });420}421422export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {423  await usingApi(async (api) => {424    const oldLimits = await queryCollectionLimits(collectionId);425    const newLimits = { ...oldLimits as any, ...limits };426    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);427    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;428    const result = getGenericResult(events);429430    expect(result.success).to.be.false;431  });432}433434export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {435  await usingApi(async (api) => {436437    // Run the transaction438    const senderPrivateKey = privateKey(sender);439    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);440    const events = await submitTransactionAsync(senderPrivateKey, tx);441    const result = getGenericResult(events);442443    // Get the collection444    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();445446    // What to expect447    expect(result.success).to.be.true;448    expect(collection.Sponsorship).to.deep.equal({449      unconfirmed: sponsor,450    });451  });452}453454export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {455  await usingApi(async (api) => {456457    // Run the transaction458    const alicePrivateKey = privateKey(sender);459    const tx = api.tx.nft.removeCollectionSponsor(collectionId);460    const events = await submitTransactionAsync(alicePrivateKey, tx);461    const result = getGenericResult(events);462463    // Get the collection464    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();465466    // What to expect467    expect(result.success).to.be.true;468    expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });469  });470}471472export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {473  await usingApi(async (api) => {474475    // Run the transaction476    const alicePrivateKey = privateKey(senderSeed);477    const tx = api.tx.nft.removeCollectionSponsor(collectionId);478    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;479  });480}481482export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {483  await usingApi(async (api) => {484485    // Run the transaction486    const alicePrivateKey = privateKey(senderSeed);487    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);488    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;489  });490}491492export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {493  await usingApi(async (api) => {494495    // Run the transaction496    const sender = privateKey(senderSeed);497    const tx = api.tx.nft.confirmSponsorship(collectionId);498    const events = await submitTransactionAsync(sender, tx);499    const result = getGenericResult(events);500501    // Get the collection502    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();503504    // What to expect505    expect(result.success).to.be.true;506    expect(collection.Sponsorship).to.be.deep.equal({507      confirmed: sender.address,508    });509  });510}511512513export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {514  await usingApi(async (api) => {515516    // Run the transaction517    const sender = privateKey(senderSeed);518    const tx = api.tx.nft.confirmSponsorship(collectionId);519    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;520  });521}522523export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {524  await usingApi(async (api) => {525    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);526    const events = await submitTransactionAsync(sender, tx);527    const result = getGenericResult(events);528529    expect(result.success).to.be.true;530  });531}532533export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {534  await usingApi(async (api) => {535    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);536    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;537    const result = getGenericResult(events);538539    expect(result.success).to.be.false;540  });541}542543export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {544545  await usingApi(async (api) => {546547    const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);548    const events = await submitTransactionAsync(sender, tx);549    const result = getGenericResult(events);550551    expect(result.success).to.be.true;552  }); 553}554555export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {556557  await usingApi(async (api) => {558559    const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);560    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;561    const result = getGenericResult(events);562563    expect(result.success).to.be.false;564  }); 565}566567export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {568  await usingApi(async (api) => {569    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);570    const events = await submitTransactionAsync(sender, tx);571    const result = getGenericResult(events);572573    expect(result.success).to.be.true;574  });575}576577export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {578  await usingApi(async (api) => {579    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);580    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;581    const result = getGenericResult(events);582583    expect(result.success).to.be.false;584  });585}586587export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {588  await usingApi(async (api) => {589    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);590    const events = await submitTransactionAsync(sender, tx);591    const result = getGenericResult(events);592593    expect(result.success).to.be.true;594  });595}596597export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {598  let whitelisted = false;599  await usingApi(async (api) => {600    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;601  });602  return whitelisted;603}604605export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {606  await usingApi(async (api) => {607    const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());608    const events = await submitTransactionAsync(sender, tx);609    const result = getGenericResult(events);610611    expect(result.success).to.be.true;612  });613}614615export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {616  await usingApi(async (api) => {617    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());618    const events = await submitTransactionAsync(sender, tx);619    const result = getGenericResult(events);620621    expect(result.success).to.be.true;622  });623}624625export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {626  await usingApi(async (api) => {627    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());628    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;629    const result = getGenericResult(events);630631    expect(result.success).to.be.false;632  });633}634635export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {636  await usingApi(async (api) => {637    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));638    const events = await submitTransactionAsync(sender, tx);639    const result = getGenericResult(events);640641    expect(result.success).to.be.true;642  });643}644645export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {646  await usingApi(async (api) => {647    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));648    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;649  });650}651652export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {653  await usingApi(async (api) => {654    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));655    const events = await submitTransactionAsync(sender, tx);656    const result = getGenericResult(events);657658    expect(result.success).to.be.true;659  });660}661662export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {663  await usingApi(async (api) => {664    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));665    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;666  });667}668669export interface CreateFungibleData {670  readonly Value: bigint;671}672673export interface CreateReFungibleData { }674export interface CreateNftData { }675676export type CreateItemData = {677  NFT: CreateNftData;678} | {679  Fungible: CreateFungibleData;680} | {681  ReFungible: CreateReFungibleData;682};683684export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {685  await usingApi(async (api) => {686    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);687    const events = await submitTransactionAsync(owner, tx);688    const result = getGenericResult(events);689    // Get the item690    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();691    // What to expect692    // tslint:disable-next-line:no-unused-expression693    expect(result.success).to.be.true;694    // tslint:disable-next-line:no-unused-expression695    expect(item).to.be.null;696  });697}698699export async function700approveExpectSuccess(701  collectionId: number,702  tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1,703) {704  await usingApi(async (api: ApiPromise) => {705    approved = normalizeAccountId(approved);706    const allowanceBefore =707      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;708    const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);709    const events = await submitTransactionAsync(owner, approveNftTx);710    const result = getCreateItemResult(events);711    // tslint:disable-next-line:no-unused-expression712    expect(result.success).to.be.true;713    const allowanceAfter =714      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;715    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());716  });717}718719export async function720transferFromExpectSuccess(721  collectionId: number,722  tokenId: number,723  accountApproved: IKeyringPair,724  accountFrom: IKeyringPair | CrossAccountId,725  accountTo: IKeyringPair | CrossAccountId,726  value: number | bigint = 1,727  type = 'NFT',728) {729  await usingApi(async (api: ApiPromise) => {730    const to = normalizeAccountId(accountTo);731    let balanceBefore = new BN(0);732    if (type === 'Fungible') {733      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;734    }735    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);736    const events = await submitTransactionAsync(accountApproved, transferFromTx);737    const result = getCreateItemResult(events);738    // tslint:disable-next-line:no-unused-expression739    expect(result.success).to.be.true;740    if (type === 'NFT') {741      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;742      expect(nftItemData.Owner).to.be.deep.equal(to);743    }744    if (type === 'Fungible') {745      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;746      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());747    }748    if (type === 'ReFungible') {749      const nftItemData =750        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;751      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));752      expect(nftItemData.Owner[0].Fraction).to.be.equal(value);753    }754  });755}756757export async function758transferFromExpectFail(759  collectionId: number,760  tokenId: number,761  accountApproved: IKeyringPair,762  accountFrom: IKeyringPair,763  accountTo: IKeyringPair,764  value: number | bigint = 1,765) {766  await usingApi(async (api: ApiPromise) => {767    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);768    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;769    const result = getCreateCollectionResult(events);770    // tslint:disable-next-line:no-unused-expression771    expect(result.success).to.be.false;772  });773}774775/* eslint no-async-promise-executor: "off" */776async function getBlockNumber(api: ApiPromise): Promise<number> {777  return new Promise<number>(async (resolve) => {778    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {779      unsubscribe();780      resolve(head.number.toNumber());781    });782  });783}784785export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: IKeyringPair) {786  await usingApi(async (api) => {787    const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(address.address));788    const events = await submitTransactionAsync(sender, changeAdminTx);789    const result = getCreateCollectionResult(events);790    expect(result.success).to.be.true;791  });792}793794export async function795scheduleTransferExpectSuccess(796  collectionId: number,797  tokenId: number,798  sender: IKeyringPair,799  recipient: IKeyringPair,800  value: number | bigint = 1,801  blockTimeMs: number,802  blockSchedule: number,803) {804  await usingApi(async (api: ApiPromise) => {805    const blockNumber: number | undefined = await getBlockNumber(api);806    const expectedBlockNumber = blockNumber + blockSchedule;807808    expect(blockNumber).to.be.greaterThan(0);809    const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value); 810    const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);811812    await submitTransactionAsync(sender, scheduleTx);813814    const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());815816    const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as any as ITokenDataType;817    expect(toSubstrateAddress(nftItemDataBefore.Owner)).to.be.equal(sender.address);818819    // sleep for 4 blocks820    await new Promise(resolve => setTimeout(resolve, blockTimeMs * (blockSchedule + 1)));821822    const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());823824    const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;825    expect(toSubstrateAddress(nftItemData.Owner)).to.be.equal(recipient.address);826    expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());827  });828}829830831export async function832transferExpectSuccess(833  collectionId: number,834  tokenId: number,835  sender: IKeyringPair,836  recipient: IKeyringPair | CrossAccountId,837  value: number | bigint = 1,838  type = 'NFT',839) {840  await usingApi(async (api: ApiPromise) => {841    const to = normalizeAccountId(recipient);842843    let balanceBefore = new BN(0);844    if (type === 'Fungible') {845      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;846    }847    const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);848    const events = await submitTransactionAsync(sender, transferTx);849    const result = getTransferResult(events);850    // tslint:disable-next-line:no-unused-expression851    expect(result.success).to.be.true;852    expect(result.collectionId).to.be.equal(collectionId);853    expect(result.itemId).to.be.equal(tokenId);854    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));855    expect(result.recipient).to.be.deep.equal(to);856    expect(result.value.toString()).to.be.equal(value.toString());857    if (type === 'NFT') {858      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;859      expect(nftItemData.Owner).to.be.deep.equal(to);860    }861    if (type === 'Fungible') {862      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;863      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());864    }865    if (type === 'ReFungible') {866      const nftItemData =867        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;868      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);869      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());870    }871  });872}873874export async function875transferExpectFailure(876  collectionId: number,877  tokenId: number,878  sender: IKeyringPair,879  recipient: IKeyringPair,880  value: number | bigint = 1,881) {882  await usingApi(async (api: ApiPromise) => {883    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);884    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;885    if (events && Array.isArray(events)) {886      const result = getCreateCollectionResult(events);887      // tslint:disable-next-line:no-unused-expression888      expect(result.success).to.be.false;889    }890  });891}892893export async function894approveExpectFail(895  collectionId: number,896  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,897) {898  await usingApi(async (api: ApiPromise) => {899    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);900    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;901    const result = getCreateCollectionResult(events);902    // tslint:disable-next-line:no-unused-expression903    expect(result.success).to.be.false;904  });905}906907export async function getFungibleBalance(908  collectionId: number,909  owner: string,910) {911  return await usingApi(async (api) => {912    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };913    return BigInt(response.Value);914  });915}916917export async function createFungibleItemExpectSuccess(918  sender: IKeyringPair,919  collectionId: number,920  data: CreateFungibleData,921  owner: CrossAccountId | string = sender.address,922) {923  return await usingApi(async (api) => {924    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });925926    const events = await submitTransactionAsync(sender, tx);927    const result = getCreateItemResult(events);928929    expect(result.success).to.be.true;930    return result.itemId;931  });932}933934export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {935  let newItemId = 0;936  await usingApi(async (api) => {937    const to = normalizeAccountId(owner);938    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);939    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();940    const AItemBalance = new BigNumber(Aitem.Value);941942    let tx;943    if (createMode === 'Fungible') {944      const createData = { fungible: { value: 10 } };945      tx = api.tx.nft.createItem(collectionId, to, createData);946    } else if (createMode === 'ReFungible') {947      const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };948      tx = api.tx.nft.createItem(collectionId, to, createData);949    } else {950      const createData = { nft: { const_data: [], variable_data: [] } };951      tx = api.tx.nft.createItem(collectionId, to, createData);952    }953954    const events = await submitTransactionAsync(sender, tx);955    const result = getCreateItemResult(events);956957    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);958    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();959    const BItemBalance = new BigNumber(Bitem.Value);960961    // What to expect962    // tslint:disable-next-line:no-unused-expression963    expect(result.success).to.be.true;964    if (createMode === 'Fungible') {965      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);966    } else {967      expect(BItemCount).to.be.equal(AItemCount + 1);968    }969    expect(collectionId).to.be.equal(result.collectionId);970    expect(BItemCount.toString()).to.be.equal(result.itemId.toString());971    expect(to).to.be.deep.equal(result.recipient);972    newItemId = result.itemId;973  });974  return newItemId;975}976977export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {978  await usingApi(async (api) => {979    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);980    981    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;982    const result = getCreateItemResult(events);983984    expect(result.success).to.be.false;985  });986}987988export async function setPublicAccessModeExpectSuccess(989  sender: IKeyringPair, collectionId: number,990  accessMode: 'Normal' | 'WhiteList',991) {992  await usingApi(async (api) => {993994    // Run the transaction995    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);996    const events = await submitTransactionAsync(sender, tx);997    const result = getGenericResult(events);998999    // Get the collection1000    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10011002    // What to expect1003    // tslint:disable-next-line:no-unused-expression1004    expect(result.success).to.be.true;1005    expect(collection.Access).to.be.equal(accessMode);1006  });1007}10081009export async function setPublicAccessModeExpectFail(1010  sender: IKeyringPair, collectionId: number,1011  accessMode: 'Normal' | 'WhiteList',1012) {1013  await usingApi(async (api) => {10141015    // Run the transaction1016    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1017    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1018    const result = getGenericResult(events);10191020    // What to expect1021    // tslint:disable-next-line:no-unused-expression1022    expect(result.success).to.be.false;1023  });1024}10251026export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1027  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');1028}10291030export async function enableWhiteListExpectFail(sender: IKeyringPair, collectionId: number) {1031  await setPublicAccessModeExpectFail(sender, collectionId, 'WhiteList');1032}10331034export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1035  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1036}10371038export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1039  await usingApi(async (api) => {10401041    // Run the transaction1042    const tx = api.tx.nft.setMintPermission(collectionId, enabled);1043    const events = await submitTransactionAsync(sender, tx);1044    const result = getGenericResult(events);10451046    // Get the collection1047    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10481049    // What to expect1050    // tslint:disable-next-line:no-unused-expression1051    expect(result.success).to.be.true;1052    expect(collection.MintMode).to.be.equal(enabled);1053  });1054}10551056export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1057  await setMintPermissionExpectSuccess(sender, collectionId, true);1058}10591060export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1061  await usingApi(async (api) => {1062    // Run the transaction1063    const tx = api.tx.nft.setMintPermission(collectionId, enabled);1064    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1065    const result = getCreateCollectionResult(events);1066    // tslint:disable-next-line:no-unused-expression1067    expect(result.success).to.be.false;1068  });1069}10701071export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1072  await usingApi(async (api) => {1073    // Run the transaction1074    const tx = api.tx.nft.setChainLimits(limits);1075    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1076    const result = getCreateCollectionResult(events);1077    // tslint:disable-next-line:no-unused-expression1078    expect(result.success).to.be.false;1079  });1080}10811082export async function isWhitelisted(collectionId: number, address: string) {1083  let whitelisted = false;1084  await usingApi(async (api) => {1085    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1086  });1087  return whitelisted;1088}10891090export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1091  await usingApi(async (api) => {10921093    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();10941095    // Run the transaction1096    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1097    const events = await submitTransactionAsync(sender, tx);1098    const result = getGenericResult(events);10991100    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();11011102    // What to expect1103    // tslint:disable-next-line:no-unused-expression1104    expect(result.success).to.be.true;1105    // tslint:disable-next-line: no-unused-expression1106    expect(whiteListedBefore).to.be.false;1107    // tslint:disable-next-line: no-unused-expression1108    expect(whiteListedAfter).to.be.true;1109  });1110}11111112export async function addToWhiteListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1113  await usingApi(async (api) => {1114    // Run the transaction1115    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1116    const events = await expect(submitTransactionAsync(sender, tx)).to.be.rejected;1117    const result = getGenericResult(events);11181119    // What to expect1120    // tslint:disable-next-line:no-unused-expression1121    expect(result.success).to.be.false;1122  });1123}11241125export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1126  await usingApi(async (api) => {1127    // Run the transaction1128    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1129    const events = await submitTransactionAsync(sender, tx);1130    const result = getGenericResult(events);11311132    // What to expect1133    // tslint:disable-next-line:no-unused-expression1134    expect(result.success).to.be.true;1135  });1136}11371138export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1139  await usingApi(async (api) => {1140    // Run the transaction1141    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1142    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1143    const result = getGenericResult(events);11441145    // What to expect1146    // tslint:disable-next-line:no-unused-expression1147    expect(result.success).to.be.false;1148  });1149}11501151export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1152  : Promise<ICollectionInterface | null> => {1153  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1154};11551156export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1157  // set global object - collectionsCount1158  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1159};11601161export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1162  return await usingApi(async (api) => {1163    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1164  });1165}
after · tests/src/util/helpers.ts
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;5556type GenericResult = {57  success: boolean,58};5960interface CreateCollectionResult {61  success: boolean;62  collectionId: number;63}6465interface CreateItemResult {66  success: boolean;67  collectionId: number;68  itemId: number;69  recipient?: CrossAccountId;70}7172interface TransferResult {73  success: boolean;74  collectionId: number;75  itemId: number;76  sender?: CrossAccountId;77  recipient?: CrossAccountId;78  value: bigint;79}8081interface IReFungibleOwner {82  Fraction: BN;83  Owner: number[];84}8586interface ITokenDataType {87  Owner: IKeyringPair;88  ConstData: number[];89  VariableData: number[];90}9192interface IGetMessage {93  checkMsgNftMethod: string;94  checkMsgTrsMethod: string;95  checkMsgSysMethod: string;96}9798export interface IFungibleTokenDataType {99  Value: number;100}101102export interface IChainLimits {103  CollectionNumbersLimit: number;104	AccountTokenOwnershipLimit: number;105	CollectionsAdminsLimit: number;106	CustomDataLimit: number;107	NftSponsorTransferTimeout: number;108	FungibleSponsorTransferTimeout: number;109	RefungibleSponsorTransferTimeout: number;110	OffchainSchemaLimit: number;111	VariableOnChainSchemaLimit: number;112	ConstOnChainSchemaLimit: number;113}114115export interface IReFungibleTokenDataType {116  Owner: IReFungibleOwner[];117  ConstData: number[];118  VariableData: number[];119}120121export function nftEventMessage(events: EventRecord[]): IGetMessage {122  let checkMsgNftMethod = '';123  let checkMsgTrsMethod = '';124  let checkMsgSysMethod = '';125  events.forEach(({ event: { method, section } }) => {126    if (section === 'nft') {127      checkMsgNftMethod = method;128    } else if (section === 'treasury') {129      checkMsgTrsMethod = method;130    } else if (section === 'system') {131      checkMsgSysMethod = method;132    } else { return null; }133  });134  const result: IGetMessage = {135    checkMsgNftMethod,136    checkMsgTrsMethod,137    checkMsgSysMethod,138  };139  return result;140}141142export function getGenericResult(events: EventRecord[]): GenericResult {143  const result: GenericResult = {144    success: false,145  };146  events.forEach(({ event: { method } }) => {147    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);148    if (method === 'ExtrinsicSuccess') {149      result.success = true;150    }151  });152  return result;153}154155156157export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {158  let success = false;159  let collectionId = 0;160  events.forEach(({ event: { data, method, section } }) => {161    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);162    if (method == 'ExtrinsicSuccess') {163      success = true;164    } else if ((section == 'nft') && (method == 'CollectionCreated')) {165      collectionId = parseInt(data[0].toString());166    }167  });168  const result: CreateCollectionResult = {169    success,170    collectionId,171  };172  return result;173}174175export function getCreateItemResult(events: EventRecord[]): CreateItemResult {176  let success = false;177  let collectionId = 0;178  let itemId = 0;179  let recipient;180  events.forEach(({ event: { data, method, section } }) => {181    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);182    if (method == 'ExtrinsicSuccess') {183      success = true;184    } else if ((section == 'nft') && (method == 'ItemCreated')) {185      collectionId = parseInt(data[0].toString());186      itemId = parseInt(data[1].toString());187      recipient = data[2].toJSON();188    }189  });190  const result: CreateItemResult = {191    success,192    collectionId,193    itemId,194    recipient,195  };196  return result;197}198199export function getTransferResult(events: EventRecord[]): TransferResult {200  const result: TransferResult = {201    success: false,202    collectionId: 0,203    itemId: 0,204    value: 0n,205  };206207  events.forEach(({ event: { data, method, section } }) => {208    if (method === 'ExtrinsicSuccess') {209      result.success = true;210    } else if (section === 'nft' && method === 'Transfer') {211      result.collectionId = +data[0].toString();212      result.itemId = +data[1].toString();213      result.sender = data[2].toJSON() as CrossAccountId;214      result.recipient = data[3].toJSON() as CrossAccountId;215      result.value = BigInt(data[4].toString());216    }217  });218219  return result;220}221222interface Invalid {223  type: 'Invalid';224}225226interface Nft {227  type: 'NFT';228}229230interface Fungible {231  type: 'Fungible';232  decimalPoints: number;233}234235interface ReFungible {236  type: 'ReFungible';237}238239type CollectionMode = Nft | Fungible | ReFungible | Invalid;240241export type CreateCollectionParams = {242  mode: CollectionMode,243  name: string,244  description: string,245  tokenPrefix: string,246};247248const defaultCreateCollectionParams: CreateCollectionParams = {249  description: 'description',250  mode: { type: 'NFT' },251  name: 'name',252  tokenPrefix: 'prefix',253};254255export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {256  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };257258  let collectionId = 0;259  await usingApi(async (api) => {260    // Get number of collections before the transaction261    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);262263    // Run the CreateCollection transaction264    const alicePrivateKey = privateKey('//Alice');265266    let modeprm = {};267    if (mode.type === 'NFT') {268      modeprm = { nft: null };269    } else if (mode.type === 'Fungible') {270      modeprm = { fungible: mode.decimalPoints };271    } else if (mode.type === 'ReFungible') {272      modeprm = { refungible: null };273    } else if (mode.type === 'Invalid') {274      modeprm = { invalid: null };275    }276277    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);278    const events = await submitTransactionAsync(alicePrivateKey, tx);279    const result = getCreateCollectionResult(events);280281    // Get number of collections after the transaction282    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);283284    // Get the collection285    const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();286287    // What to expect288    // tslint:disable-next-line:no-unused-expression289    expect(result.success).to.be.true;290    expect(result.collectionId).to.be.equal(BcollectionCount);291    // tslint:disable-next-line:no-unused-expression292    expect(collection).to.be.not.null;293    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');294    expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));295    expect(utf16ToStr(collection.Name)).to.be.equal(name);296    expect(utf16ToStr(collection.Description)).to.be.equal(description);297    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);298299    collectionId = result.collectionId;300  });301302  return collectionId;303}304305export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {306  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };307308  let modeprm = {};309  if (mode.type === 'NFT') {310    modeprm = { nft: null };311  } else if (mode.type === 'Fungible') {312    modeprm = { fungible: mode.decimalPoints };313  } else if (mode.type === 'ReFungible') {314    modeprm = { refungible: null };315  } else if (mode.type === 'Invalid') {316    modeprm = { invalid: null };317  }318319  await usingApi(async (api) => {320    // Get number of collections before the transaction321    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());322323    // Run the CreateCollection transaction324    const alicePrivateKey = privateKey('//Alice');325    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);326    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;327    const result = getCreateCollectionResult(events);328329    // Get number of collections after the transaction330    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());331332    // What to expect333    // tslint:disable-next-line:no-unused-expression334    expect(result.success).to.be.false;335    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');336  });337}338339export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {340  let bal = new BigNumber(0);341  let unused;342  do {343    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;344    const keyring = new Keyring({ type: 'sr25519' });345    unused = keyring.addFromUri(`//${randomSeed}`);346    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());347  } while (bal.toFixed() != '0');348  return unused;349}350351export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {352  return await usingApi(async (api) => {353    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;354    return BigInt(bn.toString());355  });356}357358export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {359  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));360}361362export async function findNotExistingCollection(api: ApiPromise): Promise<number> {363  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;364  const newCollection: number = totalNumber + 1;365  return newCollection;366}367368function getDestroyResult(events: EventRecord[]): boolean {369  let success = false;370  events.forEach(({ event: { method } }) => {371    if (method == 'ExtrinsicSuccess') {372      success = true;373    }374  });375  return success;376}377378export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {379  await usingApi(async (api) => {380    // Run the DestroyCollection transaction381    const alicePrivateKey = privateKey(senderSeed);382    const tx = api.tx.nft.destroyCollection(collectionId);383    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;384  });385}386387export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {388  await usingApi(async (api) => {389    // Run the DestroyCollection transaction390    const alicePrivateKey = privateKey(senderSeed);391    const tx = api.tx.nft.destroyCollection(collectionId);392    const events = await submitTransactionAsync(alicePrivateKey, tx);393    const result = getDestroyResult(events);394395    // Get the collection396    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();397398    // What to expect399    expect(result).to.be.true;400    expect(collection).to.be.null;401  });402}403404export async function queryCollectionLimits(collectionId: number) {405  return await usingApi(async (api) => {406    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;407  });408}409410export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {411  await usingApi(async (api) => {412    const oldLimits = await queryCollectionLimits(collectionId);413    const newLimits = { ...oldLimits as any, ...limits };414    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);415    const events = await submitTransactionAsync(sender, tx);416    const result = getGenericResult(events);417418    expect(result.success).to.be.true;419  });420}421422export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {423  await usingApi(async (api) => {424    const oldLimits = await queryCollectionLimits(collectionId);425    const newLimits = { ...oldLimits as any, ...limits };426    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);427    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;428    const result = getGenericResult(events);429430    expect(result.success).to.be.false;431  });432}433434export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {435  await usingApi(async (api) => {436437    // Run the transaction438    const senderPrivateKey = privateKey(sender);439    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);440    const events = await submitTransactionAsync(senderPrivateKey, tx);441    const result = getGenericResult(events);442443    // Get the collection444    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();445446    // What to expect447    expect(result.success).to.be.true;448    expect(collection.Sponsorship).to.deep.equal({449      unconfirmed: sponsor,450    });451  });452}453454export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {455  await usingApi(async (api) => {456457    // Run the transaction458    const alicePrivateKey = privateKey(sender);459    const tx = api.tx.nft.removeCollectionSponsor(collectionId);460    const events = await submitTransactionAsync(alicePrivateKey, tx);461    const result = getGenericResult(events);462463    // Get the collection464    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();465466    // What to expect467    expect(result.success).to.be.true;468    expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });469  });470}471472export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {473  await usingApi(async (api) => {474475    // Run the transaction476    const alicePrivateKey = privateKey(senderSeed);477    const tx = api.tx.nft.removeCollectionSponsor(collectionId);478    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;479  });480}481482export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {483  await usingApi(async (api) => {484485    // Run the transaction486    const alicePrivateKey = privateKey(senderSeed);487    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);488    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;489  });490}491492export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {493  await usingApi(async (api) => {494495    // Run the transaction496    const sender = privateKey(senderSeed);497    const tx = api.tx.nft.confirmSponsorship(collectionId);498    const events = await submitTransactionAsync(sender, tx);499    const result = getGenericResult(events);500501    // Get the collection502    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();503504    // What to expect505    expect(result.success).to.be.true;506    expect(collection.Sponsorship).to.be.deep.equal({507      confirmed: sender.address,508    });509  });510}511512513export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {514  await usingApi(async (api) => {515516    // Run the transaction517    const sender = privateKey(senderSeed);518    const tx = api.tx.nft.confirmSponsorship(collectionId);519    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;520  });521}522523export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {524  await usingApi(async (api) => {525    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);526    const events = await submitTransactionAsync(sender, tx);527    const result = getGenericResult(events);528529    expect(result.success).to.be.true;530  });531}532533export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {534  await usingApi(async (api) => {535    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);536    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;537    const result = getGenericResult(events);538539    expect(result.success).to.be.false;540  });541}542543export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {544545  await usingApi(async (api) => {546547    const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);548    const events = await submitTransactionAsync(sender, tx);549    const result = getGenericResult(events);550551    expect(result.success).to.be.true;552  }); 553}554555export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {556557  await usingApi(async (api) => {558559    const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);560    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;561    const result = getGenericResult(events);562563    expect(result.success).to.be.false;564  }); 565}566567export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {568  await usingApi(async (api) => {569    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);570    const events = await submitTransactionAsync(sender, tx);571    const result = getGenericResult(events);572573    expect(result.success).to.be.true;574  });575}576577export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {578  await usingApi(async (api) => {579    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);580    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;581    const result = getGenericResult(events);582583    expect(result.success).to.be.false;584  });585}586587export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {588  await usingApi(async (api) => {589    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);590    const events = await submitTransactionAsync(sender, tx);591    const result = getGenericResult(events);592593    expect(result.success).to.be.true;594  });595}596597export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {598  let whitelisted = false;599  await usingApi(async (api) => {600    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;601  });602  return whitelisted;603}604605export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {606  await usingApi(async (api) => {607    const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());608    const events = await submitTransactionAsync(sender, tx);609    const result = getGenericResult(events);610611    expect(result.success).to.be.true;612  });613}614615export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {616  await usingApi(async (api) => {617    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());618    const events = await submitTransactionAsync(sender, tx);619    const result = getGenericResult(events);620621    expect(result.success).to.be.true;622  });623}624625export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {626  await usingApi(async (api) => {627    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());628    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;629    const result = getGenericResult(events);630631    expect(result.success).to.be.false;632  });633}634635export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {636  await usingApi(async (api) => {637    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));638    const events = await submitTransactionAsync(sender, tx);639    const result = getGenericResult(events);640641    expect(result.success).to.be.true;642  });643}644645export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {646  await usingApi(async (api) => {647    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));648    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;649  });650}651652export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {653  await usingApi(async (api) => {654    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));655    const events = await submitTransactionAsync(sender, tx);656    const result = getGenericResult(events);657658    expect(result.success).to.be.true;659  });660}661662export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {663  await usingApi(async (api) => {664    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));665    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;666  });667}668669export interface CreateFungibleData {670  readonly Value: bigint;671}672673export interface CreateReFungibleData { }674export interface CreateNftData { }675676export type CreateItemData = {677  NFT: CreateNftData;678} | {679  Fungible: CreateFungibleData;680} | {681  ReFungible: CreateReFungibleData;682};683684export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {685  await usingApi(async (api) => {686    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);687    const events = await submitTransactionAsync(owner, tx);688    const result = getGenericResult(events);689    // Get the item690    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();691    // What to expect692    // tslint:disable-next-line:no-unused-expression693    expect(result.success).to.be.true;694    // tslint:disable-next-line:no-unused-expression695    expect(item).to.be.null;696  });697}698699export async function700approveExpectSuccess(701  collectionId: number,702  tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1,703) {704  await usingApi(async (api: ApiPromise) => {705    approved = normalizeAccountId(approved);706    const allowanceBefore =707      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;708    const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);709    const events = await submitTransactionAsync(owner, approveNftTx);710    const result = getCreateItemResult(events);711    // tslint:disable-next-line:no-unused-expression712    expect(result.success).to.be.true;713    const allowanceAfter =714      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;715    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());716  });717}718719export async function720transferFromExpectSuccess(721  collectionId: number,722  tokenId: number,723  accountApproved: IKeyringPair,724  accountFrom: IKeyringPair | CrossAccountId,725  accountTo: IKeyringPair | CrossAccountId,726  value: number | bigint = 1,727  type = 'NFT',728) {729  await usingApi(async (api: ApiPromise) => {730    const to = normalizeAccountId(accountTo);731    let balanceBefore = new BN(0);732    if (type === 'Fungible') {733      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;734    }735    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);736    const events = await submitTransactionAsync(accountApproved, transferFromTx);737    const result = getCreateItemResult(events);738    // tslint:disable-next-line:no-unused-expression739    expect(result.success).to.be.true;740    if (type === 'NFT') {741      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;742      expect(nftItemData.Owner).to.be.deep.equal(to);743    }744    if (type === 'Fungible') {745      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;746      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());747    }748    if (type === 'ReFungible') {749      const nftItemData =750        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;751      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));752      expect(nftItemData.Owner[0].Fraction).to.be.equal(value);753    }754  });755}756757export async function758transferFromExpectFail(759  collectionId: number,760  tokenId: number,761  accountApproved: IKeyringPair,762  accountFrom: IKeyringPair,763  accountTo: IKeyringPair,764  value: number | bigint = 1,765) {766  await usingApi(async (api: ApiPromise) => {767    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);768    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;769    const result = getCreateCollectionResult(events);770    // tslint:disable-next-line:no-unused-expression771    expect(result.success).to.be.false;772  });773}774775/* eslint no-async-promise-executor: "off" */776async function getBlockNumber(api: ApiPromise): Promise<number> {777  return new Promise<number>(async (resolve) => {778    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {779      unsubscribe();780      resolve(head.number.toNumber());781    });782  });783}784785export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: IKeyringPair) {786  await usingApi(async (api) => {787    const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(address.address));788    const events = await submitTransactionAsync(sender, changeAdminTx);789    const result = getCreateCollectionResult(events);790    expect(result.success).to.be.true;791  });792}793794export async function795scheduleTransferExpectSuccess(796  collectionId: number,797  tokenId: number,798  sender: IKeyringPair,799  recipient: IKeyringPair,800  value: number | bigint = 1,801  blockTimeMs: number,802  blockSchedule: number,803) {804  await usingApi(async (api: ApiPromise) => {805    const blockNumber: number | undefined = await getBlockNumber(api);806    const expectedBlockNumber = blockNumber + blockSchedule;807808    expect(blockNumber).to.be.greaterThan(0);809    const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value); 810    const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);811812    await submitTransactionAsync(sender, scheduleTx);813814    const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());815816    const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as any as ITokenDataType;817    expect(toSubstrateAddress(nftItemDataBefore.Owner)).to.be.equal(sender.address);818819    // sleep for 4 blocks820    await new Promise(resolve => setTimeout(resolve, blockTimeMs * (blockSchedule + 1)));821822    const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());823824    const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;825    expect(toSubstrateAddress(nftItemData.Owner)).to.be.equal(recipient.address);826    expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());827  });828}829830831export async function832transferExpectSuccess(833  collectionId: number,834  tokenId: number,835  sender: IKeyringPair,836  recipient: IKeyringPair | CrossAccountId,837  value: number | bigint = 1,838  type = 'NFT',839) {840  await usingApi(async (api: ApiPromise) => {841    const to = normalizeAccountId(recipient);842843    let balanceBefore = new BN(0);844    if (type === 'Fungible') {845      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;846    }847    const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);848    const events = await submitTransactionAsync(sender, transferTx);849    const result = getTransferResult(events);850    // tslint:disable-next-line:no-unused-expression851    expect(result.success).to.be.true;852    expect(result.collectionId).to.be.equal(collectionId);853    expect(result.itemId).to.be.equal(tokenId);854    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));855    expect(result.recipient).to.be.deep.equal(to);856    expect(result.value.toString()).to.be.equal(value.toString());857    if (type === 'NFT') {858      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;859      expect(nftItemData.Owner).to.be.deep.equal(to);860    }861    if (type === 'Fungible') {862      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;863      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());864    }865    if (type === 'ReFungible') {866      const nftItemData =867        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;868      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);869      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());870    }871  });872}873874export async function875transferExpectFailure(876  collectionId: number,877  tokenId: number,878  sender: IKeyringPair,879  recipient: IKeyringPair,880  value: number | bigint = 1,881) {882  await usingApi(async (api: ApiPromise) => {883    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);884    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;885    if (events && Array.isArray(events)) {886      const result = getCreateCollectionResult(events);887      // tslint:disable-next-line:no-unused-expression888      expect(result.success).to.be.false;889    }890  });891}892893export async function894approveExpectFail(895  collectionId: number,896  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,897) {898  await usingApi(async (api: ApiPromise) => {899    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);900    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;901    const result = getCreateCollectionResult(events);902    // tslint:disable-next-line:no-unused-expression903    expect(result.success).to.be.false;904  });905}906907export async function getFungibleBalance(908  collectionId: number,909  owner: string,910) {911  return await usingApi(async (api) => {912    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };913    return BigInt(response.Value);914  });915}916917export async function createFungibleItemExpectSuccess(918  sender: IKeyringPair,919  collectionId: number,920  data: CreateFungibleData,921  owner: CrossAccountId | string = sender.address,922) {923  return await usingApi(async (api) => {924    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });925926    const events = await submitTransactionAsync(sender, tx);927    const result = getCreateItemResult(events);928929    expect(result.success).to.be.true;930    return result.itemId;931  });932}933934export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {935  let newItemId = 0;936  await usingApi(async (api) => {937    const to = normalizeAccountId(owner);938    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);939    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();940    const AItemBalance = new BigNumber(Aitem.Value);941942    let tx;943    if (createMode === 'Fungible') {944      const createData = { fungible: { value: 10 } };945      tx = api.tx.nft.createItem(collectionId, to, createData);946    } else if (createMode === 'ReFungible') {947      const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };948      tx = api.tx.nft.createItem(collectionId, to, createData);949    } else {950      const createData = { nft: { const_data: [], variable_data: [] } };951      tx = api.tx.nft.createItem(collectionId, to, createData);952    }953954    const events = await submitTransactionAsync(sender, tx);955    const result = getCreateItemResult(events);956957    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);958    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();959    const BItemBalance = new BigNumber(Bitem.Value);960961    // What to expect962    // tslint:disable-next-line:no-unused-expression963    expect(result.success).to.be.true;964    if (createMode === 'Fungible') {965      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);966    } else {967      expect(BItemCount).to.be.equal(AItemCount + 1);968    }969    expect(collectionId).to.be.equal(result.collectionId);970    expect(BItemCount.toString()).to.be.equal(result.itemId.toString());971    expect(to).to.be.deep.equal(result.recipient);972    newItemId = result.itemId;973  });974  return newItemId;975}976977export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {978  await usingApi(async (api) => {979    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);980    981    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;982    const result = getCreateItemResult(events);983984    expect(result.success).to.be.false;985  });986}987988export async function setPublicAccessModeExpectSuccess(989  sender: IKeyringPair, collectionId: number,990  accessMode: 'Normal' | 'WhiteList',991) {992  await usingApi(async (api) => {993994    // Run the transaction995    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);996    const events = await submitTransactionAsync(sender, tx);997    const result = getGenericResult(events);998999    // Get the collection1000    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10011002    // What to expect1003    // tslint:disable-next-line:no-unused-expression1004    expect(result.success).to.be.true;1005    expect(collection.Access).to.be.equal(accessMode);1006  });1007}10081009export async function setPublicAccessModeExpectFail(1010  sender: IKeyringPair, collectionId: number,1011  accessMode: 'Normal' | 'WhiteList',1012) {1013  await usingApi(async (api) => {10141015    // Run the transaction1016    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1017    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1018    const result = getGenericResult(events);10191020    // What to expect1021    // tslint:disable-next-line:no-unused-expression1022    expect(result.success).to.be.false;1023  });1024}10251026export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1027  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');1028}10291030export async function enableWhiteListExpectFail(sender: IKeyringPair, collectionId: number) {1031  await setPublicAccessModeExpectFail(sender, collectionId, 'WhiteList');1032}10331034export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1035  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1036}10371038export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1039  await usingApi(async (api) => {10401041    // Run the transaction1042    const tx = api.tx.nft.setMintPermission(collectionId, enabled);1043    const events = await submitTransactionAsync(sender, tx);1044    const result = getGenericResult(events);10451046    // Get the collection1047    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10481049    // What to expect1050    // tslint:disable-next-line:no-unused-expression1051    expect(result.success).to.be.true;1052    expect(collection.MintMode).to.be.equal(enabled);1053  });1054}10551056export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1057  await setMintPermissionExpectSuccess(sender, collectionId, true);1058}10591060export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1061  await usingApi(async (api) => {1062    // Run the transaction1063    const tx = api.tx.nft.setMintPermission(collectionId, enabled);1064    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1065    const result = getCreateCollectionResult(events);1066    // tslint:disable-next-line:no-unused-expression1067    expect(result.success).to.be.false;1068  });1069}10701071export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1072  await usingApi(async (api) => {1073    // Run the transaction1074    const tx = api.tx.nft.setChainLimits(limits);1075    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1076    const result = getCreateCollectionResult(events);1077    // tslint:disable-next-line:no-unused-expression1078    expect(result.success).to.be.false;1079  });1080}10811082export async function isWhitelisted(collectionId: number, address: string) {1083  let whitelisted = false;1084  await usingApi(async (api) => {1085    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1086  });1087  return whitelisted;1088}10891090export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1091  await usingApi(async (api) => {10921093    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();10941095    // Run the transaction1096    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1097    const events = await submitTransactionAsync(sender, tx);1098    const result = getGenericResult(events);10991100    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();11011102    // What to expect1103    // tslint:disable-next-line:no-unused-expression1104    expect(result.success).to.be.true;1105    // tslint:disable-next-line: no-unused-expression1106    expect(whiteListedBefore).to.be.false;1107    // tslint:disable-next-line: no-unused-expression1108    expect(whiteListedAfter).to.be.true;1109  });1110}11111112export async function addToWhiteListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1113  await usingApi(async (api) => {1114    // Run the transaction1115    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1116    const events = await expect(submitTransactionAsync(sender, tx)).to.be.rejected;1117    const result = getGenericResult(events);11181119    // What to expect1120    // tslint:disable-next-line:no-unused-expression1121    expect(result.success).to.be.false;1122  });1123}11241125export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1126  await usingApi(async (api) => {1127    // Run the transaction1128    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1129    const events = await submitTransactionAsync(sender, tx);1130    const result = getGenericResult(events);11311132    // What to expect1133    // tslint:disable-next-line:no-unused-expression1134    expect(result.success).to.be.true;1135  });1136}11371138export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1139  await usingApi(async (api) => {1140    // Run the transaction1141    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1142    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1143    const result = getGenericResult(events);11441145    // What to expect1146    // tslint:disable-next-line:no-unused-expression1147    expect(result.success).to.be.false;1148  });1149}11501151export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1152  : Promise<ICollectionInterface | null> => {1153  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1154};11551156export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1157  // set global object - collectionsCount1158  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1159};11601161export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1162  return await usingApi(async (api) => {1163    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1164  });1165}11661167export async function queryNftOwner(api: ApiPromise, collectionId: number, tokenId: number): Promise<CrossAccountId> {1168  return normalizeAccountId((await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON().Owner);1169}