difftreelog
Merge branch 'develop' into tests/feed-alices
in: master
126 files changed
tests/src/.outdated/addToContractAllowList.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/addToContractAllowList.test.ts
@@ -0,0 +1,99 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import usingApi, {submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
+import {deployFlipper} from '../deprecated-helpers/contracthelpers';
+import {getGenericResult} from '../deprecated-helpers/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+// todo:playgrounds skipped ~ postponed
+describe.skip('Integration Test addToContractAllowList', () => {
+
+ it('Add an address to a contract allow list', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const bob = privateKeyWrapper('//Bob');
+ const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
+
+ const allowListedBefore = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
+ const addTx = api.tx.unique.addToContractAllowList(contract.address, bob.address);
+ const addEvents = await submitTransactionAsync(deployer, addTx);
+ const allowListedAfter = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
+
+ expect(getGenericResult(addEvents).success).to.be.true;
+ expect(allowListedBefore).to.be.false;
+ expect(allowListedAfter).to.be.true;
+ });
+ });
+
+ it('Adding same address to allow list repeatedly should not produce errors', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const bob = privateKeyWrapper('//Bob');
+ const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
+
+ const allowListedBefore = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
+ const addTx = api.tx.unique.addToContractAllowList(contract.address, bob.address);
+ const addEvents = await submitTransactionAsync(deployer, addTx);
+ const allowListedAfter = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
+ const addAgainEvents = await submitTransactionAsync(deployer, addTx);
+ const allowListedAgainAfter = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
+
+ expect(getGenericResult(addEvents).success).to.be.true;
+ expect(allowListedBefore).to.be.false;
+ expect(allowListedAfter).to.be.true;
+ expect(getGenericResult(addAgainEvents).success).to.be.true;
+ expect(allowListedAgainAfter).to.be.true;
+ });
+ });
+});
+
+describe.skip('Negative Integration Test addToContractAllowList', () => {
+
+ it('Add an address to a allow list of a non-contract', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const alice = privateKeyWrapper('//Bob');
+ const bob = privateKeyWrapper('//Bob');
+ const charlieGuineaPig = privateKeyWrapper('//Charlie');
+
+ const allowListedBefore = (await api.query.unique.contractAllowList(charlieGuineaPig.address, bob.address)).toJSON();
+ const addTx = api.tx.unique.addToContractAllowList(charlieGuineaPig.address, bob.address);
+ await expect(submitTransactionExpectFailAsync(alice, addTx)).to.be.rejected;
+ const allowListedAfter = (await api.query.unique.contractAllowList(charlieGuineaPig.address, bob.address)).toJSON();
+
+ expect(allowListedBefore).to.be.false;
+ expect(allowListedAfter).to.be.false;
+ });
+ });
+
+ it('Add to a contract allow list using a non-owner address', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const bob = privateKeyWrapper('//Bob');
+ const [contract] = await deployFlipper(api, privateKeyWrapper);
+
+ const allowListedBefore = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
+ const addTx = api.tx.unique.addToContractAllowList(contract.address, bob.address);
+ await expect(submitTransactionExpectFailAsync(bob, addTx)).to.be.rejected;
+ const allowListedAfter = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
+
+ expect(allowListedBefore).to.be.false;
+ expect(allowListedAfter).to.be.false;
+ });
+ });
+
+});
tests/src/.outdated/balance-transfer-contract/calls.wasmdiffbeforeafterbothbinary blob — no preview
tests/src/.outdated/balance-transfer-contract/metadata.jsondiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/balance-transfer-contract/metadata.json
@@ -0,0 +1,96 @@
+{
+ "registry": {
+ "strings": [
+ "Storage",
+ "calls",
+ "__ink_private",
+ "__ink_storage",
+ "new",
+ "balance_transfer",
+ "dest",
+ "AccountId",
+ "value",
+ "Balance"
+ ],
+ "types": [
+ {
+ "id": {
+ "custom.name": 1,
+ "custom.namespace": [
+ 2,
+ 2,
+ 3,
+ 4
+ ],
+ "custom.params": []
+ },
+ "def": {
+ "struct.fields": []
+ }
+ },
+ {
+ "id": {
+ "array.len": 32,
+ "array.type": 3
+ },
+ "def": "builtin"
+ },
+ {
+ "id": "u8",
+ "def": "builtin"
+ },
+ {
+ "id": "u128",
+ "def": "builtin"
+ }
+ ]
+ },
+ "storage": {
+ "struct.type": 1,
+ "struct.fields": []
+ },
+ "contract": {
+ "name": 2,
+ "constructors": [
+ {
+ "name": 5,
+ "selector": "[\"0x5E\",\"0xBD\",\"0x88\",\"0xD6\"]",
+ "args": [],
+ "docs": []
+ }
+ ],
+ "messages": [
+ {
+ "name": 6,
+ "selector": "[\"0xEC\",\"0x9F\",\"0xA4\",\"0xF0\"]",
+ "mutates": false,
+ "args": [
+ {
+ "name": 7,
+ "type": {
+ "ty": 2,
+ "display_name": [
+ 8
+ ]
+ }
+ },
+ {
+ "name": 9,
+ "type": {
+ "ty": 4,
+ "display_name": [
+ 10
+ ]
+ }
+ }
+ ],
+ "return_type": null,
+ "docs": [
+ "Dispatches a `transfer` call to the Balances srml module"
+ ]
+ }
+ ],
+ "events": [],
+ "docs": []
+ }
+}
\ No newline at end of file
tests/src/.outdated/collision-tests/admVsOwnerChanges.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/collision-tests/admVsOwnerChanges.test.ts
@@ -0,0 +1,73 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ createItemExpectSuccess,
+ normalizeAccountId,
+ waitNewBlocks,
+} from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+let Alice: IKeyringPair;
+let Bob: IKeyringPair;
+let Ferdie: IKeyringPair;
+
+before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Bob = privateKey('//Bob');
+ Ferdie = privateKey('//Ferdie');
+ });
+});
+
+describe('Admin vs Owner changes token: ', () => {
+ // tslint:disable-next-line: max-line-length
+ it('The collection admin changes the owner of the token and in the same block the current owner transfers the token to another address ', async () => {
+
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const changeAdminTxBob = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
+ await submitTransactionAsync(Alice, changeAdminTxBob);
+ const changeAdminTxFerdie = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Ferdie.address));
+ await submitTransactionAsync(Bob, changeAdminTxFerdie);
+ const itemId = await createItemExpectSuccess(Ferdie, collectionId, 'NFT');
+
+ const changeOwner = api.tx.unique.transferFrom(normalizeAccountId(Ferdie.address), normalizeAccountId(Bob.address), collectionId, itemId, 1);
+ const approve = api.tx.unique.approve(normalizeAccountId(Bob.address), collectionId, itemId, 1);
+ const sendItem = api.tx.unique.transfer(normalizeAccountId(Alice.address), collectionId, itemId, 1);
+ await Promise.all([
+ changeOwner.signAndSend(Alice),
+ approve.signAndSend(Bob),
+ sendItem.signAndSend(Ferdie),
+ ]);
+ const itemBefore: any = await api.query.unique.nftItemList(collectionId, itemId);
+ expect(itemBefore.owner).not.to.be.eq(Bob.address);
+ await waitNewBlocks(2);
+ });
+ });
+});
+*/
\ No newline at end of file
tests/src/.outdated/collision-tests/admVsOwnerData.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/collision-tests/admVsOwnerData.test.ts
@@ -0,0 +1,69 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ createItemExpectSuccess,
+ normalizeAccountId,
+ waitNewBlocks,
+} from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+let Alice: IKeyringPair;
+let Bob: IKeyringPair;
+
+before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Bob = privateKey('//Bob');
+ });
+});
+
+describe('Admin vs Owner changes the data in the token: ', () => {
+ it('The collection admin changes the data in the token and in the same block the token owner also changes the data in it ', async () => {
+ await usingApi(async (api) => {
+ const AliceData = 1;
+ const BobData = 2;
+ const collectionId = await createCollectionExpectSuccess();
+ const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
+ await submitTransactionAsync(Alice, changeAdminTx);
+ const itemId = await createItemExpectSuccess(Bob, collectionId, 'NFT');
+ //
+ // tslint:disable-next-line: max-line-length
+ const AliceTx = api.tx.unique.setVariableMetaData(collectionId, itemId, AliceData.toString());
+ // tslint:disable-next-line: max-line-length
+ const BobTx = api.tx.unique.setVariableMetaData(collectionId, itemId, BobData.toString());
+ await Promise.all([
+ AliceTx.signAndSend(Alice),
+ BobTx.signAndSend(Bob),
+ ]);
+ const item: any = await api.query.unique.nftItemList(collectionId, itemId);
+ expect(item.variableData).not.to.be.eq(null); // Pseudo-random selection of one of two values
+ await waitNewBlocks(2);
+ });
+ });
+});
+*/
\ No newline at end of file
tests/src/.outdated/collision-tests/admVsOwnerTake.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/collision-tests/admVsOwnerTake.test.ts
@@ -0,0 +1,71 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ createItemExpectSuccess,
+ normalizeAccountId,
+ waitNewBlocks,
+} from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+let Alice: IKeyringPair;
+let Bob: IKeyringPair;
+let Ferdie: IKeyringPair;
+
+before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Bob = privateKey('//Bob');
+ Ferdie = privateKey('//Ferdie');
+ });
+});
+
+describe('Admin vs Owner take token: ', () => {
+ // tslint:disable-next-line: max-line-length
+ it('The collection admin burns the token and in the same block the token owner performs a transaction on it ', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
+ await submitTransactionAsync(Alice, changeAdminTx);
+ const itemId = await createItemExpectSuccess(Bob, collectionId, 'NFT');
+ //
+ const sendItem = api.tx.unique.transfer(normalizeAccountId(Ferdie.address), collectionId, itemId, 1);
+ const burnItem = api.tx.unique.burnItem(collectionId, itemId, 1);
+ await Promise.all([
+ sendItem.signAndSend(Bob),
+ burnItem.signAndSend(Alice),
+ ]);
+ await waitNewBlocks(2);
+ let itemBurn = false;
+ itemBurn = (await (api.query.unique.nftItemList(collectionId, itemId))).toJSON() as boolean;
+ // tslint:disable-next-line: no-unused-expression
+ expect(itemBurn).to.be.null;
+ await waitNewBlocks(2);
+ });
+ });
+});
+*/
\ No newline at end of file
tests/src/.outdated/collision-tests/adminDestroyCollection.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/collision-tests/adminDestroyCollection.test.ts
@@ -0,0 +1,70 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ normalizeAccountId,
+ waitNewBlocks,
+} from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+let Alice: IKeyringPair;
+let Bob: IKeyringPair;
+let Ferdie: IKeyringPair;
+
+before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Bob = privateKey('//Bob');
+ Ferdie = privateKey('//Ferdie');
+ });
+});
+
+describe('Deleting a collection while add address to allowlist: ', () => {
+ // tslint:disable-next-line: max-line-length
+ it('Adding an address to the collection allowlist in a block by the admin, and deleting the collection by the owner ', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
+ await submitTransactionAsync(Alice, changeAdminTx);
+ await waitNewBlocks(1);
+ //
+ const addAllowlistAdm = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(Ferdie.address));
+ const destroyCollection = api.tx.unique.destroyCollection(collectionId);
+ await Promise.all([
+ addAllowlistAdm.signAndSend(Bob),
+ destroyCollection.signAndSend(Alice),
+ ]);
+ await waitNewBlocks(1);
+ let allowList = false;
+ allowList = (await api.query.unique.allowList(collectionId, Ferdie.address)).toJSON() as boolean;
+ // tslint:disable-next-line: no-unused-expression
+ expect(allowList).to.be.false;
+ await waitNewBlocks(2);
+ });
+ });
+});
+*/
\ No newline at end of file
tests/src/.outdated/collision-tests/adminLimitsOff.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/collision-tests/adminLimitsOff.test.ts
@@ -0,0 +1,86 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ normalizeAccountId,
+ waitNewBlocks,
+} from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+let Alice: IKeyringPair;
+let Bob: IKeyringPair;
+let Ferdie: IKeyringPair;
+let Charlie: IKeyringPair;
+let Eve: IKeyringPair;
+let Dave: IKeyringPair;
+
+before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Bob = privateKey('//Bob');
+ Ferdie = privateKey('//Ferdie');
+ Charlie = privateKey('//Charlie');
+ Eve = privateKey('//Eve');
+ Dave = privateKey('//Dave');
+ });
+});
+
+describe('Admin limit exceeded collection: ', () => {
+ // tslint:disable-next-line: max-line-length
+ it('In one block, the owner and admin add new admins to the collection more than the limit ', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+
+ const chainAdminLimit = (api.consts.unique.collectionAdminsLimit as any).toNumber();
+ expect(chainAdminLimit).to.be.equal(5);
+
+ const changeAdminTx1 = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Eve.address));
+ await submitTransactionAsync(Alice, changeAdminTx1);
+ const changeAdminTx2 = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Dave.address));
+ await submitTransactionAsync(Alice, changeAdminTx2);
+ const changeAdminTx3 = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
+ await submitTransactionAsync(Alice, changeAdminTx3);
+
+ const addAdmOne = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Ferdie.address));
+ const addAdmTwo = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Charlie.address));
+ await Promise.all([
+ addAdmOne.signAndSend(Bob),
+ addAdmTwo.signAndSend(Alice),
+ ]);
+ await waitNewBlocks(2);
+ const changeAdminTx4 = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Alice.address));
+ await expect(submitTransactionExpectFailAsync(Alice, changeAdminTx4)).to.be.rejected;
+
+ const adminListAfterAddAdmin: any = (await api.query.unique.adminList(collectionId));
+ expect(adminListAfterAddAdmin).to.be.contains(normalizeAccountId(Eve.address));
+ expect(adminListAfterAddAdmin).to.be.contains(normalizeAccountId(Ferdie.address));
+ expect(adminListAfterAddAdmin).not.to.be.contains(normalizeAccountId(Alice.address));
+ await waitNewBlocks(2);
+ });
+ });
+});
+*/
\ No newline at end of file
tests/src/.outdated/collision-tests/adminRightsOff.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/collision-tests/adminRightsOff.test.ts
@@ -0,0 +1,69 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
+import { IKeyringPair } from '@polkadot/types/types';
+import BN from 'bn.js';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ normalizeAccountId,
+ waitNewBlocks,
+} from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+let Alice: IKeyringPair;
+let Bob: IKeyringPair;
+
+before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Bob = privateKey('//Bob');
+ });
+});
+
+describe('Deprivation of admin rights: ', () => {
+ // tslint:disable-next-line: max-line-length
+ it('In the block, the collection admin adds a token or changes data, and the collection owner deprives the admin of rights ', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
+ await submitTransactionAsync(Alice, changeAdminTx);
+ await waitNewBlocks(1);
+ const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];
+ const addItemAdm = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(Bob.address), args);
+ const removeAdm = api.tx.unique.removeCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
+ await Promise.all([
+ addItemAdm.signAndSend(Bob),
+ removeAdm.signAndSend(Alice),
+ ]);
+ await waitNewBlocks(2);
+ const itemsListIndex = await api.query.unique.itemListIndex(collectionId) as unknown as BN;
+ expect(itemsListIndex.toNumber()).to.be.equal(0);
+ const adminList: any = (await api.query.unique.adminList(collectionId));
+ expect(adminList).not.to.be.contains(normalizeAccountId(Bob.address));
+ await waitNewBlocks(2);
+ });
+ });
+});
+*/
\ No newline at end of file
tests/src/.outdated/collision-tests/setSponsorNewOwner.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/collision-tests/setSponsorNewOwner.test.ts
@@ -0,0 +1,67 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi from '../substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ setCollectionSponsorExpectSuccess,
+ waitNewBlocks,
+} from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+let Alice: IKeyringPair;
+let Bob: IKeyringPair;
+let Ferdie: IKeyringPair;
+
+before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Bob = privateKey('//Bob');
+ Ferdie = privateKey('//Ferdie');
+ });
+});
+
+describe('Sponsored with new owner ', () => {
+ // tslint:disable-next-line: max-line-length
+ it('Confirmation of sponsorship of a collection in a block with a change in the owner of the collection: ', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, Bob.address);
+ await waitNewBlocks(2);
+ const confirmSponsorship = api.tx.unique.confirmSponsorship(collectionId);
+ const changeCollectionOwner = api.tx.unique.changeCollectionOwner(collectionId, Ferdie.address);
+ await Promise.all([
+ confirmSponsorship.signAndSend(Bob),
+ changeCollectionOwner.signAndSend(Alice),
+ ]);
+ await waitNewBlocks(2);
+ const collection: any = (await api.query.unique.collectionById(collectionId)).toJSON();
+ expect(collection.sponsorship.confirmed).to.be.eq(Bob.address);
+ expect(collection.owner).to.be.eq(Ferdie.address);
+ await waitNewBlocks(2);
+ });
+ });
+});
+*/
\ No newline at end of file
tests/src/.outdated/collision-tests/sponsorPayments.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/collision-tests/sponsorPayments.test.ts
@@ -0,0 +1,76 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import { alicesPublicKey, bobsPublicKey } from '../accounts';
+import getBalance from '../substrate/get-balance';
+import privateKey from '../substrate/privateKey';
+import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
+import {
+ confirmSponsorshipExpectSuccess,
+ createCollectionExpectSuccess,
+ createItemExpectSuccess,
+ setCollectionSponsorExpectSuccess,
+ normalizeAccountId,
+ waitNewBlocks,
+} from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+let Alice: IKeyringPair;
+let Bob: IKeyringPair;
+
+before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Bob = privateKey('//Bob');
+ });
+});
+
+describe('Payment of commission if one block: ', () => {
+ // tslint:disable-next-line: max-line-length
+ it('Payment of commission if one block contains transactions for payment from the sponsor\'s balance and his (sponsor\'s) exclusion from the collection ', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const changeAdminTxBob = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
+ await submitTransactionAsync(Alice, changeAdminTxBob);
+ const itemId = await createItemExpectSuccess(Bob, collectionId, 'NFT');
+ await setCollectionSponsorExpectSuccess(collectionId, Bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
+ const sendItem = api.tx.unique.transfer(normalizeAccountId(Alice.address), collectionId, itemId, 1);
+ const revokeSponsor = api.tx.unique.removeCollectionSponsor(collectionId);
+ await Promise.all([
+ sendItem.signAndSend(Bob),
+ revokeSponsor.signAndSend(Alice),
+ ]);
+ const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
+ // tslint:disable-next-line:no-unused-expression
+ expect(alicesBalanceAfter === alicesBalanceBefore).to.be.true;
+ // tslint:disable-next-line:no-unused-expression
+ expect(bobsBalanceAfter === bobsBalanceBefore).to.be.true;
+ await waitNewBlocks(2);
+ });
+ });
+});
+*/
\ No newline at end of file
tests/src/.outdated/collision-tests/tokenLimitsOff.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/collision-tests/tokenLimitsOff.test.ts
@@ -0,0 +1,100 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
+import { IKeyringPair } from '@polkadot/types/types';
+import BN from 'bn.js';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
+import {
+ addToAllowListExpectSuccess,
+ createCollectionExpectSuccess,
+ getCreateItemResult,
+ setMintPermissionExpectSuccess,
+ normalizeAccountId,
+ waitNewBlocks,
+} from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+let Alice: IKeyringPair;
+let Bob: IKeyringPair;
+let Ferdie: IKeyringPair;
+
+const accountTokenOwnershipLimit = 4;
+const sponsoredMintSize = 4294967295;
+const tokenLimit = 4;
+const sponsorTimeout = 14400;
+const ownerCanTransfer = false;
+const ownerCanDestroy = false;
+
+before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Bob = privateKey('//Bob');
+ Ferdie = privateKey('//Ferdie');
+ });
+});
+
+describe('Token limit exceeded collection: ', () => {
+ // tslint:disable-next-line: max-line-length
+ it('The number of tokens created in the collection from different addresses exceeds the allowed collection limit ', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setMintPermissionExpectSuccess(Alice, collectionId, true);
+ await addToAllowListExpectSuccess(Alice, collectionId, Ferdie.address);
+ await addToAllowListExpectSuccess(Alice, collectionId, Bob.address);
+ const setCollectionLim = api.tx.unique.setCollectionLimits(
+ collectionId,
+ {
+ accountTokenOwnershipLimit,
+ sponsoredMintSize,
+ tokenLimit,
+ // tslint:disable-next-line: object-literal-sort-keys
+ sponsorTimeout,
+ ownerCanTransfer,
+ ownerCanDestroy,
+ },
+ );
+ const subTx = await submitTransactionAsync(Alice, setCollectionLim);
+ const subTxTesult = getCreateItemResult(subTx);
+ // tslint:disable-next-line:no-unused-expression
+ expect(subTxTesult.success).to.be.true;
+ await waitNewBlocks(2);
+
+ const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];
+ const mintItemOne = api.tx.unique
+ .createMultipleItems(collectionId, normalizeAccountId(Ferdie.address), args);
+ const mintItemTwo = api.tx.unique
+ .createMultipleItems(collectionId, normalizeAccountId(Bob.address), args);
+ await Promise.all([
+ mintItemOne.signAndSend(Ferdie),
+ mintItemTwo.signAndSend(Bob),
+ ]);
+ await waitNewBlocks(2);
+ const itemsListIndexAfter = await api.query.unique.itemListIndex(collectionId) as unknown as BN;
+ expect(itemsListIndexAfter.toNumber()).to.be.equal(3);
+ // TokenLimit = 4. The first transaction is successful. The second should fail.
+ await waitNewBlocks(2);
+ });
+ });
+});
+*/
tests/src/.outdated/collision-tests/turnsOffMinting.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/collision-tests/turnsOffMinting.test.ts
@@ -0,0 +1,68 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi from '../substrate/substrate-api';
+import {
+ addToAllowListExpectSuccess,
+ createCollectionExpectSuccess,
+ setMintPermissionExpectSuccess,
+ normalizeAccountId,
+ waitNewBlocks,
+} from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+let Alice: IKeyringPair;
+let Ferdie: IKeyringPair;
+
+before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Ferdie = privateKey('//Ferdie');
+ });
+});
+
+describe('Turns off minting mode: ', () => {
+ // tslint:disable-next-line: max-line-length
+ it('The collection owner turns off minting mode and there are minting transactions in the same block ', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setMintPermissionExpectSuccess(Alice, collectionId, true);
+ await addToAllowListExpectSuccess(Alice, collectionId, Ferdie.address);
+
+ const mintItem = api.tx.unique.createItem(collectionId, normalizeAccountId(Ferdie.address), 'NFT');
+ const offMinting = api.tx.unique.setMintPermission(collectionId, false);
+ await Promise.all([
+ mintItem.signAndSend(Ferdie),
+ offMinting.signAndSend(Alice),
+ ]);
+ let itemList = false;
+ itemList = (await (api.query.unique.nftItemList(collectionId, mintItem))).toJSON() as boolean;
+ // tslint:disable-next-line: no-unused-expression
+ expect(itemList).to.be.null;
+ await waitNewBlocks(2);
+ });
+ });
+});
+*/
\ No newline at end of file
tests/src/.outdated/contracts.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/contracts.test.ts
@@ -0,0 +1,236 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
+import fs from 'fs';
+import {Abi, ContractPromise as Contract} from '@polkadot/api-contract';
+import {deployFlipper, getFlipValue, deployTransferContract} from '../deprecated-helpers/contracthelpers';
+
+import {
+ addToAllowListExpectSuccess,
+ approveExpectSuccess,
+ createCollectionExpectSuccess,
+ createItemExpectSuccess,
+ enablePublicMintingExpectSuccess,
+ enableAllowListExpectSuccess,
+ getGenericResult,
+ normalizeAccountId,
+ isAllowlisted,
+ transferFromExpectSuccess,
+ getTokenOwner,
+} from '../deprecated-helpers/helpers';
+
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+const value = 0;
+const gasLimit = 9000n * 1000000n;
+const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';
+
+// todo:playgrounds skipped ~ postponed
+describe.skip('Contracts', () => {
+ it('Can deploy smart contract Flipper, instantiate it and call it\'s get and flip messages.', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
+ const initialGetResponse = await getFlipValue(contract, deployer);
+
+ const bob = privateKeyWrapper('//Bob');
+ const flip = contract.tx.flip({value, gasLimit});
+ await submitTransactionAsync(bob, flip);
+
+ const afterFlipGetResponse = await getFlipValue(contract, deployer);
+ expect(afterFlipGetResponse).not.to.be.eq(initialGetResponse, 'Flipping should change value.');
+ });
+ });
+
+ it('Can initialize contract instance', async () => {
+ await usingApi(async (api) => {
+ const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));
+ const abi = new Abi(metadata);
+ const newContractInstance = new Contract(api, abi, marketContractAddress);
+ expect(newContractInstance).to.have.property('address');
+ expect(newContractInstance.address.toString()).to.equal(marketContractAddress);
+ });
+ });
+});
+
+describe.skip('Chain extensions', () => {
+ it('Transfer CE', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const alice = privateKeyWrapper('//Alice');
+ const bob = privateKeyWrapper('//Bob');
+
+ // Prep work
+ const collectionId = await createCollectionExpectSuccess();
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+ const [contract] = await deployTransferContract(api, privateKeyWrapper);
+ const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, contract.address);
+ await submitTransactionAsync(alice, changeAdminTx);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
+
+ // Transfer
+ const transferTx = contract.tx.transfer({value, gasLimit}, bob.address, collectionId, tokenId, 1);
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));
+ });
+ });
+
+ it('Mint CE', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const alice = privateKeyWrapper('//Alice');
+ const bob = privateKeyWrapper('//Bob');
+
+ const collectionId = await createCollectionExpectSuccess();
+ const [contract] = await deployTransferContract(api, privateKeyWrapper);
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, contract.address);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+
+ const transferTx = contract.tx.createItem({value, gasLimit}, bob.address, collectionId, {Nft: {const_data: '0x010203'}});
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ const tokensAfter = (await api.query.unique.nftItemList.entries(collectionId)).map((kv: any) => kv[1].toJSON());
+ expect(tokensAfter).to.be.deep.equal([
+ {
+ owner: bob.address,
+ constData: '0x010203',
+ },
+ ]);
+ });
+ });
+
+ it('Bulk mint CE', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const alice = privateKeyWrapper('//Alice');
+ const bob = privateKeyWrapper('//Bob');
+
+ const collectionId = await createCollectionExpectSuccess();
+ const [contract] = await deployTransferContract(api, privateKeyWrapper);
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, contract.address);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+
+ const transferTx = contract.tx.createMultipleItems({value, gasLimit}, bob.address, collectionId, [
+ {NFT: {/*const_data: '0x010203'*/}},
+ {NFT: {/*const_data: '0x010204'*/}},
+ {NFT: {/*const_data: '0x010205'*/}},
+ ]);
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ const tokensAfter: any = (await api.query.unique.nftItemList.entries(collectionId) as any)
+ .map((kv: any) => kv[1].toJSON())
+ .sort((a: any, b: any) => a.constData.localeCompare(b.constData));
+ expect(tokensAfter).to.be.deep.equal([
+ {
+ Owner: bob.address,
+ //ConstData: '0x010203',
+ },
+ {
+ Owner: bob.address,
+ //ConstData: '0x010204',
+ },
+ {
+ Owner: bob.address,
+ //ConstData: '0x010205',
+ },
+ ]);
+ });
+ });
+
+ it('Approve CE', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const alice = privateKeyWrapper('//Alice');
+ const bob = privateKeyWrapper('//Bob');
+ const charlie = privateKeyWrapper('//Charlie');
+
+ const collectionId = await createCollectionExpectSuccess();
+ const [contract] = await deployTransferContract(api, privateKeyWrapper);
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());
+
+ const transferTx = contract.tx.approve({value, gasLimit}, bob.address, collectionId, tokenId, 1);
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ await transferFromExpectSuccess(collectionId, tokenId, bob, normalizeAccountId(contract.address.toString()), charlie, 1, 'NFT');
+ });
+ });
+
+ it('TransferFrom CE', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const alice = privateKeyWrapper('//Alice');
+ const bob = privateKeyWrapper('//Bob');
+ const charlie = privateKeyWrapper('//Charlie');
+
+ const collectionId = await createCollectionExpectSuccess();
+ const [contract] = await deployTransferContract(api, privateKeyWrapper);
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+ await approveExpectSuccess(collectionId, tokenId, bob, contract.address.toString(), 1);
+
+ const transferTx = contract.tx.transferFrom({value, gasLimit}, bob.address, charlie.address, collectionId, tokenId, 1);
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ const token: any = (await api.query.unique.nftItemList(collectionId, tokenId) as any).unwrap();
+ expect(token.owner.toString()).to.be.equal(charlie.address);
+ });
+ });
+
+ it('ToggleAllowList CE', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const alice = privateKeyWrapper('//Alice');
+ const bob = privateKeyWrapper('//Bob');
+
+ const collectionId = await createCollectionExpectSuccess();
+ const [contract] = await deployTransferContract(api, privateKeyWrapper);
+ const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, contract.address);
+ await submitTransactionAsync(alice, changeAdminTx);
+
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
+
+ {
+ const transferTx = contract.tx.toggleAllowList({value, gasLimit}, collectionId, bob.address, true);
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.true;
+ }
+ {
+ const transferTx = contract.tx.toggleAllowList({value, gasLimit}, collectionId, bob.address, false);
+ const events = await submitTransactionAsync(alice, transferTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
+ }
+ });
+ });
+});
tests/src/.outdated/enableContractSponsoring.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/enableContractSponsoring.test.ts
@@ -0,0 +1,102 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import usingApi from '../substrate/substrate-api';
+import {deployFlipper, getFlipValue, toggleFlipValueExpectSuccess} from '../deprecated-helpers/contracthelpers';
+import {
+ enableContractSponsoringExpectFailure,
+ enableContractSponsoringExpectSuccess,
+ findUnusedAddress,
+ setContractSponsoringRateLimitExpectSuccess,
+} from '../deprecated-helpers/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+// todo:playgrounds skipped ~ postponed
+describe.skip('Integration Test enableContractSponsoring', () => {
+ it('ensure tx fee is paid from endowment', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const user = await findUnusedAddress(api, privateKeyWrapper);
+
+ const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
+ await setContractSponsoringRateLimitExpectSuccess(deployer, flipper.address, 1);
+ await toggleFlipValueExpectSuccess(user, flipper);
+
+ expect(await getFlipValue(flipper, deployer)).to.be.false;
+ });
+ });
+
+ it('ensure it can be enabled twice', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
+
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
+ });
+ });
+
+ it('ensure it can be disabled twice', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
+
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, false);
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, false);
+ });
+ });
+
+ it('ensure it can be re-enabled', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
+
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, false);
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
+ });
+ });
+
+});
+
+describe.skip('Negative Integration Test enableContractSponsoring', () => {
+ let alice: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ });
+ });
+
+ it('fails when called for non-contract address', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const user = await findUnusedAddress(api, privateKeyWrapper);
+
+ await enableContractSponsoringExpectFailure(alice, user.address, true);
+ });
+ });
+
+ it('fails when called by non-owning user', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [flipper] = await deployFlipper(api, privateKeyWrapper);
+
+ await enableContractSponsoringExpectFailure(alice, flipper.address, true);
+ });
+ });
+});
tests/src/.outdated/eth/scheduling.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/eth/scheduling.test.ts
@@ -0,0 +1,59 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {expect} from 'chai';
+import {createEthAccountWithBalance, deployFlipper, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from '../../deprecated-helpers/eth/helpers';
+import {scheduleExpectSuccess, waitNewBlocks, requirePallets, Pallets} from '../../deprecated-helpers/helpers';
+
+// TODO mrshiposha update this test in #581
+describe.skip('Scheduing EVM smart contracts', () => {
+ before(async function() {
+ await requirePallets(this, [Pallets.Scheduler]);
+ });
+
+ itWeb3('Successfully schedules and periodically executes an EVM contract', async ({api, web3, privateKeyWrapper}) => {
+ const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ const flipper = await deployFlipper(web3, deployer);
+ const initialValue = await flipper.methods.getValue().call();
+ const alice = privateKeyWrapper('//Alice');
+ await transferBalanceToEth(api, alice, subToEth(alice.address));
+
+ {
+ const tx = api.tx.evm.call(
+ subToEth(alice.address),
+ flipper.options.address,
+ flipper.methods.flip().encodeABI(),
+ '0',
+ GAS_ARGS.gas,
+ await web3.eth.getGasPrice(),
+ null,
+ null,
+ [],
+ );
+ const waitForBlocks = 4;
+ const periodBlocks = 2;
+
+ await scheduleExpectSuccess(tx, alice, waitForBlocks, '0x' + '0'.repeat(32), periodBlocks, 2);
+ expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+
+ await waitNewBlocks(waitForBlocks - 1);
+ expect(await flipper.methods.getValue().call()).to.be.not.equal(initialValue);
+
+ await waitNewBlocks(periodBlocks);
+ expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+ }
+ });
+});
tests/src/.outdated/flipper/flipper.wasmdiffbeforeafterbothbinary blob — no preview
tests/src/.outdated/flipper/metadata.jsondiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/flipper/metadata.json
@@ -0,0 +1,110 @@
+{
+ "metadataVersion": "0.1.0",
+ "source": {
+ "hash": "0x5b02ceadaacee8408d3c6496394847092c099bcb897221dbe8d22c16d372fa17",
+ "language": "ink! 3.0.0-rc2",
+ "compiler": "rustc 1.51.0-nightly"
+ },
+ "contract": {
+ "name": "flipper",
+ "version": "0.1.0",
+ "authors": [
+ "[your_name] <[your_email]>"
+ ]
+ },
+ "spec": {
+ "constructors": [
+ {
+ "args": [
+ {
+ "name": "init_value",
+ "type": {
+ "displayName": [
+ "bool"
+ ],
+ "type": 1
+ }
+ }
+ ],
+ "docs": [
+ " Constructor that initializes the `bool` value to the given `init_value`."
+ ],
+ "name": [
+ "new"
+ ],
+ "selector": "0xd183512b"
+ },
+ {
+ "args": [],
+ "docs": [
+ " Constructor that initializes the `bool` value to `false`.",
+ "",
+ " Constructors can delegate to other constructors."
+ ],
+ "name": [
+ "default"
+ ],
+ "selector": "0x6a3712e2"
+ }
+ ],
+ "docs": [],
+ "events": [],
+ "messages": [
+ {
+ "args": [],
+ "docs": [
+ " A message that can be called on instantiated contracts.",
+ " This one flips the value of the stored `bool` from `true`",
+ " to `false` and vice versa."
+ ],
+ "mutates": true,
+ "name": [
+ "flip"
+ ],
+ "payable": false,
+ "returnType": null,
+ "selector": "0xc096a5f3"
+ },
+ {
+ "args": [],
+ "docs": [
+ " Simply returns the current value of our `bool`."
+ ],
+ "mutates": false,
+ "name": [
+ "get"
+ ],
+ "payable": false,
+ "returnType": {
+ "displayName": [
+ "bool"
+ ],
+ "type": 1
+ },
+ "selector": "0x1e5ca456"
+ }
+ ]
+ },
+ "storage": {
+ "struct": {
+ "fields": [
+ {
+ "layout": {
+ "cell": {
+ "key": "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "ty": 1
+ }
+ },
+ "name": "value"
+ }
+ ]
+ }
+ },
+ "types": [
+ {
+ "def": {
+ "primitive": "bool"
+ }
+ }
+ ]
+}
\ No newline at end of file
tests/src/.outdated/load_test_sc/loadtester.wasmdiffbeforeafterbothbinary blob — no preview
tests/src/.outdated/load_test_sc/metadata.jsondiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/load_test_sc/metadata.json
@@ -0,0 +1,125 @@
+{
+ "metadataVersion": "0.1.0",
+ "source": {
+ "hash": "0x168cc3cba9657ad3950fb506e568751f99b90fb097685107f6101675662a8303",
+ "language": "ink! 3.0.0-rc2",
+ "compiler": "rustc 1.49.0-nightly"
+ },
+ "contract": {
+ "name": "loadtester",
+ "version": "0.1.0",
+ "authors": [
+ "[your_name] <[your_email]>"
+ ]
+ },
+ "spec": {
+ "constructors": [
+ {
+ "args": [],
+ "docs": [],
+ "name": [
+ "new"
+ ],
+ "selector": "0xd183512b"
+ }
+ ],
+ "docs": [],
+ "events": [],
+ "messages": [
+ {
+ "args": [
+ {
+ "name": "count",
+ "type": {
+ "displayName": [
+ "u64"
+ ],
+ "type": 2
+ }
+ }
+ ],
+ "docs": [],
+ "mutates": true,
+ "name": [
+ "bloat"
+ ],
+ "payable": false,
+ "returnType": null,
+ "selector": "0x49891c2a"
+ },
+ {
+ "args": [],
+ "docs": [],
+ "mutates": false,
+ "name": [
+ "get"
+ ],
+ "payable": false,
+ "returnType": {
+ "displayName": [
+ "u128"
+ ],
+ "type": 3
+ },
+ "selector": "0x1e5ca456"
+ }
+ ]
+ },
+ "storage": {
+ "struct": {
+ "fields": [
+ {
+ "layout": {
+ "struct": {
+ "fields": [
+ {
+ "layout": {
+ "cell": {
+ "key": "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "ty": 1
+ }
+ },
+ "name": "len"
+ },
+ {
+ "layout": {
+ "array": {
+ "cellsPerElem": 1,
+ "layout": {
+ "cell": {
+ "key": "0x0000000001000000000000000000000000000000000000000000000000000000",
+ "ty": 2
+ }
+ },
+ "len": 4294967295,
+ "offset": "0x0100000000000000000000000000000000000000000000000000000000000000"
+ }
+ },
+ "name": "elems"
+ }
+ ]
+ }
+ },
+ "name": "vector"
+ }
+ ]
+ }
+ },
+ "types": [
+ {
+ "def": {
+ "primitive": "u32"
+ }
+ },
+ {
+ "def": {
+ "primitive": "u64"
+ }
+ },
+ {
+ "def": {
+ "primitive": "u128"
+ }
+ }
+ ]
+}
\ No newline at end of file
tests/src/.outdated/overflow.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/overflow.test.ts
@@ -0,0 +1,73 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import usingApi from '../substrate/substrate-api';
+import {approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, getAllowance, getBalance, transferExpectFailure, transferExpectSuccess, transferFromExpectFail, transferFromExpectSuccess, U128_MAX} from '../deprecated-helpers/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+// todo:playgrounds skipped ~ postponed
+describe.skip('Integration Test fungible overflows', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ bob = privateKeyWrapper('//Bob');
+ charlie = privateKeyWrapper('//Charlie');
+ });
+ });
+
+ it('fails when overflows on transfer', async () => {
+ await usingApi(async api => {
+ const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+
+ await createFungibleItemExpectSuccess(alice, fungibleCollectionId, {Value: U128_MAX});
+ await transferExpectSuccess(fungibleCollectionId, 0, alice, bob, U128_MAX, 'Fungible');
+
+ await createFungibleItemExpectSuccess(alice, fungibleCollectionId, {Value: 1n});
+ await transferExpectFailure(fungibleCollectionId, 0, alice, bob, 1);
+
+ expect(await getBalance(api, fungibleCollectionId, alice.address, 0)).to.equal(1n);
+ expect(await getBalance(api, fungibleCollectionId, bob.address, 0)).to.equal(U128_MAX);
+ });
+ });
+
+ it('fails when overflows on transferFrom', async () => {
+ await usingApi(async api => {
+ const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+ await createFungibleItemExpectSuccess(alice, fungibleCollectionId, {Value: U128_MAX});
+ await approveExpectSuccess(fungibleCollectionId, 0, alice, bob.address, U128_MAX);
+ await transferFromExpectSuccess(fungibleCollectionId, 0, bob, alice, charlie, U128_MAX, 'Fungible');
+
+ expect(await getBalance(api, fungibleCollectionId, charlie.address, 0)).to.equal(U128_MAX);
+ expect(await getAllowance(api, fungibleCollectionId, alice.address, bob.address, 0)).to.equal(0n);
+
+ await createFungibleItemExpectSuccess(alice, fungibleCollectionId, {Value: U128_MAX});
+ await approveExpectSuccess(fungibleCollectionId, 0, alice, bob.address, 1n);
+ await transferFromExpectFail(fungibleCollectionId, 0, bob, alice, charlie, 1);
+
+ expect(await getBalance(api, fungibleCollectionId, charlie.address, 0)).to.equal(U128_MAX);
+ expect(await getAllowance(api, fungibleCollectionId, alice.address, bob.address, 0)).to.equal(1n);
+ });
+ });
+});
tests/src/.outdated/removeFromContractAllowList.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/removeFromContractAllowList.test.ts
@@ -0,0 +1,92 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import usingApi from '../substrate/substrate-api';
+import {deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess} from '../deprecated-helpers/contracthelpers';
+import {addToContractAllowListExpectSuccess, isAllowlistedInContract, removeFromContractAllowListExpectFailure, removeFromContractAllowListExpectSuccess, toggleContractAllowlistExpectSuccess} from '../deprecated-helpers/helpers';
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect} from 'chai';
+
+// todo:playgrounds skipped again
+describe.skip('Integration Test removeFromContractAllowList', () => {
+ let bob: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ bob = privateKeyWrapper('//Bob');
+ });
+ });
+
+ it('user is no longer allowlisted after removal', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
+
+ await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+
+ expect(await isAllowlistedInContract(flipper.address, bob.address)).to.be.false;
+ });
+ });
+
+ it('user can\'t execute contract after removal', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
+ await toggleContractAllowlistExpectSuccess(deployer, flipper.address.toString(), true);
+
+ await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ await toggleFlipValueExpectSuccess(bob, flipper);
+
+ await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ await toggleFlipValueExpectFailure(bob, flipper);
+ });
+ });
+
+ it('can be called twice', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
+
+ await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ });
+ });
+});
+
+describe.skip('Negative Integration Test removeFromContractAllowList', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ bob = privateKeyWrapper('//Bob');
+ });
+ });
+
+ it('fails when called with non-contract address', async () => {
+ await usingApi(async () => {
+ await removeFromContractAllowListExpectFailure(alice, alice.address, bob.address);
+ });
+ });
+
+ it('fails when executed by non owner', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [flipper] = await deployFlipper(api, privateKeyWrapper);
+
+ await removeFromContractAllowListExpectFailure(alice, flipper.address.toString(), bob.address);
+ });
+ });
+});
tests/src/.outdated/scheduler.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/scheduler.test.ts
@@ -0,0 +1,210 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import chai, {expect} from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import {
+ default as usingApi,
+ submitTransactionAsync,
+} from '../substrate/substrate-api';
+import {
+ createItemExpectSuccess,
+ createCollectionExpectSuccess,
+ scheduleTransferExpectSuccess,
+ scheduleTransferAndWaitExpectSuccess,
+ setCollectionSponsorExpectSuccess,
+ confirmSponsorshipExpectSuccess,
+ findUnusedAddress,
+ UNIQUE,
+ enablePublicMintingExpectSuccess,
+ addToAllowListExpectSuccess,
+ waitNewBlocks,
+ normalizeAccountId,
+ getTokenOwner,
+ getGenericResult,
+ scheduleTransferFundsPeriodicExpectSuccess,
+ getFreeBalance,
+ confirmSponsorshipByKeyExpectSuccess,
+ scheduleExpectFailure,
+} from '../deprecated-helpers/helpers';
+import {IKeyringPair} from '@polkadot/types/types';
+
+chai.use(chaiAsPromised);
+
+// todo:playgrounds skipped ~ postponed
+describe.skip('Scheduling token and balance transfers', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let scheduledIdBase: string;
+ let scheduledIdSlider: number;
+
+ before(async() => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ bob = privateKeyWrapper('//Bob');
+ });
+
+ scheduledIdBase = '0x' + '0'.repeat(31);
+ scheduledIdSlider = 0;
+ });
+
+ // Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.
+ function makeScheduledId(): string {
+ return scheduledIdBase + ((scheduledIdSlider++) % 10);
+ }
+
+ it('Can schedule a transfer of an owned token with delay', async () => {
+ await usingApi(async () => {
+ const nftCollectionId = await createCollectionExpectSuccess();
+ const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
+ await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);
+ await confirmSponsorshipExpectSuccess(nftCollectionId);
+
+ await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4, makeScheduledId());
+ });
+ });
+
+ it('Can transfer funds periodically', async () => {
+ await usingApi(async () => {
+ const waitForBlocks = 4;
+ const period = 2;
+ await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, makeScheduledId(), period, 2);
+ const bobsBalanceBefore = await getFreeBalance(bob);
+
+ // discounting already waited-for operations
+ await waitNewBlocks(waitForBlocks - 2);
+ const bobsBalanceAfterFirst = await getFreeBalance(bob);
+ expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
+
+ await waitNewBlocks(period);
+ const bobsBalanceAfterSecond = await getFreeBalance(bob);
+ expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst).to.be.true;
+ });
+ });
+
+ it('Can sponsor scheduling a transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ await usingApi(async () => {
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ const bobBalanceBefore = await getFreeBalance(bob);
+ const waitForBlocks = 4;
+ // no need to wait to check, fees must be deducted on scheduling, immediately
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());
+ const bobBalanceAfter = await getFreeBalance(bob);
+ // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+ expect(bobBalanceAfter < bobBalanceBefore).to.be.true;
+ // wait for sequentiality matters
+ await waitNewBlocks(waitForBlocks - 1);
+ });
+ });
+
+ it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Find an empty, unused account
+ const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+
+ const collectionId = await createCollectionExpectSuccess();
+
+ // Add zeroBalance address to allow list
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ // Grace zeroBalance with money, enough to cover future transactions
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ // Mint a fresh NFT
+ const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+
+ // Schedule transfer of the NFT a few blocks ahead
+ const waitForBlocks = 5;
+ await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, makeScheduledId());
+
+ // Get rid of the account's funds before the scheduled transaction takes place
+ const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);
+ const events = await submitTransactionAsync(zeroBalance, balanceTx2);
+ expect(getGenericResult(events).success).to.be.true;
+ /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;*/
+
+ // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
+ await waitNewBlocks(waitForBlocks - 3);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
+ });
+ });
+
+ it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+
+ await usingApi(async (api, privateKeyWrapper) => {
+ const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);
+ await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);
+
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ const waitForBlocks = 5;
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());
+
+ const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;
+
+ // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
+ await waitNewBlocks(waitForBlocks - 3);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
+ });
+ });
+
+ it.skip('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ await usingApi(async (api, privateKeyWrapper) => {
+ const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ const bobBalanceBefore = await getFreeBalance(bob);
+
+ const createData = {nft: {const_data: [], variable_data: []}};
+ const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);
+
+ /*const badTransaction = async function () {
+ await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
+ };
+ await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/
+
+ await scheduleExpectFailure(creationTx, zeroBalance, 3, makeScheduledId(), 1, 3);
+
+ expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);
+ });
+ });
+});
tests/src/.outdated/setChainLimits.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/setChainLimits.test.ts
@@ -0,0 +1,64 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import usingApi from '../substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ addCollectionAdminExpectSuccess,
+ setChainLimitsExpectFailure,
+ IChainLimits,
+} from '../deprecated-helpers/helpers';
+
+// todo:playgrounds skipped ~ postponed
+describe.skip('Negative Integration Test setChainLimits', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let dave: IKeyringPair;
+ let limits: IChainLimits;
+
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ bob = privateKeyWrapper('//Bob');
+ dave = privateKeyWrapper('//Dave');
+ limits = {
+ collectionNumbersLimit : 1,
+ accountTokenOwnershipLimit: 1,
+ collectionsAdminsLimit: 1,
+ customDataLimit: 1,
+ nftSponsorTransferTimeout: 1,
+ fungibleSponsorTransferTimeout: 1,
+ refungibleSponsorTransferTimeout: 1,
+ };
+ });
+ });
+
+ it('Collection owner cannot set chain limits', async () => {
+ await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ await setChainLimitsExpectFailure(alice, limits);
+ });
+
+ it('Collection admin cannot set chain limits', async () => {
+ const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await setChainLimitsExpectFailure(bob, limits);
+ });
+
+ it('Regular user cannot set chain limits', async () => {
+ await setChainLimitsExpectFailure(dave, limits);
+ });
+});
tests/src/.outdated/setContractSponsoringRateLimit.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/setContractSponsoringRateLimit.test.ts
@@ -0,0 +1,80 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import usingApi from '../substrate/substrate-api';
+import waitNewBlocks from '../substrate/wait-new-blocks';
+import {deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess} from '../deprecated-helpers/contracthelpers';
+import {
+ enableContractSponsoringExpectSuccess,
+ findUnusedAddress,
+ setContractSponsoringRateLimitExpectFailure,
+ setContractSponsoringRateLimitExpectSuccess,
+} from '../deprecated-helpers/helpers';
+
+// todo:playgrounds skipped~postponed test
+describe.skip('Integration Test setContractSponsoringRateLimit', () => {
+ it('ensure sponsored contract can\'t be called twice without pause for free', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const user = await findUnusedAddress(api, privateKeyWrapper);
+
+ const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
+ await setContractSponsoringRateLimitExpectSuccess(deployer, flipper.address, 10);
+ await toggleFlipValueExpectSuccess(user, flipper);
+ await toggleFlipValueExpectFailure(user, flipper);
+ });
+ });
+
+ it('ensure sponsored contract can be called twice with pause for free', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const user = await findUnusedAddress(api, privateKeyWrapper);
+
+ const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
+ await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
+ await setContractSponsoringRateLimitExpectSuccess(deployer, flipper.address, 1);
+ await toggleFlipValueExpectSuccess(user, flipper);
+ await waitNewBlocks(api, 1);
+ await toggleFlipValueExpectSuccess(user, flipper);
+ });
+ });
+});
+
+describe.skip('Negative Integration Test setContractSponsoringRateLimit', () => {
+ let alice: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ });
+ });
+
+ it('fails when called for non-contract address', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const user = await findUnusedAddress(api, privateKeyWrapper);
+
+ await setContractSponsoringRateLimitExpectFailure(alice, user.address, 1);
+ });
+ });
+
+ it('fails when called by non-owning user', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [flipper] = await deployFlipper(api, privateKeyWrapper);
+
+ await setContractSponsoringRateLimitExpectFailure(alice, flipper.address, 1);
+ });
+ });
+});
tests/src/.outdated/toggleContractAllowList.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/toggleContractAllowList.test.ts
@@ -0,0 +1,167 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import usingApi, {submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
+import {
+ deployFlipper,
+ getFlipValue,
+} from '../deprecated-helpers/contracthelpers';
+import {
+ getGenericResult,
+} from '../deprecated-helpers/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+const value = 0;
+const gasLimit = 3000n * 1000000n;
+
+// todo:playgrounds skipped ~ postpone
+describe.skip('Integration Test toggleContractAllowList', () => {
+
+ it('Enable allow list contract mode', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
+
+ const enabledBefore = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
+ const enableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, true);
+ const enableEvents = await submitTransactionAsync(deployer, enableAllowListTx);
+ const enabled = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
+
+ expect(getGenericResult(enableEvents).success).to.be.true;
+ expect(enabledBefore).to.be.false;
+ expect(enabled).to.be.true;
+ });
+ });
+
+ it('Only allowlisted account can call contract', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const bob = privateKeyWrapper('//Bob');
+
+ const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
+
+ let flipValueBefore = await getFlipValue(contract, deployer);
+ const flip = contract.tx.flip({value, gasLimit});
+ await submitTransactionAsync(bob, flip);
+ const flipValueAfter = await getFlipValue(contract,deployer);
+ expect(flipValueAfter).to.be.eq(!flipValueBefore, 'Anyone can call new contract.');
+
+ const deployerCanFlip = async () => {
+ const flipValueBefore = await getFlipValue(contract, deployer);
+ const deployerFlip = contract.tx.flip({value, gasLimit});
+ await submitTransactionAsync(deployer, deployerFlip);
+ const aliceFlip1Response = await getFlipValue(contract, deployer);
+ expect(aliceFlip1Response).to.be.eq(!flipValueBefore, 'Deployer always can flip.');
+ };
+ await deployerCanFlip();
+
+ flipValueBefore = await getFlipValue(contract, deployer);
+ const enableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, true);
+ await submitTransactionAsync(deployer, enableAllowListTx);
+ const flipWithEnabledAllowList = contract.tx.flip({value, gasLimit});
+ await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledAllowList)).to.be.rejected;
+ const flipValueAfterEnableAllowList = await getFlipValue(contract, deployer);
+ expect(flipValueAfterEnableAllowList).to.be.eq(flipValueBefore, 'Enabling allowlist doesn\'t make it possible to call contract for everyone.');
+
+ await deployerCanFlip();
+
+ flipValueBefore = await getFlipValue(contract, deployer);
+ const addBobToAllowListTx = api.tx.unique.addToContractAllowList(contract.address, bob.address);
+ await submitTransactionAsync(deployer, addBobToAllowListTx);
+ const flipWithAllowlistedBob = contract.tx.flip({value, gasLimit});
+ await submitTransactionAsync(bob, flipWithAllowlistedBob);
+ const flipAfterAllowListed = await getFlipValue(contract,deployer);
+ expect(flipAfterAllowListed).to.be.eq(!flipValueBefore, 'Bob was allowlisted, now he can flip.');
+
+ await deployerCanFlip();
+
+ flipValueBefore = await getFlipValue(contract, deployer);
+ const removeBobFromAllowListTx = api.tx.unique.removeFromContractAllowList(contract.address, bob.address);
+ await submitTransactionAsync(deployer, removeBobFromAllowListTx);
+ const bobRemoved = contract.tx.flip({value, gasLimit});
+ await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;
+ const afterBobRemoved = await getFlipValue(contract, deployer);
+ expect(afterBobRemoved).to.be.eq(flipValueBefore, 'Bob can\'t call contract, now when he is removeed from allow list.');
+
+ await deployerCanFlip();
+
+ flipValueBefore = await getFlipValue(contract, deployer);
+ const disableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, false);
+ await submitTransactionAsync(deployer, disableAllowListTx);
+ const allowListDisabledFlip = contract.tx.flip({value, gasLimit});
+ await submitTransactionAsync(bob, allowListDisabledFlip);
+ const afterAllowListDisabled = await getFlipValue(contract,deployer);
+ expect(afterAllowListDisabled).to.be.eq(!flipValueBefore, 'Anyone can call contract with disabled allowlist.');
+
+ });
+ });
+
+ it('Enabling allow list repeatedly should not produce errors', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
+
+ const enabledBefore = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
+ const enableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, true);
+ const enableEvents = await submitTransactionAsync(deployer, enableAllowListTx);
+ const enabled = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
+ const enableAgainEvents = await submitTransactionAsync(deployer, enableAllowListTx);
+ const enabledAgain = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
+
+ expect(getGenericResult(enableEvents).success).to.be.true;
+ expect(enabledBefore).to.be.false;
+ expect(enabled).to.be.true;
+ expect(getGenericResult(enableAgainEvents).success).to.be.true;
+ expect(enabledAgain).to.be.true;
+ });
+ });
+
+});
+
+describe.skip('Negative Integration Test toggleContractAllowList', () => {
+
+ it('Enable allow list for a non-contract', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const alice = privateKeyWrapper('//Alice');
+ const bobGuineaPig = privateKeyWrapper('//Bob');
+
+ const enabledBefore = (await api.query.unique.contractAllowListEnabled(bobGuineaPig.address)).toJSON();
+ const enableAllowListTx = api.tx.unique.toggleContractAllowList(bobGuineaPig.address, true);
+ await expect(submitTransactionExpectFailAsync(alice, enableAllowListTx)).to.be.rejected;
+ const enabled = (await api.query.unique.contractAllowListEnabled(bobGuineaPig.address)).toJSON();
+
+ expect(enabledBefore).to.be.false;
+ expect(enabled).to.be.false;
+ });
+ });
+
+ it('Enable allow list using a non-owner address', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const bob = privateKeyWrapper('//Bob');
+ const [contract] = await deployFlipper(api, privateKeyWrapper);
+
+ const enabledBefore = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
+ const enableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, true);
+ await expect(submitTransactionExpectFailAsync(bob, enableAllowListTx)).to.be.rejected;
+ const enabled = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
+
+ expect(enabledBefore).to.be.false;
+ expect(enabled).to.be.false;
+ });
+ });
+
+});
tests/src/.outdated/transfer_contract/metadata.jsondiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/transfer_contract/metadata.json
@@ -0,0 +1,469 @@
+{
+ "metadataVersion": "0.1.0",
+ "source": {
+ "hash": "0xc6c3f47adeafe86d1674ed72c7179605787842f2f05a2d7da0dbabf3c4fa1aa8",
+ "language": "ink! 3.0.0-rc3",
+ "compiler": "rustc 1.52.0-nightly"
+ },
+ "contract": {
+ "name": "nft_transfer",
+ "version": "0.1.0",
+ "authors": [
+ "[Greg Zaitsev] <[your_email]>"
+ ]
+ },
+ "spec": {
+ "constructors": [
+ {
+ "args": [],
+ "docs": [
+ "Default Constructor",
+ "",
+ "Constructors can delegate to other constructors."
+ ],
+ "name": [
+ "default"
+ ],
+ "selector": "0xed4b9d1b"
+ }
+ ],
+ "docs": [],
+ "events": [],
+ "messages": [
+ {
+ "args": [
+ {
+ "name": "recipient",
+ "type": {
+ "displayName": [
+ "AccountId"
+ ],
+ "type": 1
+ }
+ },
+ {
+ "name": "collection_id",
+ "type": {
+ "displayName": [
+ "u32"
+ ],
+ "type": 4
+ }
+ },
+ {
+ "name": "token_id",
+ "type": {
+ "displayName": [
+ "u32"
+ ],
+ "type": 4
+ }
+ },
+ {
+ "name": "amount",
+ "type": {
+ "displayName": [
+ "u128"
+ ],
+ "type": 5
+ }
+ }
+ ],
+ "docs": [
+ " Transfer one NFT token"
+ ],
+ "mutates": true,
+ "name": [
+ "transfer"
+ ],
+ "payable": false,
+ "returnType": null,
+ "selector": "0x84a15da1"
+ },
+ {
+ "args": [
+ {
+ "name": "recipient",
+ "type": {
+ "displayName": [
+ "AccountId"
+ ],
+ "type": 1
+ }
+ },
+ {
+ "name": "collection_id",
+ "type": {
+ "displayName": [
+ "u32"
+ ],
+ "type": 4
+ }
+ },
+ {
+ "name": "data",
+ "type": {
+ "displayName": [
+ "CreateItemData"
+ ],
+ "type": 6
+ }
+ }
+ ],
+ "docs": [],
+ "mutates": true,
+ "name": [
+ "create_item"
+ ],
+ "payable": false,
+ "returnType": null,
+ "selector": "0xd7c3f083"
+ },
+ {
+ "args": [
+ {
+ "name": "owner",
+ "type": {
+ "displayName": [
+ "AccountId"
+ ],
+ "type": 1
+ }
+ },
+ {
+ "name": "collection_id",
+ "type": {
+ "displayName": [
+ "u32"
+ ],
+ "type": 4
+ }
+ },
+ {
+ "name": "data",
+ "type": {
+ "displayName": [
+ "Vec"
+ ],
+ "type": 8
+ }
+ }
+ ],
+ "docs": [],
+ "mutates": true,
+ "name": [
+ "create_multiple_items"
+ ],
+ "payable": false,
+ "returnType": null,
+ "selector": "0x15f9a1eb"
+ },
+ {
+ "args": [
+ {
+ "name": "spender",
+ "type": {
+ "displayName": [
+ "AccountId"
+ ],
+ "type": 1
+ }
+ },
+ {
+ "name": "collection_id",
+ "type": {
+ "displayName": [
+ "u32"
+ ],
+ "type": 4
+ }
+ },
+ {
+ "name": "item_id",
+ "type": {
+ "displayName": [
+ "u32"
+ ],
+ "type": 4
+ }
+ },
+ {
+ "name": "amount",
+ "type": {
+ "displayName": [
+ "u128"
+ ],
+ "type": 5
+ }
+ }
+ ],
+ "docs": [],
+ "mutates": true,
+ "name": [
+ "approve"
+ ],
+ "payable": false,
+ "returnType": null,
+ "selector": "0x681266a0"
+ },
+ {
+ "args": [
+ {
+ "name": "owner",
+ "type": {
+ "displayName": [
+ "AccountId"
+ ],
+ "type": 1
+ }
+ },
+ {
+ "name": "recipient",
+ "type": {
+ "displayName": [
+ "AccountId"
+ ],
+ "type": 1
+ }
+ },
+ {
+ "name": "collection_id",
+ "type": {
+ "displayName": [
+ "u32"
+ ],
+ "type": 4
+ }
+ },
+ {
+ "name": "item_id",
+ "type": {
+ "displayName": [
+ "u32"
+ ],
+ "type": 4
+ }
+ },
+ {
+ "name": "amount",
+ "type": {
+ "displayName": [
+ "u128"
+ ],
+ "type": 5
+ }
+ }
+ ],
+ "docs": [],
+ "mutates": true,
+ "name": [
+ "transfer_from"
+ ],
+ "payable": false,
+ "returnType": null,
+ "selector": "0x0b396f18"
+ },
+ {
+ "args": [
+ {
+ "name": "collection_id",
+ "type": {
+ "displayName": [
+ "u32"
+ ],
+ "type": 4
+ }
+ },
+ {
+ "name": "item_id",
+ "type": {
+ "displayName": [
+ "u32"
+ ],
+ "type": 4
+ }
+ },
+ {
+ "name": "data",
+ "type": {
+ "displayName": [
+ "Vec"
+ ],
+ "type": 7
+ }
+ }
+ ],
+ "docs": [],
+ "mutates": true,
+ "name": [
+ "set_variable_meta_data"
+ ],
+ "payable": false,
+ "returnType": null,
+ "selector": "0xb0b26da2"
+ },
+ {
+ "args": [
+ {
+ "name": "collection_id",
+ "type": {
+ "displayName": [
+ "u32"
+ ],
+ "type": 4
+ }
+ },
+ {
+ "name": "address",
+ "type": {
+ "displayName": [
+ "AccountId"
+ ],
+ "type": 1
+ }
+ },
+ {
+ "name": "allowlisted",
+ "type": {
+ "displayName": [
+ "bool"
+ ],
+ "type": 9
+ }
+ }
+ ],
+ "docs": [],
+ "mutates": true,
+ "name": [
+ "toggle_allow_list"
+ ],
+ "payable": false,
+ "returnType": null,
+ "selector": "0x98574dac"
+ }
+ ]
+ },
+ "storage": {
+ "struct": {
+ "fields": []
+ }
+ },
+ "types": [
+ {
+ "def": {
+ "composite": {
+ "fields": [
+ {
+ "type": 2,
+ "typeName": "[u8; 32]"
+ }
+ ]
+ }
+ },
+ "path": [
+ "ink_env",
+ "types",
+ "AccountId"
+ ]
+ },
+ {
+ "def": {
+ "array": {
+ "len": 32,
+ "type": 3
+ }
+ }
+ },
+ {
+ "def": {
+ "primitive": "u8"
+ }
+ },
+ {
+ "def": {
+ "primitive": "u32"
+ }
+ },
+ {
+ "def": {
+ "primitive": "u128"
+ }
+ },
+ {
+ "def": {
+ "variant": {
+ "variants": [
+ {
+ "fields": [
+ {
+ "name": "const_data",
+ "type": 7,
+ "typeName": "Vec<u8>"
+ },
+ {
+ "name": "variable_data",
+ "type": 7,
+ "typeName": "Vec<u8>"
+ }
+ ],
+ "name": "Nft"
+ },
+ {
+ "fields": [
+ {
+ "name": "value",
+ "type": 5,
+ "typeName": "u128"
+ }
+ ],
+ "name": "Fungible"
+ },
+ {
+ "fields": [
+ {
+ "name": "const_data",
+ "type": 7,
+ "typeName": "Vec<u8>"
+ },
+ {
+ "name": "variable_data",
+ "type": 7,
+ "typeName": "Vec<u8>"
+ },
+ {
+ "name": "pieces",
+ "type": 5,
+ "typeName": "u128"
+ }
+ ],
+ "name": "ReFungible"
+ }
+ ]
+ }
+ },
+ "path": [
+ "nft_transfer",
+ "CreateItemData"
+ ]
+ },
+ {
+ "def": {
+ "sequence": {
+ "type": 3
+ }
+ }
+ },
+ {
+ "def": {
+ "sequence": {
+ "type": 6
+ }
+ }
+ },
+ {
+ "def": {
+ "primitive": "bool"
+ }
+ }
+ ]
+}
\ No newline at end of file
tests/src/.outdated/transfer_contract/nft_transfer.wasmdiffbeforeafterbothbinary blob — no preview
tests/src/.outdated/xcmTransfer.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/.outdated/xcmTransfer.test.ts
@@ -0,0 +1,187 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+
+import {WsProvider} from '@polkadot/api';
+import {ApiOptions} from '@polkadot/api/types';
+import {IKeyringPair} from '@polkadot/types/types';
+import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
+import {getGenericResult} from '../deprecated-helpers/helpers';
+import waitNewBlocks from '../substrate/wait-new-blocks';
+import getBalance from '../substrate/get-balance';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+const UNIQUE_CHAIN = 1000;
+const KARURA_CHAIN = 2000;
+const KARURA_PORT = '9946';
+const TRANSFER_AMOUNT = 2000000000000000000000000n;
+
+// todo:playgrounds refit when XCM drops
+describe.skip('Integration test: Exchanging QTZ with Karura', () => {
+ let alice: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ });
+
+ const karuraApiOptions: ApiOptions = {
+ provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT),
+ };
+
+ await usingApi(async (api) => {
+ const destination = {
+ V0: {
+ X2: [
+ 'Parent',
+ {
+ Parachain: UNIQUE_CHAIN,
+ },
+ ],
+ },
+ };
+
+ const metadata =
+ {
+ name: 'QTZ',
+ symbol: 'QTZ',
+ decimals: 18,
+ minimalBalance: 1,
+ };
+
+ const tx = api.tx.assetRegistry.registerForeignAsset(destination, metadata);
+ const sudoTx = api.tx.sudo.sudo(tx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+ }, karuraApiOptions);
+ });
+
+ it('Should connect and send QTZ to Karura', async () => {
+ let balanceOnKaruraBefore: bigint;
+
+ await usingApi(async (api) => {
+ const {free} = (await api.query.tokens.accounts(alice.addressRaw, {ForeignAssetId: 0})).toJSON() as any;
+ balanceOnKaruraBefore = free;
+ }, {provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT)});
+
+ await usingApi(async (api) => {
+ const destination = {
+ V0: {
+ X2: [
+ 'Parent',
+ {
+ Parachain: KARURA_CHAIN,
+ },
+ ],
+ },
+ };
+
+ const beneficiary = {
+ V0: {
+ X1: {
+ AccountId32: {
+ network: 'Any',
+ id: alice.addressRaw,
+ },
+ },
+ },
+ };
+
+ const assets = {
+ V1: [
+ {
+ id: {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ fun: {
+ Fungible: TRANSFER_AMOUNT,
+ },
+ },
+ ],
+ };
+
+ const feeAssetItem = 0;
+
+ const weightLimit = {
+ Limited: 5000000000,
+ };
+
+ const tx = api.tx.polkadotXcm.limitedReserveTransferAssets(destination, beneficiary, assets, feeAssetItem, weightLimit);
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+ });
+
+ await usingApi(async (api) => {
+ // todo do something about instant sealing, where there might not be any new blocks
+ await waitNewBlocks(api, 3);
+ const {free} = (await api.query.tokens.accounts(alice.addressRaw, {ForeignAssetId: 0})).toJSON() as any;
+ expect(free > balanceOnKaruraBefore).to.be.true;
+ }, {provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT)});
+ });
+
+ it('Should connect to Karura and send QTZ back', async () => {
+ let balanceBefore: bigint;
+
+ await usingApi(async (api) => {
+ [balanceBefore] = await getBalance(api, [alice.address]);
+ });
+
+ await usingApi(async (api) => {
+ const destination = {
+ V1: {
+ parents: 1,
+ interior: {
+ X2: [
+ {Parachain: UNIQUE_CHAIN},
+ {AccountId32: {
+ network: 'Any',
+ id: alice.addressRaw,
+ }},
+ ],
+ },
+ },
+ };
+
+ const id = {
+ ForeignAssetId: 0,
+ };
+
+ const amount = TRANSFER_AMOUNT;
+ const destWeight = 50000000;
+
+ const tx = api.tx.xTokens.transfer(id, amount, destination, destWeight);
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+ }, {provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT)});
+
+ await usingApi(async (api) => {
+ // todo do something about instant sealing, where there might not be any new blocks
+ await waitNewBlocks(api, 3);
+ const [balanceAfter] = await getBalance(api, [alice.address]);
+ expect(balanceAfter > balanceBefore).to.be.true;
+ });
+ });
+});
tests/src/addCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -110,7 +110,7 @@
const [alice, ...accounts] = await helper.arrange.createAccounts([10n, 0n, 0n, 0n, 0n, 0n, 0n, 0n], donor);
const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
- const chainAdminLimit = (helper.api!.consts.common.collectionAdminsLimit as any).toNumber();
+ const chainAdminLimit = (helper.getApi().consts.common.collectionAdminsLimit as any).toNumber();
expect(chainAdminLimit).to.be.equal(5);
for (let i = 0; i < chainAdminLimit; i++) {
tests/src/addToContractAllowList.test.tsdiffbeforeafterboth--- a/tests/src/addToContractAllowList.test.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import usingApi, {submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {
- deployFlipper,
-} from './util/contracthelpers';
-import {
- getGenericResult,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-// todo:playgrounds skipped ~ postponed
-describe.skip('Integration Test addToContractAllowList', () => {
-
- it('Add an address to a contract allow list', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const bob = privateKeyWrapper('//Bob');
- const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
-
- const allowListedBefore = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
- const addTx = api.tx.unique.addToContractAllowList(contract.address, bob.address);
- const addEvents = await submitTransactionAsync(deployer, addTx);
- const allowListedAfter = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
-
- expect(getGenericResult(addEvents).success).to.be.true;
- expect(allowListedBefore).to.be.false;
- expect(allowListedAfter).to.be.true;
- });
- });
-
- it('Adding same address to allow list repeatedly should not produce errors', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const bob = privateKeyWrapper('//Bob');
- const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
-
- const allowListedBefore = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
- const addTx = api.tx.unique.addToContractAllowList(contract.address, bob.address);
- const addEvents = await submitTransactionAsync(deployer, addTx);
- const allowListedAfter = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
- const addAgainEvents = await submitTransactionAsync(deployer, addTx);
- const allowListedAgainAfter = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
-
- expect(getGenericResult(addEvents).success).to.be.true;
- expect(allowListedBefore).to.be.false;
- expect(allowListedAfter).to.be.true;
- expect(getGenericResult(addAgainEvents).success).to.be.true;
- expect(allowListedAgainAfter).to.be.true;
- });
- });
-});
-
-describe.skip('Negative Integration Test addToContractAllowList', () => {
-
- it('Add an address to a allow list of a non-contract', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const alice = privateKeyWrapper('//Bob');
- const bob = privateKeyWrapper('//Bob');
- const charlieGuineaPig = privateKeyWrapper('//Charlie');
-
- const allowListedBefore = (await api.query.unique.contractAllowList(charlieGuineaPig.address, bob.address)).toJSON();
- const addTx = api.tx.unique.addToContractAllowList(charlieGuineaPig.address, bob.address);
- await expect(submitTransactionExpectFailAsync(alice, addTx)).to.be.rejected;
- const allowListedAfter = (await api.query.unique.contractAllowList(charlieGuineaPig.address, bob.address)).toJSON();
-
- expect(allowListedBefore).to.be.false;
- expect(allowListedAfter).to.be.false;
- });
- });
-
- it('Add to a contract allow list using a non-owner address', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const bob = privateKeyWrapper('//Bob');
- const [contract] = await deployFlipper(api, privateKeyWrapper);
-
- const allowListedBefore = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
- const addTx = api.tx.unique.addToContractAllowList(contract.address, bob.address);
- await expect(submitTransactionExpectFailAsync(bob, addTx)).to.be.rejected;
- const allowListedAfter = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
-
- expect(allowListedBefore).to.be.false;
- expect(allowListedAfter).to.be.false;
- });
- });
-
-});
tests/src/app-promotion.test.tsdiffbeforeafterboth--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -15,17 +15,11 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {
- normalizeAccountId,
- getModuleNames,
- Pallets,
-} from './util/helpers';
-import {itSub, usingPlaygrounds} from './util/playgrounds';
+import {itSub, usingPlaygrounds, Pallets, requirePalletsOrSkip} from './util/playgrounds';
import {encodeAddress} from '@polkadot/util-crypto';
import {stringToU8a} from '@polkadot/util';
-import {SponsoringMode} from './eth/util/helpers';
import {DevUniqueHelper} from './util/playgrounds/unique.dev';
-import {itEth, expect} from './eth/util/playgrounds';
+import {itEth, expect, SponsoringMode} from './eth/util/playgrounds';
let alice: IKeyringPair;
let palletAdmin: IKeyringPair;
@@ -42,10 +36,11 @@
describe('App promotion', () => {
before(async function () {
await usingPlaygrounds(async (helper, privateKey) => {
- if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) this.skip();
+ requirePalletsOrSkip(this, helper, [Pallets.AppPromotion]);
alice = await privateKey({filename: __filename});
[palletAdmin] = await helper.arrange.createAccounts([100n], alice);
- await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
+ const api = helper.getApi();
+ await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
nominal = helper.balance.getOneTokenNominal();
await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);
await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);
@@ -231,54 +226,59 @@
describe('admin adress', () => {
itSub('can be set by sudo only', async ({helper}) => {
+ const api = helper.getApi();
const nonAdmin = accounts.pop()!;
// nonAdmin can not set admin not from himself nor as a sudo
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
// Alice can
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
});
itSub('can be any valid CrossAccountId', async ({helper}) => {
// We are not going to set an eth address as a sponsor,
// but we do want to check, it doesn't break anything;
+ const api = helper.getApi();
const account = accounts.pop()!;
const ethAccount = helper.address.substrateToEth(account.address);
// Alice sets Ethereum address as a sudo. Then Substrate address back...
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
// ...It doesn't break anything;
const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(account, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(account, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
});
itSub('can be reassigned', async ({helper}) => {
+ const api = helper.getApi();
const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.fulfilled;
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.fulfilled;
- await expect(helper.signTransaction(oldAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: oldAdmin.address})))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: newAdmin.address})))).to.be.fulfilled;
+ await expect(helper.signTransaction(oldAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
- await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(newAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
});
});
describe('collection sponsoring', () => {
before(async function () {
await usingPlaygrounds(async (helper) => {
- const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
+ const api = helper.getApi();
+ const tx = api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
await helper.signTransaction(alice, tx);
});
});
itSub('should actually sponsor transactions', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});
const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
+ await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));
const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);
await token.transfer(tokenSender, {Substrate: receiver.address});
@@ -291,41 +291,44 @@
});
itSub('can not be set by non admin', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');
});
itSub('should set pallet address as confirmed admin', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];
// Can set sponsoring for collection without sponsor
const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;
expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
// Can set sponsoring for collection with unconfirmed sponsor
const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;
expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
// Can set sponsoring for collection with confirmed sponsor
const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;
expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
});
itSub('can be overwritten by collection owner', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
const collectionId = collection.collectionId;
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;
// Collection limits still can be changed by the owner
expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;
@@ -338,44 +341,48 @@
});
itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {
+ const api = helper.getApi();
const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};
const collectionWithLimits = await helper.nft.mintCollection(alice, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;
expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);
});
itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {
+ const api = helper.getApi();
const collectionOwner = accounts.pop()!;
// collection has never existed
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;
// collection has been burned
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
await collection.burn(collectionOwner);
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
});
});
describe('stopSponsoringCollection', () => {
- itSub('can not be called by non-admin', async ({helper}) => {
+ itSub('can not be called by non-admin', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
});
itSub('should set sponsoring as disabled', async ({helper}) => {
+ const api = helper.getApi();
const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});
const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId));
+ await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId));
+ await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId));
expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');
@@ -387,11 +394,12 @@
});
itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {
+ const api = helper.getApi();
const collectionOwner = accounts.pop()!;
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});
await collection.confirmSponsorship(collectionOwner);
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
+ await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});
});
@@ -415,8 +423,8 @@
await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);
expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
- expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
confirmed: {
substrate: palletAddress,
},
@@ -431,7 +439,7 @@
await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
// Contract is self sponsored
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.be.deep.equal({
confirmed: {
ethereum: flipper.options.address.toLowerCase(),
},
@@ -462,8 +470,8 @@
await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
- expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
confirmed: {
ethereum: flipper.options.address.toLowerCase(),
},
@@ -482,7 +490,7 @@
await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');
// contract still self-sponsored
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
confirmed: {
ethereum: flipper.options.address.toLowerCase(),
},
@@ -505,7 +513,7 @@
await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);
// Set promotion to the Flipper
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorContract(flipper.options.address));
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
// Caller calls Flipper
await flipper.methods.flip().send({from: caller});
@@ -536,8 +544,8 @@
await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);
expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;
- expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
disabled: null,
});
@@ -717,7 +725,7 @@
// Wait while promotion period less than specified block, to avoid boundary cases
// 0 if this should be the beginning of the period.
async function waitPromotionPeriodDoesntEnd(helper: DevUniqueHelper, waitBlockLessThan = LOCKING_PERIOD / 3n) {
- const relayBlockNumber = (await helper.api!.query.parachainSystem.validationData()).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();
+ const relayBlockNumber = (await helper.callRpc('api.query.parachainSystem.validationData', [])).value.relayParentNumber.toNumber(); // await helper.chain.getLatestBlockNumber();
const currentPeriodBlock = BigInt(relayBlockNumber) % LOCKING_PERIOD;
if (currentPeriodBlock > waitBlockLessThan) {
tests/src/approve.test.tsdiffbeforeafterboth--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -60,7 +60,7 @@
const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- await helper.signTransaction(alice, helper.api?.tx.unique.approve({Substrate: bob.address}, collectionId, tokenId, 0));
+ await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
});
@@ -275,7 +275,7 @@
const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- await helper.signTransaction(alice, helper.api?.tx.unique.approve({Substrate: bob.address}, collectionId, tokenId, 0));
+ await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
const transferTokenFromTx = async () => helper.nft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: bob.address});
await expect(transferTokenFromTx()).to.be.rejected;
@@ -328,7 +328,7 @@
itSub('1 for NFT', async ({helper}) => {
const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- const approveTx = async () => helper.signTransaction(bob, helper.api?.tx.unique.approve({Substrate: charlie.address}, collectionId, tokenId, 2));
+ const approveTx = async () => helper.signTransaction(bob, helper.constructApiCall('api.tx.unique.approve', [{Substrate: charlie.address}, collectionId, tokenId, 2]));
await expect(approveTx()).to.be.rejected;
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.false;
});
tests/src/balance-transfer-contract/calls.wasmdiffbeforeafterbothbinary blob — no preview
tests/src/balance-transfer-contract/metadata.jsondiffbeforeafterboth--- a/tests/src/balance-transfer-contract/metadata.json
+++ /dev/null
@@ -1,96 +0,0 @@
-{
- "registry": {
- "strings": [
- "Storage",
- "calls",
- "__ink_private",
- "__ink_storage",
- "new",
- "balance_transfer",
- "dest",
- "AccountId",
- "value",
- "Balance"
- ],
- "types": [
- {
- "id": {
- "custom.name": 1,
- "custom.namespace": [
- 2,
- 2,
- 3,
- 4
- ],
- "custom.params": []
- },
- "def": {
- "struct.fields": []
- }
- },
- {
- "id": {
- "array.len": 32,
- "array.type": 3
- },
- "def": "builtin"
- },
- {
- "id": "u8",
- "def": "builtin"
- },
- {
- "id": "u128",
- "def": "builtin"
- }
- ]
- },
- "storage": {
- "struct.type": 1,
- "struct.fields": []
- },
- "contract": {
- "name": 2,
- "constructors": [
- {
- "name": 5,
- "selector": "[\"0x5E\",\"0xBD\",\"0x88\",\"0xD6\"]",
- "args": [],
- "docs": []
- }
- ],
- "messages": [
- {
- "name": 6,
- "selector": "[\"0xEC\",\"0x9F\",\"0xA4\",\"0xF0\"]",
- "mutates": false,
- "args": [
- {
- "name": 7,
- "type": {
- "ty": 2,
- "display_name": [
- 8
- ]
- }
- },
- {
- "name": 9,
- "type": {
- "ty": 4,
- "display_name": [
- 10
- ]
- }
- }
- ],
- "return_type": null,
- "docs": [
- "Dispatches a `transfer` call to the Balances srml module"
- ]
- }
- ],
- "events": [],
- "docs": []
- }
-}
\ No newline at end of file
tests/src/block-production.test.tsdiffbeforeafterboth--- a/tests/src/block-production.test.ts
+++ b/tests/src/block-production.test.ts
@@ -37,7 +37,7 @@
describe('Block Production smoke test', () => {
itSub('Node produces new blocks', async ({helper}) => {
- const blocks: number[] | undefined = await getBlocks(helper.api!);
+ const blocks: number[] | undefined = await getBlocks(helper.getApi());
expect(blocks[0]).to.be.lessThan(blocks[1]);
});
});
tests/src/calibrate.tsdiffbeforeafterboth--- a/tests/src/calibrate.ts
+++ b/tests/src/calibrate.ts
@@ -1,11 +1,8 @@
-import {ApiPromise} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
-import Web3 from 'web3';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, recordEthFee, usingWeb3} from './eth/util/helpers';
-import usingApi, {executeTransaction} from './substrate/substrate-api';
-import {createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, UNIQUE, waitNewBlocks} from './util/helpers';
-import nonFungibleAbi from './eth/nonFungibleAbi.json';
+import {usingEthPlaygrounds, EthUniqueHelper} from './eth/util/playgrounds';
+
+
function linearRegression(points: { x: bigint, y: bigint }[]) {
let sumxy = 0n;
let sumx = 0n;
@@ -59,32 +56,33 @@
}).reduce((a, b) => a + b, 0n) / BigInt(points.length));
}
-async function calibrateWeightToFee(api: ApiPromise, privateKey: (account: string) => IKeyringPair) {
+async function calibrateWeightToFee(helper: EthUniqueHelper, privateKey: (account: string) => IKeyringPair) {
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
const dataPoints = [];
{
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
- const aliceBalanceBefore = (await api.query.system.account(alice.address)).data.free.toBigInt();
- await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');
- const aliceBalanceAfter = (await api.query.system.account(alice.address)).data.free.toBigInt();
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address});
+ const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
+ await token.transfer(alice, {Substrate: bob.address});
+ const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);
- console.log(`Original price: ${Number(aliceBalanceBefore - aliceBalanceAfter) / Number(UNIQUE)} UNQ`);
+ console.log(`Original price: ${Number(aliceBalanceBefore - aliceBalanceAfter) / Number(helper.balance.getOneTokenNominal())} UNQ`);
}
+ const api = helper.getApi();
const defaultCoeff = (api.consts.configuration.defaultWeightToFeeCoefficient as any).toBigInt();
for (let i = -5; i < 5; i++) {
- await executeTransaction(api, alice, api.tx.sudo.sudo(api.tx.configuration.setWeightToFeeCoefficientOverride(defaultCoeff + defaultCoeff / 1000n * BigInt(i))));
+ await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.configuration.setWeightToFeeCoefficientOverride(defaultCoeff + defaultCoeff / 1000n * BigInt(i))));
const coefficient = (await api.query.configuration.weightToFeeCoefficientOverride() as any).toBigInt();
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address});
- const aliceBalanceBefore = (await api.query.system.account(alice.address)).data.free.toBigInt();
- await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');
- const aliceBalanceAfter = (await api.query.system.account(alice.address)).data.free.toBigInt();
+ const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
+ await token.transfer(alice, {Substrate: bob.address});
+ const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);
const transferPrice = aliceBalanceBefore - aliceBalanceAfter;
@@ -94,52 +92,53 @@
// console.log(`Error: ${error(dataPoints, x => a*x+b)}`);
- const perfectValue = a * UNIQUE / 10n + b;
- await executeTransaction(api, alice, api.tx.sudo.sudo(api.tx.configuration.setWeightToFeeCoefficientOverride(perfectValue.toString())));
+ const perfectValue = a * helper.balance.getOneTokenNominal() / 10n + b;
+ await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.configuration.setWeightToFeeCoefficientOverride(perfectValue.toString())));
{
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
- const aliceBalanceBefore = (await api.query.system.account(alice.address)).data.free.toBigInt();
- await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');
- const aliceBalanceAfter = (await api.query.system.account(alice.address)).data.free.toBigInt();
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Substrate: alice.address});
+ const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
+ await token.transfer(alice, {Substrate: bob.address});
+ const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);
- console.log(`Calibrated price: ${Number(aliceBalanceBefore - aliceBalanceAfter) / Number(UNIQUE)} UNQ`);
+ console.log(`Calibrated price: ${Number(aliceBalanceBefore - aliceBalanceAfter) / Number(helper.balance.getOneTokenNominal())} UNQ`);
}
}
-async function calibrateMinGasPrice(api: ApiPromise, web3: Web3, privateKey: (account: string) => IKeyringPair) {
+async function calibrateMinGasPrice(helper: EthUniqueHelper, privateKey: (account: string) => IKeyringPair) {
const alice = privateKey('//Alice');
- const caller = await createEthAccountWithBalance(api, web3, privateKey);
- const receiver = createEthAccount(web3);
+ const caller = await helper.eth.createAccountWithBalance(alice);
+ const receiver = helper.eth.createAccount();
const dataPoints = [];
{
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', {Ethereum: caller});
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Ethereum: caller});
- const address = collectionIdToAddress(collectionId);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'nft', caller);
- const cost = await recordEthFee(api, caller, () => contract.methods.transfer(receiver, tokenId).send(caller));
+ const cost = await helper.eth.calculateFee({Ethereum: caller}, () => contract.methods.transfer(receiver, token.tokenId).send({from: caller, gas: helper.eth.DEFAULT_GAS}));
- console.log(`Original price: ${Number(cost) / Number(UNIQUE)} UNQ`);
+ console.log(`Original price: ${Number(cost) / Number(helper.balance.getOneTokenNominal())} UNQ`);
}
+ const api = helper.getApi();
const defaultCoeff = (api.consts.configuration.defaultMinGasPrice as any).toBigInt();
for (let i = -8; i < 8; i++) {
const gasPrice = defaultCoeff + defaultCoeff / 100000n * BigInt(i);
const gasPriceStr = '0x' + gasPrice.toString(16);
- await executeTransaction(api, alice, api.tx.sudo.sudo(api.tx.configuration.setMinGasPriceOverride(gasPrice)));
+ await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.configuration.setMinGasPriceOverride(gasPrice)));
const coefficient = (await api.query.configuration.minGasPriceOverride() as any).toBigInt();
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', {Ethereum: caller});
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Ethereum: caller});
- const address = collectionIdToAddress(collectionId);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, gasPrice: gasPriceStr, ...GAS_ARGS});
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'nft', caller);
- const transferPrice = await recordEthFee(api, caller, () => contract.methods.transfer(receiver, tokenId).send(caller));
+ const transferPrice = await helper.eth.calculateFee({Ethereum: caller}, () => contract.methods.transfer(receiver, token.tokenId).send({from: caller, gasPrice: gasPriceStr, gas: helper.eth.DEFAULT_GAS}));
dataPoints.push({x: transferPrice, y: coefficient});
}
@@ -149,34 +148,30 @@
// console.log(`Error: ${error(dataPoints, x => a*x+b)}`);
// * 0.15 = * 10000 / 66666
- const perfectValue = a * UNIQUE * 1000000n / 6666666n + b;
- await executeTransaction(api, alice, api.tx.sudo.sudo(api.tx.configuration.setMinGasPriceOverride(perfectValue.toString())));
+ const perfectValue = a * helper.balance.getOneTokenNominal() * 1000000n / 6666666n + b;
+ await helper.signTransaction(alice, api.tx.sudo.sudo(api.tx.configuration.setMinGasPriceOverride(perfectValue.toString())));
{
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', {Ethereum: caller});
+ const collection = await helper.nft.mintCollection(alice, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
+ const token = await collection.mintToken(alice, {Ethereum: caller});
- const address = collectionIdToAddress(collectionId);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'nft', caller);
- const cost = await recordEthFee(api, caller, () => contract.methods.transfer(receiver, tokenId).send(caller));
+ const cost = await helper.eth.calculateFee({Ethereum: caller}, () => contract.methods.transfer(receiver, token.tokenId).send({from: caller, gas: helper.eth.DEFAULT_GAS}));
- console.log(`Calibrated price: ${Number(cost) / Number(UNIQUE)} UNQ`);
+ console.log(`Calibrated price: ${Number(cost) / Number(helper.balance.getOneTokenNominal())} UNQ`);
}
}
(async () => {
- await usingApi(async (api, privateKey) => {
+ await usingEthPlaygrounds(async (helper: EthUniqueHelper, privateKey) => {
// Second run slightly reduces error sometimes, as price line is not actually straight, this is a curve
- await calibrateWeightToFee(api, privateKey);
- await calibrateWeightToFee(api, privateKey);
+ await calibrateWeightToFee(helper, privateKey);
+ await calibrateWeightToFee(helper, privateKey);
- await usingWeb3(async web3 => {
- await calibrateMinGasPrice(api, web3, privateKey);
- await calibrateMinGasPrice(api, web3, privateKey);
- });
-
- await api.disconnect();
+ await calibrateMinGasPrice(helper, privateKey);
+ await calibrateMinGasPrice(helper, privateKey);
});
})();
tests/src/collision-tests/admVsOwnerChanges.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/admVsOwnerChanges.test.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-/* broken by design
-// substrate transactions are sequential, not parallel
-// the order of execution is indeterminate
-
-import { IKeyringPair } from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from '../substrate/privateKey';
-import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- createItemExpectSuccess,
- normalizeAccountId,
- waitNewBlocks,
-} from '../util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-let Alice: IKeyringPair;
-let Bob: IKeyringPair;
-let Ferdie: IKeyringPair;
-
-before(async () => {
- await usingApi(async () => {
- Alice = privateKey('//Alice');
- Bob = privateKey('//Bob');
- Ferdie = privateKey('//Ferdie');
- });
-});
-
-describe('Admin vs Owner changes token: ', () => {
- // tslint:disable-next-line: max-line-length
- it('The collection admin changes the owner of the token and in the same block the current owner transfers the token to another address ', async () => {
-
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const changeAdminTxBob = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
- await submitTransactionAsync(Alice, changeAdminTxBob);
- const changeAdminTxFerdie = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Ferdie.address));
- await submitTransactionAsync(Bob, changeAdminTxFerdie);
- const itemId = await createItemExpectSuccess(Ferdie, collectionId, 'NFT');
-
- const changeOwner = api.tx.unique.transferFrom(normalizeAccountId(Ferdie.address), normalizeAccountId(Bob.address), collectionId, itemId, 1);
- const approve = api.tx.unique.approve(normalizeAccountId(Bob.address), collectionId, itemId, 1);
- const sendItem = api.tx.unique.transfer(normalizeAccountId(Alice.address), collectionId, itemId, 1);
- await Promise.all([
- changeOwner.signAndSend(Alice),
- approve.signAndSend(Bob),
- sendItem.signAndSend(Ferdie),
- ]);
- const itemBefore: any = await api.query.unique.nftItemList(collectionId, itemId);
- expect(itemBefore.owner).not.to.be.eq(Bob.address);
- await waitNewBlocks(2);
- });
- });
-});
-*/
\ No newline at end of file
tests/src/collision-tests/admVsOwnerData.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/admVsOwnerData.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-/* broken by design
-// substrate transactions are sequential, not parallel
-// the order of execution is indeterminate
-
-import { IKeyringPair } from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from '../substrate/privateKey';
-import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- createItemExpectSuccess,
- normalizeAccountId,
- waitNewBlocks,
-} from '../util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-let Alice: IKeyringPair;
-let Bob: IKeyringPair;
-
-before(async () => {
- await usingApi(async () => {
- Alice = privateKey('//Alice');
- Bob = privateKey('//Bob');
- });
-});
-
-describe('Admin vs Owner changes the data in the token: ', () => {
- it('The collection admin changes the data in the token and in the same block the token owner also changes the data in it ', async () => {
- await usingApi(async (api) => {
- const AliceData = 1;
- const BobData = 2;
- const collectionId = await createCollectionExpectSuccess();
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
- await submitTransactionAsync(Alice, changeAdminTx);
- const itemId = await createItemExpectSuccess(Bob, collectionId, 'NFT');
- //
- // tslint:disable-next-line: max-line-length
- const AliceTx = api.tx.unique.setVariableMetaData(collectionId, itemId, AliceData.toString());
- // tslint:disable-next-line: max-line-length
- const BobTx = api.tx.unique.setVariableMetaData(collectionId, itemId, BobData.toString());
- await Promise.all([
- AliceTx.signAndSend(Alice),
- BobTx.signAndSend(Bob),
- ]);
- const item: any = await api.query.unique.nftItemList(collectionId, itemId);
- expect(item.variableData).not.to.be.eq(null); // Pseudo-random selection of one of two values
- await waitNewBlocks(2);
- });
- });
-});
-*/
\ No newline at end of file
tests/src/collision-tests/admVsOwnerTake.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/admVsOwnerTake.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-/* broken by design
-// substrate transactions are sequential, not parallel
-// the order of execution is indeterminate
-
-import { IKeyringPair } from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from '../substrate/privateKey';
-import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- createItemExpectSuccess,
- normalizeAccountId,
- waitNewBlocks,
-} from '../util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-let Alice: IKeyringPair;
-let Bob: IKeyringPair;
-let Ferdie: IKeyringPair;
-
-before(async () => {
- await usingApi(async () => {
- Alice = privateKey('//Alice');
- Bob = privateKey('//Bob');
- Ferdie = privateKey('//Ferdie');
- });
-});
-
-describe('Admin vs Owner take token: ', () => {
- // tslint:disable-next-line: max-line-length
- it('The collection admin burns the token and in the same block the token owner performs a transaction on it ', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
- await submitTransactionAsync(Alice, changeAdminTx);
- const itemId = await createItemExpectSuccess(Bob, collectionId, 'NFT');
- //
- const sendItem = api.tx.unique.transfer(normalizeAccountId(Ferdie.address), collectionId, itemId, 1);
- const burnItem = api.tx.unique.burnItem(collectionId, itemId, 1);
- await Promise.all([
- sendItem.signAndSend(Bob),
- burnItem.signAndSend(Alice),
- ]);
- await waitNewBlocks(2);
- let itemBurn = false;
- itemBurn = (await (api.query.unique.nftItemList(collectionId, itemId))).toJSON() as boolean;
- // tslint:disable-next-line: no-unused-expression
- expect(itemBurn).to.be.null;
- await waitNewBlocks(2);
- });
- });
-});
-*/
\ No newline at end of file
tests/src/collision-tests/adminDestroyCollection.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/adminDestroyCollection.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-/* broken by design
-// substrate transactions are sequential, not parallel
-// the order of execution is indeterminate
-
-import { IKeyringPair } from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from '../substrate/privateKey';
-import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- normalizeAccountId,
- waitNewBlocks,
-} from '../util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-let Alice: IKeyringPair;
-let Bob: IKeyringPair;
-let Ferdie: IKeyringPair;
-
-before(async () => {
- await usingApi(async () => {
- Alice = privateKey('//Alice');
- Bob = privateKey('//Bob');
- Ferdie = privateKey('//Ferdie');
- });
-});
-
-describe('Deleting a collection while add address to allowlist: ', () => {
- // tslint:disable-next-line: max-line-length
- it('Adding an address to the collection allowlist in a block by the admin, and deleting the collection by the owner ', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
- await submitTransactionAsync(Alice, changeAdminTx);
- await waitNewBlocks(1);
- //
- const addAllowlistAdm = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(Ferdie.address));
- const destroyCollection = api.tx.unique.destroyCollection(collectionId);
- await Promise.all([
- addAllowlistAdm.signAndSend(Bob),
- destroyCollection.signAndSend(Alice),
- ]);
- await waitNewBlocks(1);
- let allowList = false;
- allowList = (await api.query.unique.allowList(collectionId, Ferdie.address)).toJSON() as boolean;
- // tslint:disable-next-line: no-unused-expression
- expect(allowList).to.be.false;
- await waitNewBlocks(2);
- });
- });
-});
-*/
\ No newline at end of file
tests/src/collision-tests/adminLimitsOff.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/adminLimitsOff.test.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-/* broken by design
-// substrate transactions are sequential, not parallel
-// the order of execution is indeterminate
-
-import { IKeyringPair } from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from '../substrate/privateKey';
-import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- normalizeAccountId,
- waitNewBlocks,
-} from '../util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-let Alice: IKeyringPair;
-let Bob: IKeyringPair;
-let Ferdie: IKeyringPair;
-let Charlie: IKeyringPair;
-let Eve: IKeyringPair;
-let Dave: IKeyringPair;
-
-before(async () => {
- await usingApi(async () => {
- Alice = privateKey('//Alice');
- Bob = privateKey('//Bob');
- Ferdie = privateKey('//Ferdie');
- Charlie = privateKey('//Charlie');
- Eve = privateKey('//Eve');
- Dave = privateKey('//Dave');
- });
-});
-
-describe('Admin limit exceeded collection: ', () => {
- // tslint:disable-next-line: max-line-length
- it('In one block, the owner and admin add new admins to the collection more than the limit ', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
-
- const chainAdminLimit = (api.consts.unique.collectionAdminsLimit as any).toNumber();
- expect(chainAdminLimit).to.be.equal(5);
-
- const changeAdminTx1 = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Eve.address));
- await submitTransactionAsync(Alice, changeAdminTx1);
- const changeAdminTx2 = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Dave.address));
- await submitTransactionAsync(Alice, changeAdminTx2);
- const changeAdminTx3 = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
- await submitTransactionAsync(Alice, changeAdminTx3);
-
- const addAdmOne = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Ferdie.address));
- const addAdmTwo = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Charlie.address));
- await Promise.all([
- addAdmOne.signAndSend(Bob),
- addAdmTwo.signAndSend(Alice),
- ]);
- await waitNewBlocks(2);
- const changeAdminTx4 = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Alice.address));
- await expect(submitTransactionExpectFailAsync(Alice, changeAdminTx4)).to.be.rejected;
-
- const adminListAfterAddAdmin: any = (await api.query.unique.adminList(collectionId));
- expect(adminListAfterAddAdmin).to.be.contains(normalizeAccountId(Eve.address));
- expect(adminListAfterAddAdmin).to.be.contains(normalizeAccountId(Ferdie.address));
- expect(adminListAfterAddAdmin).not.to.be.contains(normalizeAccountId(Alice.address));
- await waitNewBlocks(2);
- });
- });
-});
-*/
\ No newline at end of file
tests/src/collision-tests/adminRightsOff.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/adminRightsOff.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-/* broken by design
-// substrate transactions are sequential, not parallel
-// the order of execution is indeterminate
-
-import { IKeyringPair } from '@polkadot/types/types';
-import BN from 'bn.js';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from '../substrate/privateKey';
-import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- normalizeAccountId,
- waitNewBlocks,
-} from '../util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-let Alice: IKeyringPair;
-let Bob: IKeyringPair;
-
-before(async () => {
- await usingApi(async () => {
- Alice = privateKey('//Alice');
- Bob = privateKey('//Bob');
- });
-});
-
-describe('Deprivation of admin rights: ', () => {
- // tslint:disable-next-line: max-line-length
- it('In the block, the collection admin adds a token or changes data, and the collection owner deprives the admin of rights ', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
- await submitTransactionAsync(Alice, changeAdminTx);
- await waitNewBlocks(1);
- const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];
- const addItemAdm = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(Bob.address), args);
- const removeAdm = api.tx.unique.removeCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
- await Promise.all([
- addItemAdm.signAndSend(Bob),
- removeAdm.signAndSend(Alice),
- ]);
- await waitNewBlocks(2);
- const itemsListIndex = await api.query.unique.itemListIndex(collectionId) as unknown as BN;
- expect(itemsListIndex.toNumber()).to.be.equal(0);
- const adminList: any = (await api.query.unique.adminList(collectionId));
- expect(adminList).not.to.be.contains(normalizeAccountId(Bob.address));
- await waitNewBlocks(2);
- });
- });
-});
-*/
\ No newline at end of file
tests/src/collision-tests/setSponsorNewOwner.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/setSponsorNewOwner.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-/* broken by design
-// substrate transactions are sequential, not parallel
-// the order of execution is indeterminate
-
-import { IKeyringPair } from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from '../substrate/privateKey';
-import usingApi from '../substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- setCollectionSponsorExpectSuccess,
- waitNewBlocks,
-} from '../util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-let Alice: IKeyringPair;
-let Bob: IKeyringPair;
-let Ferdie: IKeyringPair;
-
-before(async () => {
- await usingApi(async () => {
- Alice = privateKey('//Alice');
- Bob = privateKey('//Bob');
- Ferdie = privateKey('//Ferdie');
- });
-});
-
-describe('Sponsored with new owner ', () => {
- // tslint:disable-next-line: max-line-length
- it('Confirmation of sponsorship of a collection in a block with a change in the owner of the collection: ', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, Bob.address);
- await waitNewBlocks(2);
- const confirmSponsorship = api.tx.unique.confirmSponsorship(collectionId);
- const changeCollectionOwner = api.tx.unique.changeCollectionOwner(collectionId, Ferdie.address);
- await Promise.all([
- confirmSponsorship.signAndSend(Bob),
- changeCollectionOwner.signAndSend(Alice),
- ]);
- await waitNewBlocks(2);
- const collection: any = (await api.query.unique.collectionById(collectionId)).toJSON();
- expect(collection.sponsorship.confirmed).to.be.eq(Bob.address);
- expect(collection.owner).to.be.eq(Ferdie.address);
- await waitNewBlocks(2);
- });
- });
-});
-*/
\ No newline at end of file
tests/src/collision-tests/sponsorPayments.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/sponsorPayments.test.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-/* broken by design
-// substrate transactions are sequential, not parallel
-// the order of execution is indeterminate
-
-import { IKeyringPair } from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import { alicesPublicKey, bobsPublicKey } from '../accounts';
-import getBalance from '../substrate/get-balance';
-import privateKey from '../substrate/privateKey';
-import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
-import {
- confirmSponsorshipExpectSuccess,
- createCollectionExpectSuccess,
- createItemExpectSuccess,
- setCollectionSponsorExpectSuccess,
- normalizeAccountId,
- waitNewBlocks,
-} from '../util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-let Alice: IKeyringPair;
-let Bob: IKeyringPair;
-
-before(async () => {
- await usingApi(async () => {
- Alice = privateKey('//Alice');
- Bob = privateKey('//Bob');
- });
-});
-
-describe('Payment of commission if one block: ', () => {
- // tslint:disable-next-line: max-line-length
- it('Payment of commission if one block contains transactions for payment from the sponsor\'s balance and his (sponsor\'s) exclusion from the collection ', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const changeAdminTxBob = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
- await submitTransactionAsync(Alice, changeAdminTxBob);
- const itemId = await createItemExpectSuccess(Bob, collectionId, 'NFT');
- await setCollectionSponsorExpectSuccess(collectionId, Bob.address);
- await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
-
- const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
- const sendItem = api.tx.unique.transfer(normalizeAccountId(Alice.address), collectionId, itemId, 1);
- const revokeSponsor = api.tx.unique.removeCollectionSponsor(collectionId);
- await Promise.all([
- sendItem.signAndSend(Bob),
- revokeSponsor.signAndSend(Alice),
- ]);
- const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
- // tslint:disable-next-line:no-unused-expression
- expect(alicesBalanceAfter === alicesBalanceBefore).to.be.true;
- // tslint:disable-next-line:no-unused-expression
- expect(bobsBalanceAfter === bobsBalanceBefore).to.be.true;
- await waitNewBlocks(2);
- });
- });
-});
-*/
\ No newline at end of file
tests/src/collision-tests/tokenLimitsOff.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/tokenLimitsOff.test.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-/* broken by design
-// substrate transactions are sequential, not parallel
-// the order of execution is indeterminate
-
-import { IKeyringPair } from '@polkadot/types/types';
-import BN from 'bn.js';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from '../substrate/privateKey';
-import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
-import {
- addToAllowListExpectSuccess,
- createCollectionExpectSuccess,
- getCreateItemResult,
- setMintPermissionExpectSuccess,
- normalizeAccountId,
- waitNewBlocks,
-} from '../util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-let Alice: IKeyringPair;
-let Bob: IKeyringPair;
-let Ferdie: IKeyringPair;
-
-const accountTokenOwnershipLimit = 4;
-const sponsoredMintSize = 4294967295;
-const tokenLimit = 4;
-const sponsorTimeout = 14400;
-const ownerCanTransfer = false;
-const ownerCanDestroy = false;
-
-before(async () => {
- await usingApi(async () => {
- Alice = privateKey('//Alice');
- Bob = privateKey('//Bob');
- Ferdie = privateKey('//Ferdie');
- });
-});
-
-describe('Token limit exceeded collection: ', () => {
- // tslint:disable-next-line: max-line-length
- it('The number of tokens created in the collection from different addresses exceeds the allowed collection limit ', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- await setMintPermissionExpectSuccess(Alice, collectionId, true);
- await addToAllowListExpectSuccess(Alice, collectionId, Ferdie.address);
- await addToAllowListExpectSuccess(Alice, collectionId, Bob.address);
- const setCollectionLim = api.tx.unique.setCollectionLimits(
- collectionId,
- {
- accountTokenOwnershipLimit,
- sponsoredMintSize,
- tokenLimit,
- // tslint:disable-next-line: object-literal-sort-keys
- sponsorTimeout,
- ownerCanTransfer,
- ownerCanDestroy,
- },
- );
- const subTx = await submitTransactionAsync(Alice, setCollectionLim);
- const subTxTesult = getCreateItemResult(subTx);
- // tslint:disable-next-line:no-unused-expression
- expect(subTxTesult.success).to.be.true;
- await waitNewBlocks(2);
-
- const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];
- const mintItemOne = api.tx.unique
- .createMultipleItems(collectionId, normalizeAccountId(Ferdie.address), args);
- const mintItemTwo = api.tx.unique
- .createMultipleItems(collectionId, normalizeAccountId(Bob.address), args);
- await Promise.all([
- mintItemOne.signAndSend(Ferdie),
- mintItemTwo.signAndSend(Bob),
- ]);
- await waitNewBlocks(2);
- const itemsListIndexAfter = await api.query.unique.itemListIndex(collectionId) as unknown as BN;
- expect(itemsListIndexAfter.toNumber()).to.be.equal(3);
- // TokenLimit = 4. The first transaction is successful. The second should fail.
- await waitNewBlocks(2);
- });
- });
-});
-*/
tests/src/collision-tests/turnsOffMinting.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/turnsOffMinting.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-/* broken by design
-// substrate transactions are sequential, not parallel
-// the order of execution is indeterminate
-
-import { IKeyringPair } from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from '../substrate/privateKey';
-import usingApi from '../substrate/substrate-api';
-import {
- addToAllowListExpectSuccess,
- createCollectionExpectSuccess,
- setMintPermissionExpectSuccess,
- normalizeAccountId,
- waitNewBlocks,
-} from '../util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-let Alice: IKeyringPair;
-let Ferdie: IKeyringPair;
-
-before(async () => {
- await usingApi(async () => {
- Alice = privateKey('//Alice');
- Ferdie = privateKey('//Ferdie');
- });
-});
-
-describe('Turns off minting mode: ', () => {
- // tslint:disable-next-line: max-line-length
- it('The collection owner turns off minting mode and there are minting transactions in the same block ', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- await setMintPermissionExpectSuccess(Alice, collectionId, true);
- await addToAllowListExpectSuccess(Alice, collectionId, Ferdie.address);
-
- const mintItem = api.tx.unique.createItem(collectionId, normalizeAccountId(Ferdie.address), 'NFT');
- const offMinting = api.tx.unique.setMintPermission(collectionId, false);
- await Promise.all([
- mintItem.signAndSend(Ferdie),
- offMinting.signAndSend(Alice),
- ]);
- let itemList = false;
- itemList = (await (api.query.unique.nftItemList(collectionId, mintItem))).toJSON() as boolean;
- // tslint:disable-next-line: no-unused-expression
- expect(itemList).to.be.null;
- await waitNewBlocks(2);
- });
- });
-});
-*/
\ No newline at end of file
tests/src/contracts.test.tsdiffbeforeafterboth--- a/tests/src/contracts.test.ts
+++ /dev/null
@@ -1,240 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import usingApi, {submitTransactionAsync} from './substrate/substrate-api';
-import fs from 'fs';
-import {Abi, ContractPromise as Contract} from '@polkadot/api-contract';
-import {
- deployFlipper,
- getFlipValue,
- deployTransferContract,
-} from './util/contracthelpers';
-
-import {
- addToAllowListExpectSuccess,
- approveExpectSuccess,
- createCollectionExpectSuccess,
- createItemExpectSuccess,
- enablePublicMintingExpectSuccess,
- enableAllowListExpectSuccess,
- getGenericResult,
- normalizeAccountId,
- isAllowlisted,
- transferFromExpectSuccess,
- getTokenOwner,
-} from './util/helpers';
-
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-const value = 0;
-const gasLimit = 9000n * 1000000n;
-const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';
-
-// todo:playgrounds skipped ~ postponed
-describe.skip('Contracts', () => {
- it('Can deploy smart contract Flipper, instantiate it and call it\'s get and flip messages.', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
- const initialGetResponse = await getFlipValue(contract, deployer);
-
- const bob = privateKeyWrapper('//Bob');
- const flip = contract.tx.flip({value, gasLimit});
- await submitTransactionAsync(bob, flip);
-
- const afterFlipGetResponse = await getFlipValue(contract, deployer);
- expect(afterFlipGetResponse).not.to.be.eq(initialGetResponse, 'Flipping should change value.');
- });
- });
-
- it('Can initialize contract instance', async () => {
- await usingApi(async (api) => {
- const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));
- const abi = new Abi(metadata);
- const newContractInstance = new Contract(api, abi, marketContractAddress);
- expect(newContractInstance).to.have.property('address');
- expect(newContractInstance.address.toString()).to.equal(marketContractAddress);
- });
- });
-});
-
-describe.skip('Chain extensions', () => {
- it('Transfer CE', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const alice = privateKeyWrapper('//Alice');
- const bob = privateKeyWrapper('//Bob');
-
- // Prep work
- const collectionId = await createCollectionExpectSuccess();
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
- const [contract] = await deployTransferContract(api, privateKeyWrapper);
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, contract.address);
- await submitTransactionAsync(alice, changeAdminTx);
-
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
-
- // Transfer
- const transferTx = contract.tx.transfer({value, gasLimit}, bob.address, collectionId, tokenId, 1);
- const events = await submitTransactionAsync(alice, transferTx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));
- });
- });
-
- it('Mint CE', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const alice = privateKeyWrapper('//Alice');
- const bob = privateKeyWrapper('//Bob');
-
- const collectionId = await createCollectionExpectSuccess();
- const [contract] = await deployTransferContract(api, privateKeyWrapper);
- await enablePublicMintingExpectSuccess(alice, collectionId);
- await enableAllowListExpectSuccess(alice, collectionId);
- await addToAllowListExpectSuccess(alice, collectionId, contract.address);
- await addToAllowListExpectSuccess(alice, collectionId, bob.address);
-
- const transferTx = contract.tx.createItem({value, gasLimit}, bob.address, collectionId, {Nft: {const_data: '0x010203'}});
- const events = await submitTransactionAsync(alice, transferTx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- const tokensAfter = (await api.query.unique.nftItemList.entries(collectionId)).map((kv: any) => kv[1].toJSON());
- expect(tokensAfter).to.be.deep.equal([
- {
- owner: bob.address,
- constData: '0x010203',
- },
- ]);
- });
- });
-
- it('Bulk mint CE', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const alice = privateKeyWrapper('//Alice');
- const bob = privateKeyWrapper('//Bob');
-
- const collectionId = await createCollectionExpectSuccess();
- const [contract] = await deployTransferContract(api, privateKeyWrapper);
- await enablePublicMintingExpectSuccess(alice, collectionId);
- await enableAllowListExpectSuccess(alice, collectionId);
- await addToAllowListExpectSuccess(alice, collectionId, contract.address);
- await addToAllowListExpectSuccess(alice, collectionId, bob.address);
-
- const transferTx = contract.tx.createMultipleItems({value, gasLimit}, bob.address, collectionId, [
- {NFT: {/*const_data: '0x010203'*/}},
- {NFT: {/*const_data: '0x010204'*/}},
- {NFT: {/*const_data: '0x010205'*/}},
- ]);
- const events = await submitTransactionAsync(alice, transferTx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- const tokensAfter: any = (await api.query.unique.nftItemList.entries(collectionId) as any)
- .map((kv: any) => kv[1].toJSON())
- .sort((a: any, b: any) => a.constData.localeCompare(b.constData));
- expect(tokensAfter).to.be.deep.equal([
- {
- Owner: bob.address,
- //ConstData: '0x010203',
- },
- {
- Owner: bob.address,
- //ConstData: '0x010204',
- },
- {
- Owner: bob.address,
- //ConstData: '0x010205',
- },
- ]);
- });
- });
-
- it('Approve CE', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const alice = privateKeyWrapper('//Alice');
- const bob = privateKeyWrapper('//Bob');
- const charlie = privateKeyWrapper('//Charlie');
-
- const collectionId = await createCollectionExpectSuccess();
- const [contract] = await deployTransferContract(api, privateKeyWrapper);
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());
-
- const transferTx = contract.tx.approve({value, gasLimit}, bob.address, collectionId, tokenId, 1);
- const events = await submitTransactionAsync(alice, transferTx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- await transferFromExpectSuccess(collectionId, tokenId, bob, normalizeAccountId(contract.address.toString()), charlie, 1, 'NFT');
- });
- });
-
- it('TransferFrom CE', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const alice = privateKeyWrapper('//Alice');
- const bob = privateKeyWrapper('//Bob');
- const charlie = privateKeyWrapper('//Charlie');
-
- const collectionId = await createCollectionExpectSuccess();
- const [contract] = await deployTransferContract(api, privateKeyWrapper);
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
- await approveExpectSuccess(collectionId, tokenId, bob, contract.address.toString(), 1);
-
- const transferTx = contract.tx.transferFrom({value, gasLimit}, bob.address, charlie.address, collectionId, tokenId, 1);
- const events = await submitTransactionAsync(alice, transferTx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- const token: any = (await api.query.unique.nftItemList(collectionId, tokenId) as any).unwrap();
- expect(token.owner.toString()).to.be.equal(charlie.address);
- });
- });
-
- it('ToggleAllowList CE', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const alice = privateKeyWrapper('//Alice');
- const bob = privateKeyWrapper('//Bob');
-
- const collectionId = await createCollectionExpectSuccess();
- const [contract] = await deployTransferContract(api, privateKeyWrapper);
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, contract.address);
- await submitTransactionAsync(alice, changeAdminTx);
-
- expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
-
- {
- const transferTx = contract.tx.toggleAllowList({value, gasLimit}, collectionId, bob.address, true);
- const events = await submitTransactionAsync(alice, transferTx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- expect(await isAllowlisted(api, collectionId, bob.address)).to.be.true;
- }
- {
- const transferTx = contract.tx.toggleAllowList({value, gasLimit}, collectionId, bob.address, false);
- const events = await submitTransactionAsync(alice, transferTx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
- }
- });
- });
-});
tests/src/createMultipleItemsEx.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItemsEx.test.ts
+++ b/tests/src/createMultipleItemsEx.test.ts
@@ -178,13 +178,12 @@
tokenPrefix: 'COL',
}, 0);
- const api = helper.api;
- await helper.signTransaction(alice, api?.tx.unique.createMultipleItemsEx(collection.collectionId, {
+ await helper.executeExtrinsic(alice, 'api.tx.unique.createMultipleItemsEx',[collection.collectionId, {
Fungible: new Map([
[JSON.stringify({Substrate: alice.address}), 50],
[JSON.stringify({Substrate: bob.address}), 100],
]),
- }));
+ }], true);
expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(50n);
expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(100n);
@@ -200,8 +199,7 @@
],
});
- const api = helper.api;
- await helper.signTransaction(alice, api?.tx.unique.createMultipleItemsEx(collection.collectionId, {
+ await helper.executeExtrinsic(alice, 'api.tx.unique.createMultipleItemsEx', [collection.collectionId, {
RefungibleMultipleOwners: {
users: new Map([
[JSON.stringify({Substrate: alice.address}), 1],
@@ -211,7 +209,7 @@
{key: 'k', value: 'v'},
],
},
- }));
+ }], true);
const tokenId = await collection.getLastTokenId();
expect(tokenId).to.be.equal(1);
expect(await collection.getTokenBalance(1, {Substrate: alice.address})).to.be.equal(1n);
@@ -228,9 +226,7 @@
],
});
- const api = helper.api;
-
- await helper.signTransaction(alice, api?.tx.unique.createMultipleItemsEx(collection.collectionId, {
+ await helper.executeExtrinsic(alice, 'api.tx.unique.createMultipleItemsEx', [collection.collectionId, {
RefungibleMultipleItems: [
{
user: {Substrate: alice.address}, pieces: 1,
@@ -245,7 +241,7 @@
],
},
],
- }));
+ }], true);
expect(await collection.getLastTokenId()).to.be.equal(2);
expect(await collection.getTokenBalance(1, {Substrate: alice.address})).to.be.equal(1n);
tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -29,7 +29,7 @@
/*eslint no-async-promise-executor: "off"*/
function skipInflationBlock(api: ApiPromise): Promise<void> {
const promise = new Promise<void>(async (resolve) => {
- const blockInterval = (await api.consts.inflation.inflationBlockInterval).toNumber();
+ const blockInterval = api.consts.inflation.inflationBlockInterval.toNumber();
const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {
const currentBlock = head.number.toNumber();
if (currentBlock % blockInterval < blockInterval - 10) {
@@ -56,21 +56,21 @@
});
itSub('Total issuance does not change', async ({helper}) => {
- const api = helper.api!;
+ const api = helper.getApi();
await skipInflationBlock(api);
await helper.wait.newBlocks(1);
- const totalBefore = (await api.query.balances.totalIssuance()).toBigInt();
+ const totalBefore = (await helper.callRpc('api.query.balances.totalIssuance', [])).toBigInt();
await helper.balance.transferToSubstrate(alice, bob.address, 1n);
- const totalAfter = (await api.query.balances.totalIssuance()).toBigInt();
+ const totalAfter = (await helper.callRpc('api.query.balances.totalIssuance', [])).toBigInt();
expect(totalAfter).to.be.equal(totalBefore);
});
itSub('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async ({helper}) => {
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
@@ -89,7 +89,7 @@
});
itSub('Treasury balance increased by failed tx fee', async ({helper}) => {
- const api = helper.api!;
+ const api = helper.getApi();
await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
@@ -107,7 +107,7 @@
});
itSub('NFT Transactions also send fees to Treasury', async ({helper}) => {
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
@@ -125,7 +125,7 @@
itSub('Fees are sane', async ({helper}) => {
const unique = helper.balance.getOneTokenNominal();
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
@@ -140,7 +140,7 @@
});
itSub('NFT Transfer fee is close to 0.1 Unique', async ({helper}) => {
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const collection = await helper.nft.mintCollection(alice, {
tests/src/deprecated-helpers/contracthelpers.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/deprecated-helpers/contracthelpers.ts
@@ -0,0 +1,114 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import {submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
+import fs from 'fs';
+import {Abi, CodePromise, ContractPromise as Contract} from '@polkadot/api-contract';
+import {IKeyringPair} from '@polkadot/types/types';
+import {ApiPromise} from '@polkadot/api';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+import {findUnusedAddress, getGenericResult} from './helpers';
+
+const value = 0;
+const gasLimit = '200000000000';
+const endowment = '100000000000000000';
+
+/* eslint no-async-promise-executor: "off" */
+function deployContract(alice: IKeyringPair, code: CodePromise, constructor = 'default', ...args: any[]): Promise<Contract> {
+ return new Promise<Contract>(async (resolve) => {
+ const unsub = await (code as any)
+ .tx[constructor]({value: endowment, gasLimit}, ...args)
+ .signAndSend(alice, (result: any) => {
+ if (result.status.isInBlock || result.status.isFinalized) {
+ // here we have an additional field in the result, containing the blueprint
+ resolve((result as any).contract);
+ unsub();
+ }
+ });
+ });
+}
+
+async function prepareDeployer(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) {
+ // Find unused address
+ const deployer = await findUnusedAddress(api, privateKeyWrapper);
+
+ // Transfer balance to it
+ const alice = privateKeyWrapper('//Alice');
+ const amount = BigInt(endowment) + 10n**15n;
+ const tx = api.tx.balances.transfer(deployer.address, amount);
+ await submitTransactionAsync(alice, tx);
+
+ return deployer;
+}
+
+export async function deployFlipper(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
+ const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));
+ const abi = new Abi(metadata);
+
+ const deployer = await prepareDeployer(api, privateKeyWrapper);
+
+ const wasm = fs.readFileSync('./src/flipper/flipper.wasm');
+
+ const code = new CodePromise(api, abi, wasm);
+
+ const contract = (await deployContract(deployer, code, 'new', true)) as Contract;
+
+ const initialGetResponse = await getFlipValue(contract, deployer);
+ expect(initialGetResponse).to.be.true;
+
+ return [contract, deployer];
+}
+
+export async function getFlipValue(contract: Contract, deployer: IKeyringPair) {
+ const result = await contract.query.get(deployer.address, {value, gasLimit});
+
+ if(!result.result.isOk) {
+ throw 'Failed to get flipper value';
+ }
+ return (result.result.asOk.data[0] == 0x00) ? false : true;
+}
+
+export async function toggleFlipValueExpectSuccess(sender: IKeyringPair, contract: Contract) {
+ const tx = contract.tx.flip({value, gasLimit});
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+}
+
+export async function toggleFlipValueExpectFailure(sender: IKeyringPair, contract: Contract) {
+ const tx = contract.tx.flip({value, gasLimit});
+ await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+}
+
+export async function deployTransferContract(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
+ const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));
+ const abi = new Abi(metadata);
+
+ const deployer = await prepareDeployer(api, privateKeyWrapper);
+
+ const wasm = fs.readFileSync('./src/transfer_contract/nft_transfer.wasm');
+
+ const code = new CodePromise(api, abi, wasm);
+
+ const contract = await deployContract(deployer, code);
+
+ return [contract, deployer];
+}
tests/src/deprecated-helpers/eth/helpers.d.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/deprecated-helpers/eth/helpers.d.ts
@@ -0,0 +1,17 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+declare module 'solc';
\ No newline at end of file
tests/src/deprecated-helpers/eth/helpers.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/deprecated-helpers/eth/helpers.ts
@@ -0,0 +1,451 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+// eslint-disable-next-line @typescript-eslint/triple-slash-reference
+/// <reference path="helpers.d.ts" />
+
+import {ApiPromise} from '@polkadot/api';
+import {IKeyringPair} from '@polkadot/types/types';
+import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';
+import {expect} from 'chai';
+import * as solc from 'solc';
+import Web3 from 'web3';
+import config from '../../config';
+import getBalance from '../../substrate/get-balance';
+import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';
+import waitNewBlocks from '../../substrate/wait-new-blocks';
+import {CollectionMode, CrossAccountId, getDetailedCollectionInfo, getGenericResult, UNIQUE} from '../helpers';
+import collectionHelpersAbi from '../../eth/collectionHelpersAbi.json';
+import fungibleAbi from '../../eth/fungibleAbi.json';
+import nonFungibleAbi from '../../eth/nonFungibleAbi.json';
+import refungibleAbi from '../../eth/reFungibleAbi.json';
+import refungibleTokenAbi from '../../eth/reFungibleTokenAbi.json';
+import contractHelpersAbi from '../../eth/util/contractHelpersAbi.json';
+
+export const GAS_ARGS = {gas: 2500000};
+
+export enum SponsoringMode {
+ Disabled = 0,
+ Allowlisted = 1,
+ Generous = 2,
+}
+
+let web3Connected = false;
+export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {
+ if (web3Connected) throw new Error('do not nest usingWeb3 calls');
+ web3Connected = true;
+
+ const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);
+ const web3 = new Web3(provider);
+
+ try {
+ return await cb(web3);
+ } finally {
+ // provider.disconnect(3000, 'normal disconnect');
+ provider.connection.close();
+ web3Connected = false;
+ }
+}
+
+function encodeIntBE(v: number): number[] {
+ if (v >= 0xffffffff || v < 0) throw new Error('id overflow');
+ return [
+ v >> 24,
+ (v >> 16) & 0xff,
+ (v >> 8) & 0xff,
+ v & 0xff,
+ ];
+}
+
+export async function getCollectionAddressFromResult(api: ApiPromise, result: any) {
+ const collectionIdAddress = normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const collectionId = collectionIdFromAddress(collectionIdAddress);
+ const collection = (await getDetailedCollectionInfo(api, collectionId))!;
+ return {collectionIdAddress, collectionId, collection};
+}
+
+export function collectionIdToAddress(collection: number): string {
+ const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
+ ...encodeIntBE(collection),
+ ]);
+ return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
+}
+export function collectionIdFromAddress(address: string): number {
+ if (!address.startsWith('0x'))
+ throw 'address not starts with "0x"';
+ if (address.length > 42)
+ throw 'address length is more than 20 bytes';
+ return Number('0x' + address.substring(address.length - 8));
+}
+
+export function normalizeAddress(address: string): string {
+ return '0x' + address.substring(address.length - 40);
+}
+
+export function tokenIdToAddress(collection: number, token: number): string {
+ const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
+ ...encodeIntBE(collection),
+ ...encodeIntBE(token),
+ ]);
+ return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
+}
+
+export function tokenIdFromAddress(address: string) {
+ if (!address.startsWith('0x'))
+ throw 'address not starts with "0x"';
+ if (address.length > 42)
+ throw 'address length is more than 20 bytes';
+ return {
+ collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),
+ tokenId: Number('0x' + address.substring(address.length - 8)),
+ };
+}
+
+export function tokenIdToCross(collection: number, token: number): CrossAccountId {
+ return {
+ Ethereum: tokenIdToAddress(collection, token),
+ };
+}
+
+export function createEthAccount(web3: Web3) {
+ const account = web3.eth.accounts.create();
+ web3.eth.accounts.wallet.add(account.privateKey);
+ return account.address;
+}
+
+export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair) {
+ const alice = privateKeyWrapper('//Alice');
+ const account = createEthAccount(web3);
+ await transferBalanceToEth(api, alice, account);
+
+ return account;
+}
+
+export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {
+ const tx = api.tx.balances.transfer(evmToAddress(target), amount);
+ const events = await submitTransactionAsync(source, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+}
+
+export async function createRFTCollection(api: ApiPromise, web3: Web3, owner: string) {
+ const collectionHelper = evmCollectionHelpers(web3, owner);
+ const result = await collectionHelper.methods
+ .createRFTCollection('A', 'B', 'C')
+ .send({value: Number(2n * UNIQUE)});
+ return await getCollectionAddressFromResult(api, result);
+}
+
+
+export async function createNonfungibleCollection(api: ApiPromise, web3: Web3, owner: string) {
+ const collectionHelper = evmCollectionHelpers(web3, owner);
+ const result = await collectionHelper.methods
+ .createNonfungibleCollection('A', 'B', 'C')
+ .send({value: Number(2n * UNIQUE)});
+ return await getCollectionAddressFromResult(api, result);
+}
+
+export function uniqueNFT(web3: Web3, address: string, owner: string) {
+ return new web3.eth.Contract(nonFungibleAbi as any, address, {
+ from: owner,
+ ...GAS_ARGS,
+ });
+}
+
+export function uniqueRefungible(web3: Web3, collectionAddress: string, owner: string) {
+ return new web3.eth.Contract(refungibleAbi as any, collectionAddress, {
+ from: owner,
+ ...GAS_ARGS,
+ });
+}
+
+export function uniqueRefungibleToken(web3: Web3, tokenAddress: string, owner: string | undefined = undefined) {
+ return new web3.eth.Contract(refungibleTokenAbi as any, tokenAddress, {
+ from: owner,
+ ...GAS_ARGS,
+ });
+}
+
+export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
+ let i: any = it;
+ if (opts.only) i = i.only;
+ else if (opts.skip) i = i.skip;
+ i(name, async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ await usingWeb3(async web3 => {
+ await cb({api, web3, privateKeyWrapper});
+ });
+ });
+ });
+}
+itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {only: true});
+itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {skip: true});
+
+export async function generateSubstrateEthPair(web3: Web3) {
+ const account = web3.eth.accounts.create();
+ evmToAddress(account.address);
+}
+
+type NormalizedEvent = {
+ address: string,
+ event: string,
+ args: { [key: string]: string }
+};
+
+export function normalizeEvents(events: any): NormalizedEvent[] {
+ const output = [];
+ for (const key of Object.keys(events)) {
+ if (key.match(/^[0-9]+$/)) {
+ output.push(events[key]);
+ } else if (Array.isArray(events[key])) {
+ output.push(...events[key]);
+ } else {
+ output.push(events[key]);
+ }
+ }
+ output.sort((a, b) => a.logIndex - b.logIndex);
+ return output.map(({address, event, returnValues}) => {
+ const args: { [key: string]: string } = {};
+ for (const key of Object.keys(returnValues)) {
+ if (!key.match(/^[0-9]+$/)) {
+ args[key] = returnValues[key];
+ }
+ }
+ return {
+ address,
+ event,
+ args,
+ };
+ });
+}
+
+export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {
+ const out: any = [];
+ contract.events.allEvents((_: any, event: any) => {
+ out.push(event);
+ });
+ await action();
+ 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 {
+ return Web3.utils.toChecksumAddress(subToEthLowercase(eth));
+}
+
+export interface CompiledContract {
+ abi: any,
+ object: string,
+}
+
+export function compileContract(name: string, src: string) : CompiledContract {
+ const out = JSON.parse(solc.compile(JSON.stringify({
+ language: 'Solidity',
+ sources: {
+ [`${name}.sol`]: {
+ content: `
+ // SPDX-License-Identifier: UNLICENSED
+ pragma solidity ^0.8.6;
+
+ ${src}
+ `,
+ },
+ },
+ settings: {
+ outputSelection: {
+ '*': {
+ '*': ['*'],
+ },
+ },
+ },
+ }))).contracts[`${name}.sol`][name];
+
+ return {
+ abi: out.abi,
+ object: '0x' + out.evm.bytecode.object,
+ };
+}
+
+export async function deployFlipper(web3: Web3, deployer: string) {
+ const compiled = compileContract('Flipper', `
+ contract Flipper {
+ bool value = false;
+ function flip() public {
+ value = !value;
+ }
+ function getValue() public view returns (bool) {
+ return value;
+ }
+ }
+ `);
+ const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {
+ data: compiled.object,
+ from: deployer,
+ ...GAS_ARGS,
+ });
+ const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});
+
+ return flipper;
+}
+
+export async function deployCollector(web3: Web3, deployer: string) {
+ const compiled = compileContract('Collector', `
+ contract Collector {
+ uint256 collected;
+ fallback() external payable {
+ giveMoney();
+ }
+ function giveMoney() public payable {
+ collected += msg.value;
+ }
+ function getCollected() public view returns (uint256) {
+ return collected;
+ }
+ function getUnaccounted() public view returns (uint256) {
+ return address(this).balance - collected;
+ }
+
+ function withdraw(address payable target) public {
+ target.transfer(collected);
+ collected = 0;
+ }
+ }
+ `);
+ const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {
+ data: compiled.object,
+ from: deployer,
+ ...GAS_ARGS,
+ });
+ const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});
+
+ return collector;
+}
+
+/**
+ * pallet evm_contract_helpers
+ * @param web3
+ * @param caller - eth address
+ * @returns
+ */
+export function contractHelpers(web3: Web3, caller: string) {
+ return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});
+}
+
+/**
+ * evm collection helper
+ * @param web3
+ * @param caller - eth address
+ * @returns
+ */
+export function evmCollectionHelpers(web3: Web3, caller: string) {
+ return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
+}
+
+/**
+ * evm collection
+ * @param web3
+ * @param caller - eth address
+ * @returns
+ */
+export function evmCollection(web3: Web3, caller: string, collection: string, mode: CollectionMode = {type: 'NFT'}) {
+ let abi;
+ switch (mode.type) {
+ case 'Fungible':
+ abi = fungibleAbi;
+ break;
+
+ case 'NFT':
+ abi = nonFungibleAbi;
+ break;
+
+ case 'ReFungible':
+ abi = refungibleAbi;
+ break;
+
+ default:
+ throw 'Bad collection mode';
+ }
+ const contract = new web3.eth.Contract(abi as any, collection, {from: caller, ...GAS_ARGS});
+ return contract;
+}
+
+/**
+ * Execute ethereum method call using substrate account
+ * @param to target contract
+ * @param mkTx - closure, receiving `contract.methods`, and returning method call,
+ * to be used as following (assuming `to` = erc20 contract):
+ * `m => m.transfer(to, amount)`
+ *
+ * # Example
+ * ```ts
+ * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));
+ * ```
+ */
+export async function executeEthTxOnSub(web3: Web3, 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,
+ await web3.eth.getGasPrice(),
+ null,
+ null,
+ [],
+ );
+ const events = await submitTransactionAsync(from, tx);
+ expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;
+}
+
+export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {
+ return (await getBalance(api, [evmToAddress(address)]))[0];
+}
+
+/**
+ * Measure how much gas given closure consumes
+ *
+ * @param user which user balance will be checked
+ */
+export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {
+ const before = await ethBalanceViaSub(api, user);
+
+ await call();
+
+ // In dev mode, the transaction might not finish processing in time
+ await waitNewBlocks(api, 1);
+ const after = await ethBalanceViaSub(api, user);
+
+ // Can't use .to.be.less, because chai doesn't supports bigint
+ expect(after < before).to.be.true;
+
+ return before - after;
+}
+
+type ElementOf<A> = A extends readonly (infer T)[] ? T : never;
+// I want a fancier api, not a memory efficiency
+export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {
+ if(args.length === 0) {
+ yield internalRest as any;
+ return;
+ }
+ for(const value of args[0]) {
+ yield* cartesian([...internalRest, value], ...args.slice(1)) as any;
+ }
+}
\ No newline at end of file
tests/src/deprecated-helpers/helpers.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/deprecated-helpers/helpers.ts
@@ -0,0 +1,1879 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import '../interfaces/augment-api-rpc';
+import '../interfaces/augment-api-query';
+import {ApiPromise, Keyring} from '@polkadot/api';
+import type {AccountId, EventRecord, Event, BlockNumber} from '@polkadot/types/interfaces';
+import type {GenericEventData} from '@polkadot/types';
+import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';
+import {evmToAddress} from '@polkadot/util-crypto';
+import {AnyNumber} from '@polkadot/types-codec/types';
+import BN from 'bn.js';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
+import {hexToStr, strToUTF16, utf16ToStr} from './util';
+import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';
+import {UpDataStructsTokenChild} from '../interfaces';
+import {Context} from 'mocha';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+export type CrossAccountId = {
+ Substrate: string,
+} | {
+ Ethereum: string,
+};
+
+
+export enum Pallets {
+ Inflation = 'inflation',
+ RmrkCore = 'rmrkcore',
+ RmrkEquip = 'rmrkequip',
+ ReFungible = 'refungible',
+ Fungible = 'fungible',
+ NFT = 'nonfungible',
+ Scheduler = 'scheduler',
+ AppPromotion = 'apppromotion',
+}
+
+export async function isUnique(): Promise<boolean> {
+ return usingApi(async api => {
+ const chain = await api.rpc.system.chain();
+
+ return chain.eq('UNIQUE');
+ });
+}
+
+export async function isQuartz(): Promise<boolean> {
+ return usingApi(async api => {
+ const chain = await api.rpc.system.chain();
+
+ return chain.eq('QUARTZ');
+ });
+}
+
+let modulesNames: any;
+export function getModuleNames(api: ApiPromise): string[] {
+ if (typeof modulesNames === 'undefined')
+ modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());
+ return modulesNames;
+}
+
+export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {
+ return await usingApi(async api => {
+ const pallets = getModuleNames(api);
+
+ return requiredPallets.filter(p => !pallets.includes(p));
+ });
+}
+
+export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {
+ return (await missingRequiredPallets(requiredPallets)).length == 0;
+}
+
+export async function requirePallets(mocha: Context, requiredPallets: string[]) {
+ const missingPallets = await missingRequiredPallets(requiredPallets);
+
+ if (missingPallets.length > 0) {
+ const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;
+ const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;
+ const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;
+
+ console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);
+
+ mocha.skip();
+ }
+}
+
+export function bigIntToSub(api: ApiPromise, number: bigint) {
+ return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();
+}
+
+export function bigIntToDecimals(number: bigint, decimals = 18): string {
+ const numberStr = number.toString();
+ const dotPos = numberStr.length - decimals;
+
+ if (dotPos <= 0) {
+ return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;
+ } else {
+ const intPart = numberStr.substring(0, dotPos);
+ const fractPart = numberStr.substring(dotPos);
+ return intPart + '.' + fractPart;
+ }
+}
+
+export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {
+ if (typeof input === 'string') {
+ if (input.length >= 47) {
+ return {Substrate: input};
+ } else if (input.length === 42 && input.startsWith('0x')) {
+ return {Ethereum: input.toLowerCase()};
+ } else if (input.length === 40 && !input.startsWith('0x')) {
+ return {Ethereum: '0x' + input.toLowerCase()};
+ } else {
+ throw new Error(`Unknown address format: "${input}"`);
+ }
+ }
+ if ('address' in input) {
+ return {Substrate: input.address};
+ }
+ if ('Ethereum' in input) {
+ return {
+ Ethereum: input.Ethereum.toLowerCase(),
+ };
+ } else if ('ethereum' in input) {
+ return {
+ Ethereum: (input as any).ethereum.toLowerCase(),
+ };
+ } else if ('Substrate' in input) {
+ return input;
+ } else if ('substrate' in input) {
+ return {
+ Substrate: (input as any).substrate,
+ };
+ }
+
+ // AccountId
+ return {Substrate: input.toString()};
+}
+export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {
+ input = normalizeAccountId(input);
+ if ('Substrate' in input) {
+ return input.Substrate;
+ } else {
+ return evmToAddress(input.Ethereum);
+ }
+}
+
+export const U128_MAX = (1n << 128n) - 1n;
+
+const MICROUNIQUE = 1_000_000_000_000n;
+const MILLIUNIQUE = 1_000n * MICROUNIQUE;
+const CENTIUNIQUE = 10n * MILLIUNIQUE;
+export const UNIQUE = 100n * CENTIUNIQUE;
+
+interface GenericResult<T> {
+ success: boolean;
+ data: T | null;
+}
+
+interface CreateCollectionResult {
+ success: boolean;
+ collectionId: number;
+}
+
+interface CreateItemResult {
+ success: boolean;
+ collectionId: number;
+ itemId: number;
+ recipient?: CrossAccountId;
+ amount?: number;
+}
+
+interface DestroyItemResult {
+ success: boolean;
+ collectionId: number;
+ itemId: number;
+ owner: CrossAccountId;
+ amount: number;
+}
+
+interface TransferResult {
+ collectionId: number;
+ itemId: number;
+ sender?: CrossAccountId;
+ recipient?: CrossAccountId;
+ value: bigint;
+}
+
+interface IReFungibleOwner {
+ fraction: BN;
+ owner: number[];
+}
+
+interface IGetMessage {
+ checkMsgUnqMethod: string;
+ checkMsgTrsMethod: string;
+ checkMsgSysMethod: string;
+}
+
+export interface IFungibleTokenDataType {
+ value: number;
+}
+
+export interface IChainLimits {
+ collectionNumbersLimit: number;
+ accountTokenOwnershipLimit: number;
+ collectionsAdminsLimit: number;
+ customDataLimit: number;
+ nftSponsorTransferTimeout: number;
+ fungibleSponsorTransferTimeout: number;
+ refungibleSponsorTransferTimeout: number;
+ //offchainSchemaLimit: number;
+ //constOnChainSchemaLimit: number;
+}
+
+export interface IReFungibleTokenDataType {
+ owner: IReFungibleOwner[];
+}
+
+export function uniqueEventMessage(events: EventRecord[]): IGetMessage {
+ let checkMsgUnqMethod = '';
+ let checkMsgTrsMethod = '';
+ let checkMsgSysMethod = '';
+ events.forEach(({event: {method, section}}) => {
+ if (section === 'common') {
+ checkMsgUnqMethod = method;
+ } else if (section === 'treasury') {
+ checkMsgTrsMethod = method;
+ } else if (section === 'system') {
+ checkMsgSysMethod = method;
+ } else { return null; }
+ });
+ const result: IGetMessage = {
+ checkMsgUnqMethod,
+ checkMsgTrsMethod,
+ checkMsgSysMethod,
+ };
+ return result;
+}
+
+export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {
+ const event = events.find(r => check(r.event));
+ if (!event) return;
+ return event.event as T;
+}
+
+export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;
+export function getGenericResult<T>(
+ events: EventRecord[],
+ expectSection: string,
+ expectMethod: string,
+ extractAction: (data: GenericEventData) => T
+): GenericResult<T>;
+
+export function getGenericResult<T>(
+ events: EventRecord[],
+ expectSection?: string,
+ expectMethod?: string,
+ extractAction?: (data: GenericEventData) => T,
+): GenericResult<T> {
+ let success = false;
+ let successData = null;
+
+ events.forEach(({event: {data, method, section}}) => {
+ // console.log(` ${phase}: ${section}.${method}:: ${data}`);
+ if (method === 'ExtrinsicSuccess') {
+ success = true;
+ } else if ((expectSection == section) && (expectMethod == method)) {
+ successData = extractAction!(data as any);
+ }
+ });
+
+ const result: GenericResult<T> = {
+ success,
+ data: successData,
+ };
+ return result;
+}
+
+export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {
+ const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));
+ const result: CreateCollectionResult = {
+ success: genericResult.success,
+ collectionId: genericResult.data ?? 0,
+ };
+ return result;
+}
+
+export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {
+ const results: CreateItemResult[] = [];
+
+ const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {
+ const collectionId = parseInt(data[0].toString(), 10);
+ const itemId = parseInt(data[1].toString(), 10);
+ const recipient = normalizeAccountId(data[2].toJSON() as any);
+ const amount = parseInt(data[3].toString(), 10);
+
+ const itemRes: CreateItemResult = {
+ success: true,
+ collectionId,
+ itemId,
+ recipient,
+ amount,
+ };
+
+ results.push(itemRes);
+ return results;
+ });
+
+ if (!genericResult.success) return [];
+ return results;
+}
+
+export function getCreateItemResult(events: EventRecord[]): CreateItemResult {
+ const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));
+
+ if (genericResult.data == null)
+ return {
+ success: genericResult.success,
+ collectionId: 0,
+ itemId: 0,
+ amount: 0,
+ };
+ else
+ return {
+ success: genericResult.success,
+ collectionId: genericResult.data[0] as number,
+ itemId: genericResult.data[1] as number,
+ recipient: normalizeAccountId(genericResult.data![2] as any),
+ amount: genericResult.data[3] as number,
+ };
+}
+
+export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {
+ const results: DestroyItemResult[] = [];
+
+ const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {
+ const collectionId = parseInt(data[0].toString(), 10);
+ const itemId = parseInt(data[1].toString(), 10);
+ const owner = normalizeAccountId(data[2].toJSON() as any);
+ const amount = parseInt(data[3].toString(), 10);
+
+ const itemRes: DestroyItemResult = {
+ success: true,
+ collectionId,
+ itemId,
+ owner,
+ amount,
+ };
+
+ results.push(itemRes);
+ return results;
+ });
+
+ if (!genericResult.success) return [];
+ return results;
+}
+
+export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {
+ for (const {event} of events) {
+ if (api.events.common.Transfer.is(event)) {
+ const [collection, token, sender, recipient, value] = event.data;
+ return {
+ collectionId: collection.toNumber(),
+ itemId: token.toNumber(),
+ sender: normalizeAccountId(sender.toJSON() as any),
+ recipient: normalizeAccountId(recipient.toJSON() as any),
+ value: value.toBigInt(),
+ };
+ }
+ }
+ throw new Error('no transfer event');
+}
+
+interface Nft {
+ type: 'NFT';
+}
+
+interface Fungible {
+ type: 'Fungible';
+ decimalPoints: number;
+}
+
+interface ReFungible {
+ type: 'ReFungible';
+}
+
+export type CollectionMode = Nft | Fungible | ReFungible;
+
+export type Property = {
+ key: any,
+ value: any,
+};
+
+type Permission = {
+ mutable: boolean;
+ collectionAdmin: boolean;
+ tokenOwner: boolean;
+}
+
+type PropertyPermission = {
+ key: any;
+ permission: Permission;
+}
+
+export type CreateCollectionParams = {
+ mode: CollectionMode,
+ name: string,
+ description: string,
+ tokenPrefix: string,
+ properties?: Array<Property>,
+ propPerm?: Array<PropertyPermission>
+};
+
+const defaultCreateCollectionParams: CreateCollectionParams = {
+ description: 'description',
+ mode: {type: 'NFT'},
+ name: 'name',
+ tokenPrefix: 'prefix',
+};
+
+export async function
+createCollection(
+ api: ApiPromise,
+ sender: IKeyringPair,
+ params: Partial<CreateCollectionParams> = {},
+): Promise<CreateCollectionResult> {
+ const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
+
+ let modeprm = {};
+ if (mode.type === 'NFT') {
+ modeprm = {nft: null};
+ } else if (mode.type === 'Fungible') {
+ modeprm = {fungible: mode.decimalPoints};
+ } else if (mode.type === 'ReFungible') {
+ modeprm = {refungible: null};
+ }
+
+ const tx = api.tx.unique.createCollectionEx({
+ name: strToUTF16(name),
+ description: strToUTF16(description),
+ tokenPrefix: strToUTF16(tokenPrefix),
+ mode: modeprm as any,
+ });
+ const events = await executeTransaction(api, sender, tx);
+ return getCreateCollectionResult(events);
+}
+
+export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
+ const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
+
+ let collectionId = 0;
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Get number of collections before the transaction
+ const collectionCountBefore = await getCreatedCollectionCount(api);
+
+ // Run the CreateCollection transaction
+ const alicePrivateKey = privateKeyWrapper('//Alice');
+
+ const result = await createCollection(api, alicePrivateKey, params);
+
+ // Get number of collections after the transaction
+ const collectionCountAfter = await getCreatedCollectionCount(api);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, result.collectionId);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ expect(result.collectionId).to.be.equal(collectionCountAfter);
+ // tslint:disable-next-line:no-unused-expression
+ expect(collection).to.be.not.null;
+ expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');
+ expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));
+ expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);
+ expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);
+ expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);
+
+ collectionId = result.collectionId;
+ });
+
+ return collectionId;
+}
+
+export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
+ const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
+
+ let collectionId = 0;
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Get number of collections before the transaction
+ const collectionCountBefore = await getCreatedCollectionCount(api);
+
+ // Run the CreateCollection transaction
+ const alicePrivateKey = privateKeyWrapper('//Alice');
+
+ let modeprm = {};
+ if (mode.type === 'NFT') {
+ modeprm = {nft: null};
+ } else if (mode.type === 'Fungible') {
+ modeprm = {fungible: mode.decimalPoints};
+ } else if (mode.type === 'ReFungible') {
+ modeprm = {refungible: null};
+ }
+
+ const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});
+ const events = await submitTransactionAsync(alicePrivateKey, tx);
+ const result = getCreateCollectionResult(events);
+
+ // Get number of collections after the transaction
+ const collectionCountAfter = await getCreatedCollectionCount(api);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, result.collectionId);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ expect(result.collectionId).to.be.equal(collectionCountAfter);
+ // tslint:disable-next-line:no-unused-expression
+ expect(collection).to.be.not.null;
+ expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');
+ expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));
+ expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);
+ expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);
+ expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);
+
+
+ collectionId = result.collectionId;
+ });
+
+ return collectionId;
+}
+
+export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {
+ const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
+
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Get number of collections before the transaction
+ const collectionCountBefore = await getCreatedCollectionCount(api);
+
+ // Run the CreateCollection transaction
+ const alicePrivateKey = privateKeyWrapper('//Alice');
+
+ let modeprm = {};
+ if (mode.type === 'NFT') {
+ modeprm = {nft: null};
+ } else if (mode.type === 'Fungible') {
+ modeprm = {fungible: mode.decimalPoints};
+ } else if (mode.type === 'ReFungible') {
+ modeprm = {refungible: null};
+ }
+
+ const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
+
+
+ // Get number of collections after the transaction
+ const collectionCountAfter = await getCreatedCollectionCount(api);
+
+ expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
+ });
+}
+
+export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {
+ const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
+
+ let modeprm = {};
+ if (mode.type === 'NFT') {
+ modeprm = {nft: null};
+ } else if (mode.type === 'Fungible') {
+ modeprm = {fungible: mode.decimalPoints};
+ } else if (mode.type === 'ReFungible') {
+ modeprm = {refungible: null};
+ }
+
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Get number of collections before the transaction
+ const collectionCountBefore = await getCreatedCollectionCount(api);
+
+ // Run the CreateCollection transaction
+ const alicePrivateKey = privateKeyWrapper('//Alice');
+ const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
+
+ // Get number of collections after the transaction
+ const collectionCountAfter = await getCreatedCollectionCount(api);
+
+ // What to expect
+ expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
+ });
+}
+
+export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {
+ let bal = 0n;
+ let unused;
+ do {
+ const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;
+ unused = privateKeyWrapper(`//${randomSeed}`);
+ bal = (await api.query.system.account(unused.address)).data.free.toBigInt();
+ } while (bal !== 0n);
+ return unused;
+}
+
+export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {
+ return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();
+}
+
+export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {
+ return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));
+}
+
+export async function findNotExistingCollection(api: ApiPromise): Promise<number> {
+ const totalNumber = await getCreatedCollectionCount(api);
+ const newCollection: number = totalNumber + 1;
+ return newCollection;
+}
+
+function getDestroyResult(events: EventRecord[]): boolean {
+ let success = false;
+ events.forEach(({event: {method}}) => {
+ if (method == 'ExtrinsicSuccess') {
+ success = true;
+ }
+ });
+ return success;
+}
+
+export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Run the DestroyCollection transaction
+ const alicePrivateKey = privateKeyWrapper(senderSeed);
+ const tx = api.tx.unique.destroyCollection(collectionId);
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
+ });
+}
+
+export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+ // Run the DestroyCollection transaction
+ const alicePrivateKey = privateKeyWrapper(senderSeed);
+ const tx = api.tx.unique.destroyCollection(collectionId);
+ const events = await submitTransactionAsync(alicePrivateKey, tx);
+ const result = getDestroyResult(events);
+ expect(result).to.be.true;
+
+ // What to expect
+ expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;
+ });
+}
+
+export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.setCollectionLimits(collectionId, limits);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {
+ await usingApi(async(api) => {
+ const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+};
+
+export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.setCollectionLimits(collectionId, limits);
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const senderPrivateKey = privateKeyWrapper(sender);
+ const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);
+ const events = await submitTransactionAsync(senderPrivateKey, tx);
+ const result = getGenericResult(events);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
+
+ // What to expect
+ expect(result.success).to.be.true;
+ expect(collection.sponsorship.toJSON()).to.deep.equal({
+ unconfirmed: sponsor,
+ });
+ });
+}
+
+export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const alicePrivateKey = privateKeyWrapper(sender);
+ const tx = api.tx.unique.removeCollectionSponsor(collectionId);
+ const events = await submitTransactionAsync(alicePrivateKey, tx);
+ const result = getGenericResult(events);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
+
+ // What to expect
+ expect(result.success).to.be.true;
+ expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});
+ });
+}
+
+export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const alicePrivateKey = privateKeyWrapper(senderSeed);
+ const tx = api.tx.unique.removeCollectionSponsor(collectionId);
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
+ });
+}
+
+export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const alicePrivateKey = privateKeyWrapper(senderSeed);
+ const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
+ });
+}
+
+export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const sender = privateKeyWrapper(senderSeed);
+ await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);
+ });
+}
+
+export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const tx = api.tx.unique.confirmSponsorship(collectionId);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
+
+ // What to expect
+ expect(result.success).to.be.true;
+ expect(collection.sponsorship.toJSON()).to.be.deep.equal({
+ confirmed: sender.address,
+ });
+ });
+}
+
+
+export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async (api, privateKeyWrapper) => {
+
+ // Run the transaction
+ const sender = privateKeyWrapper(senderSeed);
+ const tx = api.tx.unique.confirmSponsorship(collectionId);
+ await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ });
+}
+
+export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {
+
+ await usingApi(async (api) => {
+
+ const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
+
+ await usingApi(async (api) => {
+
+ const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function getNextSponsored(
+ api: ApiPromise,
+ collectionId: number,
+ account: string | CrossAccountId,
+ tokenId: number,
+): Promise<number> {
+ return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));
+}
+
+export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {
+ let allowlisted = false;
+ await usingApi(async (api) => {
+ allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;
+ });
+ return allowlisted;
+}
+
+export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export interface CreateFungibleData {
+ readonly Value: bigint;
+}
+
+export interface CreateReFungibleData { }
+export interface CreateNftData { }
+
+export type CreateItemData = {
+ NFT: CreateNftData;
+} | {
+ Fungible: CreateFungibleData;
+} | {
+ ReFungible: CreateReFungibleData;
+};
+
+export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {
+ const tx = api.tx.unique.burnItem(collectionId, tokenId, value);
+ const events = await submitTransactionAsync(sender, tx);
+ return getGenericResult(events).success;
+}
+
+export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {
+ await usingApi(async (api) => {
+ const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);
+ // if burning token by admin - use adminButnItemExpectSuccess
+ expect(balanceBefore >= BigInt(value)).to.be.true;
+
+ expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;
+
+ const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);
+ expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);
+ });
+}
+
+export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.burnItem(collectionId, tokenId, value);
+
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);
+ const events = await submitTransactionAsync(sender, tx);
+ return getGenericResult(events).success;
+ });
+}
+
+export async function
+approve(
+ api: ApiPromise,
+ collectionId: number,
+ tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,
+) {
+ const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
+ const events = await submitTransactionAsync(owner, approveUniqueTx);
+ return getGenericResult(events).success;
+}
+
+export async function
+approveExpectSuccess(
+ collectionId: number,
+ tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const result = await approve(api, collectionId, tokenId, owner, approved, amount);
+ expect(result).to.be.true;
+
+ expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));
+ });
+}
+
+export async function adminApproveFromExpectSuccess(
+ collectionId: number,
+ tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
+ const events = await submitTransactionAsync(admin, approveUniqueTx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));
+ });
+}
+
+export async function
+transferFrom(
+ api: ApiPromise,
+ collectionId: number,
+ tokenId: number,
+ accountApproved: IKeyringPair,
+ accountFrom: IKeyringPair | CrossAccountId,
+ accountTo: IKeyringPair | CrossAccountId,
+ value: number | bigint,
+) {
+ const from = normalizeAccountId(accountFrom);
+ const to = normalizeAccountId(accountTo);
+ const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);
+ const events = await submitTransactionAsync(accountApproved, transferFromTx);
+ return getGenericResult(events).success;
+}
+
+export async function
+transferFromExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ accountApproved: IKeyringPair,
+ accountFrom: IKeyringPair | CrossAccountId,
+ accountTo: IKeyringPair | CrossAccountId,
+ value: number | bigint = 1,
+ type = 'NFT',
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const from = normalizeAccountId(accountFrom);
+ const to = normalizeAccountId(accountTo);
+ let balanceBefore = 0n;
+ if (type === 'Fungible' || type === 'ReFungible') {
+ balanceBefore = await getBalance(api, collectionId, to, tokenId);
+ }
+ expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;
+ if (type === 'NFT') {
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);
+ }
+ if (type === 'Fungible') {
+ const balanceAfter = await getBalance(api, collectionId, to, tokenId);
+ if (JSON.stringify(to) !== JSON.stringify(from)) {
+ expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));
+ } else {
+ expect(balanceAfter).to.be.equal(balanceBefore);
+ }
+ }
+ if (type === 'ReFungible') {
+ expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));
+ }
+ });
+}
+
+export async function
+transferFromExpectFail(
+ collectionId: number,
+ tokenId: number,
+ accountApproved: IKeyringPair,
+ accountFrom: IKeyringPair,
+ accountTo: IKeyringPair,
+ value: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);
+ const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;
+ const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+/* eslint no-async-promise-executor: "off" */
+export async function getBlockNumber(api: ApiPromise): Promise<number> {
+ return new Promise<number>(async (resolve) => {
+ const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {
+ unsubscribe();
+ resolve(head.number.toNumber());
+ });
+ });
+}
+
+export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {
+ await usingApi(async (api) => {
+ const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));
+ const events = await submitTransactionAsync(sender, changeAdminTx);
+ const result = getCreateCollectionResult(events);
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function adminApproveFromExpectFail(
+ collectionId: number,
+ tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
+ const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;
+ const result = getGenericResult(events);
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function
+getFreeBalance(account: IKeyringPair): Promise<bigint> {
+ let balance = 0n;
+ await usingApi(async (api) => {
+ balance = BigInt((await api.query.system.account(account.address)).data.free.toString());
+ });
+
+ return balance;
+}
+
+export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {
+ return usingApi(async api => {
+ // We are getting a *sibling* parachain sovereign account,
+ // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c
+ const siblingPrefix = '0x7369626c';
+
+ const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);
+ const suffix = '000000000000000000000000000000000000000000000000';
+
+ return siblingPrefix + encodedParaId + suffix;
+ });
+}
+
+export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {
+ const tx = api.tx.balances.transfer(target, amount);
+ const events = await submitTransactionAsync(source, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+}
+
+export async function
+scheduleExpectSuccess(
+ operationTx: any,
+ sender: IKeyringPair,
+ blockSchedule: number,
+ scheduledId: string,
+ period = 1,
+ repetitions = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const blockNumber: number | undefined = await getBlockNumber(api);
+ const expectedBlockNumber = blockNumber + blockSchedule;
+
+ expect(blockNumber).to.be.greaterThan(0);
+ const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
+ scheduledId,
+ expectedBlockNumber,
+ repetitions > 1 ? [period, repetitions] : null,
+ 0,
+ {Value: operationTx as any},
+ );
+
+ const events = await submitTransactionAsync(sender, scheduleTx);
+ expect(getGenericResult(events).success).to.be.true;
+ });
+}
+
+export async function
+scheduleExpectFailure(
+ operationTx: any,
+ sender: IKeyringPair,
+ blockSchedule: number,
+ scheduledId: string,
+ period = 1,
+ repetitions = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const blockNumber: number | undefined = await getBlockNumber(api);
+ const expectedBlockNumber = blockNumber + blockSchedule;
+
+ expect(blockNumber).to.be.greaterThan(0);
+ const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
+ scheduledId,
+ expectedBlockNumber,
+ repetitions <= 1 ? null : [period, repetitions],
+ 0,
+ {Value: operationTx as any},
+ );
+
+ //const events =
+ await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;
+ //expect(getGenericResult(events).success).to.be.false;
+ });
+}
+
+export async function
+scheduleTransferAndWaitExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ value: number | bigint = 1,
+ blockSchedule: number,
+ scheduledId: string,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);
+
+ const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+
+ // sleep for n + 1 blocks
+ await waitNewBlocks(blockSchedule + 1);
+
+ const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
+ expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
+ });
+}
+
+export async function
+scheduleTransferExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ value: number | bigint = 1,
+ blockSchedule: number,
+ scheduledId: string,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
+
+ await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
+ });
+}
+
+export async function
+scheduleTransferFundsPeriodicExpectSuccess(
+ amount: bigint,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ blockSchedule: number,
+ scheduledId: string,
+ period: number,
+ repetitions: number,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferTx = api.tx.balances.transfer(recipient.address, amount);
+
+ const balanceBefore = await getFreeBalance(recipient);
+
+ await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);
+
+ expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
+ });
+}
+
+export async function
+transfer(
+ api: ApiPromise,
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair | CrossAccountId,
+ value: number | bigint,
+) : Promise<boolean> {
+ const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
+ const events = await executeTransaction(api, sender, transferTx);
+ return getGenericResult(events).success;
+}
+
+export async function
+transferExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair | CrossAccountId,
+ value: number | bigint = 1,
+ type = 'NFT',
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const from = normalizeAccountId(sender);
+ const to = normalizeAccountId(recipient);
+
+ let balanceBefore = 0n;
+ if (type === 'Fungible' || type === 'ReFungible') {
+ balanceBefore = await getBalance(api, collectionId, to, tokenId);
+ }
+
+ const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
+ const events = await executeTransaction(api, sender, transferTx);
+ const result = getTransferResult(api, events);
+
+ expect(result.collectionId).to.be.equal(collectionId);
+ expect(result.itemId).to.be.equal(tokenId);
+ expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));
+ expect(result.recipient).to.be.deep.equal(to);
+ expect(result.value).to.be.equal(BigInt(value));
+
+ if (type === 'NFT') {
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);
+ }
+ if (type === 'Fungible' || type === 'ReFungible') {
+ const balanceAfter = await getBalance(api, collectionId, to, tokenId);
+ if (JSON.stringify(to) !== JSON.stringify(from)) {
+ expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));
+ } else {
+ expect(balanceAfter).to.be.equal(balanceBefore);
+ }
+ }
+ });
+}
+
+export async function
+transferExpectFailure(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair | CrossAccountId,
+ value: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
+ const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;
+ const result = getGenericResult(events);
+ // if (events && Array.isArray(events)) {
+ // const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ //}
+ });
+}
+
+export async function
+approveExpectFail(
+ collectionId: number,
+ tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);
+ const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;
+ const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function getBalance(
+ api: ApiPromise,
+ collectionId: number,
+ owner: string | CrossAccountId | IKeyringPair,
+ token: number,
+): Promise<bigint> {
+ return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();
+}
+export async function getTokenOwner(
+ api: ApiPromise,
+ collectionId: number,
+ token: number,
+): Promise<CrossAccountId> {
+ const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;
+ if (owner == null) throw new Error('owner == null');
+ return normalizeAccountId(owner);
+}
+export async function getTopmostTokenOwner(
+ api: ApiPromise,
+ collectionId: number,
+ token: number,
+): Promise<CrossAccountId> {
+ const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;
+ if (owner == null) throw new Error('owner == null');
+ return normalizeAccountId(owner);
+}
+export async function getTokenChildren(
+ api: ApiPromise,
+ collectionId: number,
+ tokenId: number,
+): Promise<UpDataStructsTokenChild[]> {
+ return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;
+}
+export async function isTokenExists(
+ api: ApiPromise,
+ collectionId: number,
+ token: number,
+): Promise<boolean> {
+ return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();
+}
+export async function getLastTokenId(
+ api: ApiPromise,
+ collectionId: number,
+): Promise<number> {
+ return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();
+}
+export async function getAdminList(
+ api: ApiPromise,
+ collectionId: number,
+): Promise<string[]> {
+ return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;
+}
+export async function getTokenProperties(
+ api: ApiPromise,
+ collectionId: number,
+ tokenId: number,
+ propertyKeys: string[],
+): Promise<UpDataStructsProperty[]> {
+ return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;
+}
+
+export async function createFungibleItemExpectSuccess(
+ sender: IKeyringPair,
+ collectionId: number,
+ data: CreateFungibleData,
+ owner: CrossAccountId | string = sender.address,
+) {
+ return await usingApi(async (api) => {
+ const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});
+
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getCreateItemResult(events);
+
+ expect(result.success).to.be.true;
+ return result.itemId;
+ });
+}
+
+export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {
+ await usingApi(async (api) => {
+ const to = normalizeAccountId(owner);
+ const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);
+
+ const events = await submitTransactionAsync(sender, tx);
+ expect(getGenericResult(events).success).to.be.true;
+ });
+}
+
+export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {
+ await usingApi(async (api) => {
+ const to = normalizeAccountId(owner);
+ const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);
+
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getCreateItemsResult(events);
+
+ for (const res of result) {
+ expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;
+ }
+ });
+}
+
+export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);
+
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getCreateItemsResult(events);
+
+ for (const res of result) {
+ expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;
+ }
+ });
+}
+
+export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {
+ let newItemId = 0;
+ await usingApi(async (api) => {
+ const to = normalizeAccountId(owner);
+ const itemCountBefore = await getLastTokenId(api, collectionId);
+ const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);
+
+ let tx;
+ if (createMode === 'Fungible') {
+ const createData = {fungible: {value: 10}};
+ tx = api.tx.unique.createItem(collectionId, to, createData as any);
+ } else if (createMode === 'ReFungible') {
+ const createData = {refungible: {pieces: 100}};
+ tx = api.tx.unique.createItem(collectionId, to, createData as any);
+ } else {
+ const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});
+ tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);
+ }
+
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getCreateItemResult(events);
+
+ const itemCountAfter = await getLastTokenId(api, collectionId);
+ const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);
+
+ if (createMode === 'NFT') {
+ expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;
+ }
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ if (createMode === 'Fungible') {
+ expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
+ } else {
+ expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
+ }
+ expect(collectionId).to.be.equal(result.collectionId);
+ expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());
+ expect(to).to.be.deep.equal(result.recipient);
+ newItemId = result.itemId;
+ });
+ return newItemId;
+}
+
+export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {
+ await usingApi(async (api) => {
+
+ let tx;
+ if (createMode === 'NFT') {
+ const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;
+ tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);
+ } else {
+ tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);
+ }
+
+
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;
+ const result = getCreateItemResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {
+ let newItemId = 0;
+ await usingApi(async (api) => {
+ const to = normalizeAccountId(owner);
+ const itemCountBefore = await getLastTokenId(api, collectionId);
+ const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);
+
+ let tx;
+ if (createMode === 'Fungible') {
+ const createData = {fungible: {value: 10}};
+ tx = api.tx.unique.createItem(collectionId, to, createData as any);
+ } else if (createMode === 'ReFungible') {
+ const createData = {refungible: {pieces: 100}};
+ tx = api.tx.unique.createItem(collectionId, to, createData as any);
+ } else {
+ const createData = {nft: {}};
+ tx = api.tx.unique.createItem(collectionId, to, createData as any);
+ }
+
+ const events = await executeTransaction(api, sender, tx);
+ const result = getCreateItemResult(events);
+
+ const itemCountAfter = await getLastTokenId(api, collectionId);
+ const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ if (createMode === 'Fungible') {
+ expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
+ } else {
+ expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
+ }
+ expect(collectionId).to.be.equal(result.collectionId);
+ expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());
+ expect(to).to.be.deep.equal(result.recipient);
+ newItemId = result.itemId;
+ });
+ return newItemId;
+}
+
+export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {
+ const createData = {refungible: {pieces: amount}};
+ const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);
+
+ const events = await submitTransactionAsync(sender, tx);
+ return getCreateItemResult(events);
+}
+
+export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {
+ await usingApi(async (api) => {
+ const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);
+
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getCreateItemResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function setPublicAccessModeExpectSuccess(
+ sender: IKeyringPair, collectionId: number,
+ accessMode: 'Normal' | 'AllowList',
+) {
+ await usingApi(async (api) => {
+
+ // Run the transaction
+ const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);
+ });
+}
+
+export async function setPublicAccessModeExpectFail(
+ sender: IKeyringPair, collectionId: number,
+ accessMode: 'Normal' | 'AllowList',
+) {
+ await usingApi(async (api) => {
+
+ // Run the transaction
+ const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
+ await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');
+}
+
+export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {
+ await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');
+}
+
+export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
+ await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');
+}
+
+export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {
+ await usingApi(async (api) => {
+
+ // Run the transaction
+ const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ // Get the collection
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
+
+ expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);
+ });
+}
+
+export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {
+ await setMintPermissionExpectSuccess(sender, collectionId, true);
+}
+
+export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
+ await usingApi(async (api) => {
+ // Run the transaction
+ const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {
+ await usingApi(async (api) => {
+ // Run the transaction
+ const tx = api.tx.unique.setChainLimits(limits);
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getCreateCollectionResult(events);
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {
+ return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();
+}
+
+export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {
+ await usingApi(async (api) => {
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;
+
+ // Run the transaction
+ const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
+ });
+}
+
+export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
+ await usingApi(async (api) => {
+
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
+
+ // Run the transaction
+ const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
+ });
+}
+
+export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
+ await usingApi(async (api) => {
+
+ // Run the transaction
+ const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
+ await usingApi(async (api) => {
+ // Run the transaction
+ const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
+ await usingApi(async (api) => {
+ // Run the transaction
+ const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(result.success).to.be.false;
+ });
+}
+
+export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)
+ : Promise<UpDataStructsRpcCollection | null> => {
+ return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);
+};
+
+export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {
+ // set global object - collectionsCount
+ return (await api.rpc.unique.collectionStats()).created.toNumber();
+};
+
+export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {
+ return (await api.rpc.unique.collectionById(collectionId)).unwrap();
+}
+
+export const describe_xcm = (
+ process.env.RUN_XCM_TESTS
+ ? describe
+ : describe.skip
+);
+
+export async function waitNewBlocks(blocksCount = 1): Promise<void> {
+ await usingApi(async (api) => {
+ const promise = new Promise<void>(async (resolve) => {
+ const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {
+ if (blocksCount > 0) {
+ blocksCount--;
+ } else {
+ unsubscribe();
+ resolve();
+ }
+ });
+ });
+ return promise;
+ });
+}
+
+export async function waitEvent(
+ api: ApiPromise,
+ maxBlocksToWait: number,
+ eventSection: string,
+ eventMethod: string,
+): Promise<EventRecord | null> {
+
+ const promise = new Promise<EventRecord | null>(async (resolve) => {
+ const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {
+ const blockNumber = header.number.toHuman();
+ const blockHash = header.hash;
+ const eventIdStr = `${eventSection}.${eventMethod}`;
+ const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;
+
+ console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);
+
+ const apiAt = await api.at(blockHash);
+ const eventRecords = await apiAt.query.system.events();
+
+ const neededEvent = eventRecords.find(r => {
+ return r.event.section == eventSection && r.event.method == eventMethod;
+ });
+
+ if (neededEvent) {
+ unsubscribe();
+ resolve(neededEvent);
+ } else if (maxBlocksToWait > 0) {
+ maxBlocksToWait--;
+ } else {
+ console.log(`Event \`${eventIdStr}\` is NOT found`);
+
+ unsubscribe();
+ resolve(null);
+ }
+ });
+ });
+ return promise;
+}
+
+export async function repartitionRFT(
+ api: ApiPromise,
+ collectionId: number,
+ sender: IKeyringPair,
+ tokenId: number,
+ amount: bigint,
+): Promise<boolean> {
+ const tx = api.tx.unique.repartition(collectionId, tokenId, amount);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ return result.success;
+}
+
+export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
+ let i: any = it;
+ if (opts.only) i = i.only;
+ else if (opts.skip) i = i.skip;
+ i(name, async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ await cb({api, privateKeyWrapper});
+ });
+ });
+}
+
+itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});
+itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});
+
+let accountSeed = 10000;
+export function generateKeyringPair(keyring: Keyring) {
+ const privateKey = `0xDEADBEEF${(Date.now() + (accountSeed++)).toString(16).padStart(64 - 8, '0')}`;
+ return keyring.addFromUri(privateKey);
+}
+
+export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {
+ const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
+ const subEvents = (await api.query.system.events.at(blockHash))
+ .filter(x => x.event.section === section)
+ .map((x) => x.toHuman());
+ const events = methods.map((m) => {
+ return {
+ event: {
+ method: m,
+ section,
+ },
+ };
+ });
+ if (!dryRun) {
+ expect(subEvents).to.be.like(events);
+ }
+ return subEvents;
+}
tests/src/deprecated-helpers/util.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/deprecated-helpers/util.ts
@@ -0,0 +1,46 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+export function strToUTF16(str: string): any {
+ const buf: number[] = [];
+ for (let i=0, strLen=str.length; i < strLen; i++) {
+ buf.push(str.charCodeAt(i));
+ }
+ return buf;
+}
+
+export function utf16ToStr(buf: number[]): string {
+ let str = '';
+ for (let i=0, strLen=buf.length; i < strLen; i++) {
+ if (buf[i] != 0) str += String.fromCharCode(buf[i]);
+ else break;
+ }
+ return str;
+}
+
+export function hexToStr(buf: string): string {
+ let str = '';
+ let hexStart = buf.indexOf('0x');
+ if (hexStart < 0) hexStart = 0;
+ else hexStart = 2;
+ for (let i=hexStart, strLen=buf.length; i < strLen; i+=2) {
+ const ch = buf[i] + buf[i+1];
+ const num = parseInt(ch, 16);
+ if (num != 0) str += String.fromCharCode(num);
+ else break;
+ }
+ return str;
+}
tests/src/enableContractSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/enableContractSponsoring.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {IKeyringPair} from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import usingApi from './substrate/substrate-api';
-import {deployFlipper, getFlipValue, toggleFlipValueExpectSuccess} from './util/contracthelpers';
-import {
- enableContractSponsoringExpectFailure,
- enableContractSponsoringExpectSuccess,
- findUnusedAddress,
- setContractSponsoringRateLimitExpectSuccess,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-// todo:playgrounds skipped ~ postponed
-describe.skip('Integration Test enableContractSponsoring', () => {
- it('ensure tx fee is paid from endowment', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const user = await findUnusedAddress(api, privateKeyWrapper);
-
- const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
- await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
- await setContractSponsoringRateLimitExpectSuccess(deployer, flipper.address, 1);
- await toggleFlipValueExpectSuccess(user, flipper);
-
- expect(await getFlipValue(flipper, deployer)).to.be.false;
- });
- });
-
- it('ensure it can be enabled twice', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
-
- await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
- await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
- });
- });
-
- it('ensure it can be disabled twice', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
-
- await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
- await enableContractSponsoringExpectSuccess(deployer, flipper.address, false);
- await enableContractSponsoringExpectSuccess(deployer, flipper.address, false);
- });
- });
-
- it('ensure it can be re-enabled', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
-
- await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
- await enableContractSponsoringExpectSuccess(deployer, flipper.address, false);
- await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
- });
- });
-
-});
-
-describe.skip('Negative Integration Test enableContractSponsoring', () => {
- let alice: IKeyringPair;
-
- before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- });
- });
-
- it('fails when called for non-contract address', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const user = await findUnusedAddress(api, privateKeyWrapper);
-
- await enableContractSponsoringExpectFailure(alice, user.address, true);
- });
- });
-
- it('fails when called by non-owning user', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [flipper] = await deployFlipper(api, privateKeyWrapper);
-
- await enableContractSponsoringExpectFailure(alice, flipper.address, true);
- });
- });
-});
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -14,16 +14,12 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {
- ethBalanceViaSub,
- GAS_ARGS,
- recordEthFee,
-} from './util/helpers';
import {Contract} from 'web3-eth-contract';
import {IKeyringPair} from '@polkadot/types/types';
import {EthUniqueHelper, itEth, usingEthPlaygrounds, expect} from './util/playgrounds';
+
describe('Contract calls', () => {
let donor: IKeyringPair;
@@ -37,15 +33,15 @@
const deployer = await helper.eth.createAccountWithBalance(donor);
const flipper = await helper.eth.deployFlipper(deployer);
- const cost = await recordEthFee(helper.api!, deployer, () => flipper.methods.flip().send({from: deployer}));
+ const cost = await helper.eth.calculateFee({Ethereum: deployer}, () => flipper.methods.flip().send({from: deployer}));
expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal()))).to.be.true;
});
itEth('Balance transfer fee is less than 0.2 UNQ', async ({helper}) => {
const userA = await helper.eth.createAccountWithBalance(donor);
const userB = helper.eth.createAccount();
- const cost = await recordEthFee(helper.api!, userA, () => helper.web3!.eth.sendTransaction({from: userA, to: userB, value: '1000000', ...GAS_ARGS}));
- const balanceB = await ethBalanceViaSub(helper.api!, userB);
+ const cost = await helper.eth.calculateFee({Ethereum: userA}, () => helper.getWeb3().eth.sendTransaction({from: userA, to: userB, value: '1000000', gas: helper.eth.DEFAULT_GAS}));
+ const balanceB = await helper.balance.getEthereum(userB);
expect(cost - balanceB < BigInt(0.2 * Number(helper.balance.getOneTokenNominal()))).to.be.true;
});
@@ -60,7 +56,7 @@
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'nft', caller);
- const cost = await recordEthFee(helper.api!, caller, () => contract.methods.transfer(receiver, tokenId).send(caller));
+ const cost = await helper.eth.calculateFee({Ethereum: caller}, () => contract.methods.transfer(receiver, tokenId).send(caller));
const fee = Number(cost) / Number(helper.balance.getOneTokenNominal());
const expectedFee = 0.15;
tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -1,33 +1,45 @@
-import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess, UNIQUE} from '../util/helpers';
-import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub} from './util/helpers';
-import nonFungibleAbi from './nonFungibleAbi.json';
-import {expect} from 'chai';
-import {evmToAddress} from '@polkadot/util-crypto';
+import {IKeyringPair} from '@polkadot/types/types';
+import {usingPlaygrounds} from './../util/playgrounds/index';
+import {itEth, expect} from '../eth/util/playgrounds';
describe('evm collection sponsoring', () => {
- itWeb3('sponsors mint transactions', async ({web3, privateKeyWrapper}) => {
- const alice = privateKeyWrapper('//Alice');
+ let donor: IKeyringPair;
+ let alice: IKeyringPair;
+ let nominal: bigint;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ donor = privateKey('//Alice');
+ nominal = helper.balance.getOneTokenNominal();
+ });
+ });
+
+ beforeEach(async () => {
+ await usingPlaygrounds(async (helper) => {
+ [alice] = await helper.arrange.createAccounts([1000n], donor);
+ });
+ });
- const collection = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collection, alice.address);
- await confirmSponsorshipExpectSuccess(collection);
+ itEth('sponsors mint transactions', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'spnr', permissions: {mintMode: true}});
+ await collection.setSponsor(alice, alice.address);
+ await collection.confirmSponsorship(alice);
- const minter = createEthAccount(web3);
- expect(await web3.eth.getBalance(minter)).to.equal('0');
+ const minter = helper.eth.createAccount();
+ expect(await helper.balance.getEthereum(minter)).to.equal(0n);
- const address = collectionIdToAddress(collection);
- const contract = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collection), {from: minter, ...GAS_ARGS});
+ const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', minter);
- await enablePublicMintingExpectSuccess(alice, collection);
- await addToAllowListExpectSuccess(alice, collection, {Ethereum: minter});
+ await collection.addToAllowList(alice, {Ethereum: minter});
const nextTokenId = await contract.methods.nextTokenId().call();
expect(nextTokenId).to.equal('1');
const result = await contract.methods.mint(minter, nextTokenId).send();
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
- address,
+ address: collectionAddress,
event: 'Transfer',
args: {
from: '0x0000000000000000000000000000000000000000',
@@ -59,13 +71,14 @@
// expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);
// });
- itWeb3('Remove sponsor', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const collectionHelpers = evmCollectionHelpers(web3, owner);
- let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * UNIQUE)});
- const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ itEth('Remove sponsor', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
+
+ let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
+ const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
result = await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
@@ -80,30 +93,31 @@
expect(sponsorTuple.field_0).to.be.eq('0x0000000000000000000000000000000000000000');
});
- itWeb3('Sponsoring collection from evm address via access list', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const collectionHelpers = evmCollectionHelpers(web3, owner);
- let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * UNIQUE)});
- const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ itEth('Sponsoring collection from evm address via access list', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
+
+ let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
+ const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
+ const collection = helper.nft.getCollectionObject(collectionId);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
+
result = await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
- let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
- const ss58Format = (api.registry.getChainProperties())!.toJSON().ss58Format;
- expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;
- expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor, Number(ss58Format)));
+ let collectionData = (await collection.getData())!;
+ expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
- collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
- expect(collectionSub.sponsorship.isConfirmed).to.be.true;
- expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor, Number(ss58Format)));
+ collectionData = (await collection.getData())!;
+ expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
- const user = createEthAccount(web3);
+ const user = helper.eth.createAccount();
const nextTokenId = await collectionEvm.methods.nextTokenId().call();
expect(nextTokenId).to.be.equal('1');
- const oldPermissions = (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
+ const oldPermissions = (await collection.getData())!.raw.permissions; // (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
expect(oldPermissions.mintMode).to.be.false;
expect(oldPermissions.access).to.be.equal('Normal');
@@ -111,12 +125,12 @@
await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});
await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
- const newPermissions = (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
+ const newPermissions = (await collection.getData())!.raw.permissions; // (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
expect(newPermissions.mintMode).to.be.true;
expect(newPermissions.access).to.be.equal('AllowList');
- const ownerBalanceBefore = await ethBalanceViaSub(api, owner);
- const sponsorBalanceBefore = await ethBalanceViaSub(api, sponsor);
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
{
const nextTokenId = await collectionEvm.methods.nextTokenId().call();
@@ -126,7 +140,7 @@
nextTokenId,
'Test URI',
).send({from: user});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -140,8 +154,8 @@
},
]);
- const ownerBalanceAfter = await ethBalanceViaSub(api, owner);
- const sponsorBalanceAfter = await ethBalanceViaSub(api, sponsor);
+ const ownerBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(owner));
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));
expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
@@ -205,33 +219,34 @@
// }
// });
- itWeb3('Check that transaction via EVM spend money from sponsor address', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const collectionHelpers = evmCollectionHelpers(web3, owner);
- let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * UNIQUE)});
- const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ itEth('Check that transaction via EVM spend money from sponsor address', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
+
+ let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
+ const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
+ const collection = helper.nft.getCollectionObject(collectionId);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
+
result = await collectionEvm.methods.setCollectionSponsor(sponsor).send();
- let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
- const ss58Format = (api.registry.getChainProperties())!.toJSON().ss58Format;
- expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;
- expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor, Number(ss58Format)));
+ let collectionData = (await collection.getData())!;
+ expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
- const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+
+ const sponsorCollection = helper.ethNativeContract.collection(collectionIdAddress, 'nft', sponsor);
await sponsorCollection.methods.confirmCollectionSponsorship().send();
- collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
- expect(collectionSub.sponsorship.isConfirmed).to.be.true;
- expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor, Number(ss58Format)));
+ collectionData = (await collection.getData())!;
+ expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
- const user = createEthAccount(web3);
+ const user = helper.eth.createAccount();
await collectionEvm.methods.addCollectionAdmin(user).send();
- const ownerBalanceBefore = await ethBalanceViaSub(api, owner);
- const sponsorBalanceBefore = await ethBalanceViaSub(api, sponsor);
-
-
- const userCollectionEvm = evmCollection(web3, user, collectionIdAddress);
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+
+ const userCollectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', user);
const nextTokenId = await userCollectionEvm.methods.nextTokenId().call();
expect(nextTokenId).to.be.equal('1');
result = await userCollectionEvm.methods.mintWithTokenURI(
@@ -240,8 +255,8 @@
'Test URI',
).send();
- const events = normalizeEvents(result.events);
- const address = collectionIdToAddress(collectionId);
+ const events = helper.eth.normalizeEvents(result.events);
+ const address = helper.ethAddress.fromCollectionId(collectionId);
expect(events).to.be.deep.equal([
{
@@ -256,9 +271,9 @@
]);
expect(await userCollectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
- const ownerBalanceAfter = await ethBalanceViaSub(api, owner);
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
- const sponsorBalanceAfter = await ethBalanceViaSub(api, sponsor);
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
});
});
tests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -14,45 +14,39 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+import {IKeyringPair} from '@polkadot/types/types';
import * as solc from 'solc';
-import {expect} from 'chai';
-import {expectSubstrateEventsAtBlock} from '../util/helpers';
-import Web3 from 'web3';
+import {EthUniqueHelper} from './util/playgrounds/unique.dev';
+import {itEth, expect, SponsoringMode, usingEthPlaygrounds} from '../eth/util/playgrounds';
+import {usingPlaygrounds} from '../util/playgrounds';
+import {CompiledContract} from './util/playgrounds/types';
-import {
- contractHelpers,
- createEthAccountWithBalance,
- transferBalanceToEth,
- deployFlipper,
- itWeb3,
- SponsoringMode,
- createEthAccount,
- ethBalanceViaSub,
- normalizeEvents,
- CompiledContract,
- GAS_ARGS,
- subToEth,
-} from './util/helpers';
-import {submitTransactionAsync} from '../substrate/substrate-api';
+describe('Sponsoring EVM contracts', () => {
+ let donor: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (_helper, privateKey) => {
+ donor = privateKey('//Alice');
+ });
+ });
+
+ itEth('Self sponsored can be set by the address that deployed the contract', async ({helper, privateKey}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const flipper = await helper.eth.deployFlipper(owner);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
-describe('Sponsoring EVM contracts', () => {
- itWeb3('Self sponsored can be set by the address that deployed the contract', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
await expect(helpers.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;
});
- itWeb3('Set self sponsored events', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Set self sponsored events', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const flipper = await helper.eth.deployFlipper(owner);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
const result = await helpers.methods.selfSponsoredEnable(flipper.options.address).send();
- // console.log(result);
- const ethEvents = normalizeEvents(result.events);
+ const ethEvents = helper.eth.helper.eth.normalizeEvents(result.events);
expect(ethEvents).to.be.deep.equal([
{
address: flipper.options.address,
@@ -71,62 +65,59 @@
},
},
]);
-
- await expectSubstrateEventsAtBlock(
- api,
- result.blockNumber,
- 'evmContractHelpers',
- ['ContractSponsorSet','ContractSponsorshipConfirmed'],
- );
});
- itWeb3('Self sponsored can not be set by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const notOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Self sponsored can not be set by the address that did not deployed the contract', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const notOwner = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
await expect(helpers.methods.selfSponsoredEnable(flipper.options.address).call({from: notOwner})).to.be.rejectedWith('NoPermission');
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
});
- itWeb3('Sponsoring can be set by the address that has deployed the contract', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Sponsoring can be set by the address that has deployed the contract', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
await expect(helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner})).to.be.not.rejected;
expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
});
- itWeb3('Sponsoring cannot be set by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const notOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Sponsoring cannot be set by the address that did not deployed the contract', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const notOwner = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
await expect(helpers.methods.setSponsoringMode(notOwner, SponsoringMode.Allowlisted).call({from: notOwner})).to.be.rejectedWith('NoPermission');
expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
});
- itWeb3('Sponsor can be set by the address that deployed the contract', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Sponsor can be set by the address that deployed the contract', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.false;
await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;
expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.true;
});
- itWeb3('Set sponsor event', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Set sponsor event', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
const result = await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
address: flipper.options.address,
@@ -137,45 +128,41 @@
},
},
]);
-
- await expectSubstrateEventsAtBlock(
- api,
- result.blockNumber,
- 'evmContractHelpers',
- ['ContractSponsorSet'],
- );
});
- itWeb3('Sponsor can not be set by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const notOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Sponsor can not be set by the address that did not deployed the contract', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const notOwner = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.false;
await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).call({from: notOwner})).to.be.rejectedWith('NoPermission');
expect(await helpers.methods.hasPendingSponsor(flipper.options.address).call()).to.be.false;
});
- itWeb3('Sponsorship can be confirmed by the address that pending as sponsor', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Sponsorship can be confirmed by the address that pending as sponsor', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;
await expect(helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor})).to.be.not.rejected;
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;
});
- itWeb3('Confirm sponsorship event', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Confirm sponsorship event', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;
const result = await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
address: flipper.options.address,
@@ -186,41 +173,37 @@
},
},
]);
+ });
- await expectSubstrateEventsAtBlock(
- api,
- result.blockNumber,
- 'evmContractHelpers',
- ['ContractSponsorshipConfirmed'],
- );
- });
+ itEth('Sponsorship can not be confirmed by the address that not pending as sponsor', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const notSponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
- itWeb3('Sponsorship can not be confirmed by the address that not pending as sponsor', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const notSponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
await expect(helpers.methods.setSponsor(flipper.options.address, sponsor).send()).to.be.not.rejected;
await expect(helpers.methods.confirmSponsorship(flipper.options.address).call({from: notSponsor})).to.be.rejectedWith('NoPermission');
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
});
- itWeb3('Sponsorship can not be confirmed by the address that not set as sponsor', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const notSponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Sponsorship can not be confirmed by the address that not set as sponsor', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const notSponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
await expect(helpers.methods.confirmSponsorship(flipper.options.address).call({from: notSponsor})).to.be.rejectedWith('NoPendingSponsor');
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
});
- itWeb3('Get self sponsored sponsor', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Get self sponsored sponsor', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
await helpers.methods.selfSponsoredEnable(flipper.options.address).send();
const result = await helpers.methods.sponsor(flipper.options.address).call();
@@ -229,11 +212,12 @@
expect(result[1]).to.be.eq('0');
});
- itWeb3('Get confirmed sponsor', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Get confirmed sponsor', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});
@@ -243,11 +227,11 @@
expect(result[1]).to.be.eq('0');
});
- itWeb3('Sponsor can be removed by the address that deployed the contract', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Sponsor can be removed by the address that deployed the contract', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
@@ -258,17 +242,17 @@
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
});
- itWeb3('Remove sponsor event', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Remove sponsor event', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});
const result = await helpers.methods.removeSponsor(flipper.options.address).send();
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
address: flipper.options.address,
@@ -278,21 +262,14 @@
},
},
]);
-
- await expectSubstrateEventsAtBlock(
- api,
- result.blockNumber,
- 'evmContractHelpers',
- ['ContractSponsorRemoved'],
- );
});
- itWeb3('Sponsor can not be removed by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const notOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Sponsor can not be removed by the address that did not deployed the contract', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const notOwner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.false;
await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
@@ -303,14 +280,12 @@
expect(await helpers.methods.hasSponsor(flipper.options.address).call()).to.be.true;
});
- itWeb3('In generous mode, non-allowlisted user transaction will be sponsored', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
- const flipper = await deployFlipper(web3, owner);
-
- const helpers = contractHelpers(web3, owner);
+ itEth('In generous mode, non-allowlisted user transaction will be sponsored', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});
@@ -318,57 +293,52 @@
await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: owner});
await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
- const sponsorBalanceBefore = await ethBalanceViaSub(api, sponsor);
- const callerBalanceBefore = await ethBalanceViaSub(api, caller);
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));
+ const callerBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));
await flipper.methods.flip().send({from: caller});
expect(await flipper.methods.getValue().call()).to.be.true;
// Balance should be taken from sponsor instead of caller
- const sponsorBalanceAfter = await ethBalanceViaSub(api, sponsor);
- const callerBalanceAfter = await ethBalanceViaSub(api, caller);
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));
+ const callerBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));
expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
expect(callerBalanceAfter).to.be.eq(callerBalanceBefore);
});
-
- itWeb3('In generous mode, non-allowlisted user transaction will be self sponsored', async ({api, web3, privateKeyWrapper}) => {
- const alice = privateKeyWrapper('//Alice');
-
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('In generous mode, non-allowlisted user transaction will be self sponsored', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
await helpers.methods.selfSponsoredEnable(flipper.options.address).send();
await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: owner});
await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
- await transferBalanceToEth(api, alice, flipper.options.address);
+ await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);
- const contractBalanceBefore = await ethBalanceViaSub(api, flipper.options.address);
- const callerBalanceBefore = await ethBalanceViaSub(api, caller);
+ const contractBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(flipper.options.address));
+ const callerBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));
await flipper.methods.flip().send({from: caller});
expect(await flipper.methods.getValue().call()).to.be.true;
// Balance should be taken from sponsor instead of caller
- const contractBalanceAfter = await ethBalanceViaSub(api, flipper.options.address);
- const callerBalanceAfter = await ethBalanceViaSub(api, caller);
+ const contractBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(flipper.options.address));
+ const callerBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));
expect(contractBalanceAfter < contractBalanceBefore).to.be.true;
expect(callerBalanceAfter).to.be.eq(callerBalanceBefore);
});
- itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should decrease (allowlisted)', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const caller = createEthAccount(web3);
-
- const flipper = await deployFlipper(web3, owner);
+ itEth('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should decrease (allowlisted)', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const caller = helper.eth.createAccount();
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
- const helpers = contractHelpers(web3, owner);
await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});
await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});
@@ -378,51 +348,47 @@
await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});
- const sponsorBalanceBefore = await ethBalanceViaSub(api, sponsor);
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));
expect(sponsorBalanceBefore).to.be.not.equal('0');
await flipper.methods.flip().send({from: caller});
expect(await flipper.methods.getValue().call()).to.be.true;
// Balance should be taken from flipper instead of caller
- const sponsorBalanceAfter = await ethBalanceViaSub(api, sponsor);
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));
expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
});
- itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should not decrease (non-allowlisted)', async ({api, web3, privateKeyWrapper}) => {
- const alice = privateKeyWrapper('//Alice');
-
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const caller = createEthAccount(web3);
-
- const flipper = await deployFlipper(web3, owner);
+ itEth('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should not decrease (non-allowlisted)', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccount();
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
- const helpers = contractHelpers(web3, owner);
-
await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});
await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
- await transferBalanceToEth(api, alice, flipper.options.address);
+ await helper.eth.transferBalanceFromSubstrate(donor, flipper.options.address);
- const originalFlipperBalance = await web3.eth.getBalance(flipper.options.address);
+ const originalFlipperBalance = await helper.balance.getEthereum(flipper.options.address);
expect(originalFlipperBalance).to.be.not.equal('0');
await expect(flipper.methods.flip().send({from: caller})).to.be.rejectedWith(/InvalidTransaction::Payment/);
expect(await flipper.methods.getValue().call()).to.be.false;
// Balance should be taken from flipper instead of caller
- const balanceAfter = await web3.eth.getBalance(flipper.options.address);
- expect(+balanceAfter).to.be.equals(+originalFlipperBalance);
+ // FIXME the comment is wrong! What check should be here?
+ const balanceAfter = await helper.balance.getEthereum(flipper.options.address);
+ expect(balanceAfter).to.be.equals(originalFlipperBalance);
});
- itWeb3('Sponsoring is set, an address that has UNQ can send a transaction and it works. User balance should not change', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
- const flipper = await deployFlipper(web3, owner);
+ itEth('Sponsoring is set, an address that has UNQ can send a transaction and it works. User balance should not change', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
- const helpers = contractHelpers(web3, owner);
await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});
await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});
@@ -432,27 +398,26 @@
await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});
- const sponsorBalanceBefore = await ethBalanceViaSub(api, sponsor);
- const callerBalanceBefore = await ethBalanceViaSub(api, caller);
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));
+ const callerBalanceBefore = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));
await flipper.methods.flip().send({from: caller});
expect(await flipper.methods.getValue().call()).to.be.true;
- const sponsorBalanceAfter = await ethBalanceViaSub(api, sponsor);
- const callerBalanceAfter = await ethBalanceViaSub(api, caller);
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(sponsor));
+ const callerBalanceAfter = await helper.balance.getSubstrate(await helper.address.ethToSubstrate(caller));
expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
expect(callerBalanceAfter).to.be.equals(callerBalanceBefore);
});
- itWeb3('Sponsoring is limited, with setContractRateLimit. The limitation is working if transactions are sent more often, the sender pays the commission.', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const originalCallerBalance = await web3.eth.getBalance(caller);
-
- const flipper = await deployFlipper(web3, owner);
-
- const helpers = contractHelpers(web3, owner);
+ itEth('Sponsoring is limited, with setContractRateLimit. The limitation is working if transactions are sent more often, the sender pays the commission.', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
+ const originalCallerBalance = await helper.balance.getEthereum(caller);
await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});
await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});
@@ -462,34 +427,36 @@
await helpers.methods.setSponsor(flipper.options.address, sponsor).send();
await helpers.methods.confirmSponsorship(flipper.options.address).send({from: sponsor});
- const originalFlipperBalance = await web3.eth.getBalance(sponsor);
+ const originalFlipperBalance = await helper.balance.getEthereum(sponsor);
expect(originalFlipperBalance).to.be.not.equal('0');
await flipper.methods.flip().send({from: caller});
expect(await flipper.methods.getValue().call()).to.be.true;
- expect(await web3.eth.getBalance(caller)).to.be.equals(originalCallerBalance);
+ expect(await helper.balance.getEthereum(caller)).to.be.equals(originalCallerBalance);
- const newFlipperBalance = await web3.eth.getBalance(sponsor);
+ const newFlipperBalance = await helper.balance.getEthereum(sponsor);
expect(newFlipperBalance).to.be.not.equals(originalFlipperBalance);
await flipper.methods.flip().send({from: caller});
- expect(await web3.eth.getBalance(sponsor)).to.be.equal(newFlipperBalance);
- expect(await web3.eth.getBalance(caller)).to.be.not.equals(originalCallerBalance);
+ expect(await helper.balance.getEthereum(sponsor)).to.be.equal(newFlipperBalance);
+ expect(await helper.balance.getEthereum(caller)).to.be.not.equals(originalCallerBalance);
});
// TODO: Find a way to calculate default rate limit
- itWeb3('Default rate limit equals 7200', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Default rate limit equals 7200', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
expect(await helpers.methods.sponsoringRateLimit(flipper.options.address).call()).to.be.equals('7200');
});
});
describe('Sponsoring Fee Limit', () => {
+ let donor: IKeyringPair;
+ let alice: IKeyringPair;
+ let DEFAULT_GAS: number;
- let testContract: CompiledContract;
-
function compileTestContract() {
if (!testContract) {
const input = {
@@ -537,46 +504,67 @@
return testContract;
}
- async function deployTestContract(web3: Web3, owner: string) {
+ async function deployTestContract(helper: EthUniqueHelper, owner: string) {
+ const web3 = helper.getWeb3();
const compiled = compileTestContract();
const testContract = new web3.eth.Contract(compiled.abi, undefined, {
data: compiled.object,
from: owner,
- ...GAS_ARGS,
+ gas: DEFAULT_GAS,
});
return await testContract.deploy({data: compiled.object}).send({from: owner});
}
- itWeb3('Default fee limit', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ before(async () => {
+ await usingEthPlaygrounds(async (helper, privateKey) => {
+ donor = privateKey('//Alice');
+ DEFAULT_GAS = helper.eth.DEFAULT_GAS;
+ });
+ });
+
+ beforeEach(async () => {
+ await usingPlaygrounds(async (helper) => {
+ [alice] = await helper.arrange.createAccounts([1000n], donor);
+ });
+ });
+
+ let testContract: CompiledContract;
+
+
+
+ itEth('Default fee limit', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equals('115792089237316195423570985008687907853269984665640564039457584007913129639935');
});
- itWeb3('Set fee limit', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Set fee limit', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
await helpers.methods.setSponsoringFeeLimit(flipper.options.address, 100).send();
expect(await helpers.methods.sponsoringFeeLimit(flipper.options.address).call()).to.be.equals('100');
});
- itWeb3('Negative test - set fee limit by non-owner', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const stranger = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ itEth('Negative test - set fee limit by non-owner', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const stranger = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
+ const flipper = await helper.eth.deployFlipper(owner);
+
await expect(helpers.methods.setSponsoringFeeLimit(flipper.options.address, 100).send({from: stranger})).to.be.rejected;
});
- itWeb3('Negative test - check that eth transactions exceeding fee limit are not executed', async ({api, web3, privateKeyWrapper}) => {
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const user = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ itEth('Negative test - check that eth transactions exceeding fee limit are not executed', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const user = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
- const testContract = await deployTestContract(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ const testContract = await deployTestContract(helper, owner);
await helpers.methods.setSponsoringMode(testContract.options.address, SponsoringMode.Generous).send({from: owner});
await helpers.methods.setSponsoringRateLimit(testContract.options.address, 0).send({from: owner});
@@ -584,24 +572,24 @@
await helpers.methods.setSponsor(testContract.options.address, sponsor).send();
await helpers.methods.confirmSponsorship(testContract.options.address).send({from: sponsor});
- const gasPrice = BigInt(await web3.eth.getGasPrice());
+ const gasPrice = BigInt(await helper.getWeb3().eth.getGasPrice());
await helpers.methods.setSponsoringFeeLimit(testContract.options.address, 2_000_000n * gasPrice).send();
- const originalUserBalance = await web3.eth.getBalance(user);
+ const originalUserBalance = await helper.balance.getEthereum(user);
await testContract.methods.test(100).send({from: user, gas: 2_000_000});
- expect(await web3.eth.getBalance(user)).to.be.equal(originalUserBalance);
+ expect(await helper.balance.getEthereum(user)).to.be.equal(originalUserBalance);
await testContract.methods.test(100).send({from: user, gas: 2_100_000});
- expect(await web3.eth.getBalance(user)).to.not.be.equal(originalUserBalance);
+ expect(await helper.balance.getEthereum(user)).to.not.be.equal(originalUserBalance);
});
- itWeb3('Negative test - check that evm.call transactions exceeding fee limit are not executed', async ({api, web3, privateKeyWrapper}) => {
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ itEth('Negative test - check that evm.call transactions exceeding fee limit are not executed', async ({helper, privateKey}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
- const testContract = await deployTestContract(web3, owner);
- const helpers = contractHelpers(web3, owner);
+ const testContract = await deployTestContract(helper, owner);
await helpers.methods.setSponsoringMode(testContract.options.address, SponsoringMode.Generous).send({from: owner});
await helpers.methods.setSponsoringRateLimit(testContract.options.address, 0).send({from: owner});
@@ -609,43 +597,29 @@
await helpers.methods.setSponsor(testContract.options.address, sponsor).send();
await helpers.methods.confirmSponsorship(testContract.options.address).send({from: sponsor});
- const gasPrice = BigInt(await web3.eth.getGasPrice());
+ const gasPrice = BigInt(await helper.getWeb3().eth.getGasPrice());
await helpers.methods.setSponsoringFeeLimit(testContract.options.address, 2_000_000n * gasPrice).send();
- const alice = privateKeyWrapper('//Alice');
- const originalAliceBalance = (await api.query.system.account(alice.address)).data.free.toBigInt();
-
- await submitTransactionAsync(
+ const originalAliceBalance = await helper.balance.getSubstrate(alice.address);
+
+ await helper.eth.sendEVM(
alice,
- api.tx.evm.call(
- subToEth(alice.address),
- testContract.options.address,
- testContract.methods.test(100).encodeABI(),
- Uint8Array.from([]),
- 2_000_000n,
- gasPrice,
- null,
- null,
- [],
- ),
+ testContract.options.address,
+ testContract.methods.test(100).encodeABI(),
+ '0',
+ 2_000_000,
);
- expect((await api.query.system.account(alice.address)).data.free.toBigInt()).to.be.equal(originalAliceBalance);
+ // expect((await api.query.system.account(alice.address)).data.free.toBigInt()).to.be.equal(originalAliceBalance);
+ expect(await helper.balance.getSubstrate(alice.address)).to.be.equal(originalAliceBalance);
- await submitTransactionAsync(
+ await helper.eth.sendEVM(
alice,
- api.tx.evm.call(
- subToEth(alice.address),
- testContract.options.address,
- testContract.methods.test(100).encodeABI(),
- Uint8Array.from([]),
- 2_100_000n,
- gasPrice,
- null,
- null,
- [],
- ),
+ testContract.options.address,
+ testContract.methods.test(100).encodeABI(),
+ '0',
+ 2_100_000,
);
- expect((await api.query.system.account(alice.address)).data.free.toBigInt()).to.not.be.equal(originalAliceBalance);
+ expect(await helper.balance.getSubstrate(alice.address)).to.not.be.equal(originalAliceBalance);
});
});
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -17,8 +17,8 @@
import {evmToAddress} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
import {expect, itEth, usingEthPlaygrounds} from './util/playgrounds';
-import {UNIQUE} from '../util/helpers';
+
describe('Create NFT collection from EVM', () => {
let donor: IKeyringPair;
@@ -65,7 +65,7 @@
await collectionHelpers.methods
.createNonfungibleCollection('A', 'A', 'A')
- .send({value: Number(2n * UNIQUE)});
+ .send({value: Number(2n * helper.balance.getOneTokenNominal())});
expect(await collectionHelpers.methods
.isCollectionExist(expectedCollectionAddress)
@@ -147,10 +147,12 @@
describe('(!negative tests!) Create NFT collection from EVM', () => {
let donor: IKeyringPair;
+ let nominal: bigint;
before(async function() {
- await usingEthPlaygrounds(async (_helper, privateKey) => {
+ await usingEthPlaygrounds(async (helper, privateKey) => {
donor = await privateKey({filename: __filename});
+ nominal = helper.balance.getOneTokenNominal();
});
});
@@ -165,7 +167,7 @@
await expect(collectionHelper.methods
.createNonfungibleCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
}
{
@@ -175,7 +177,7 @@
const tokenPrefix = 'A';
await expect(collectionHelper.methods
.createNonfungibleCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
}
{
const MAX_TOKEN_PREFIX_LENGTH = 16;
@@ -184,7 +186,7 @@
const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
await expect(collectionHelper.methods
.createNonfungibleCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
}
});
@@ -193,7 +195,7 @@
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
await expect(collectionHelper.methods
.createNonfungibleCollection('Peasantry', 'absolutely anything', 'CVE')
- .call({value: Number(1n * UNIQUE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+ .call({value: Number(1n * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
});
itEth('(!negative test!) Check owner', async ({helper}) => {
tests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -18,8 +18,8 @@
import {IKeyringPair} from '@polkadot/types/types';
import {Pallets, requirePalletsOrSkip} from '../util/playgrounds';
import {expect, itEth, usingEthPlaygrounds} from './util/playgrounds';
-import {UNIQUE} from '../util/helpers';
+
describe('Create RFT collection from EVM', () => {
let donor: IKeyringPair;
@@ -66,7 +66,7 @@
await collectionHelpers.methods
.createRFTCollection('A', 'A', 'A')
- .send({value: Number(2n * UNIQUE)});
+ .send({value: Number(2n * helper.balance.getOneTokenNominal())});
expect(await collectionHelpers.methods
.isCollectionExist(expectedCollectionAddress)
@@ -148,11 +148,13 @@
describe('(!negative tests!) Create RFT collection from EVM', () => {
let donor: IKeyringPair;
+ let nominal: bigint;
before(async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
donor = await privateKey({filename: __filename});
+ nominal = helper.balance.getOneTokenNominal();
});
});
@@ -167,7 +169,7 @@
await expect(collectionHelper.methods
.createRFTCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
}
{
const MAX_DESCRIPTION_LENGTH = 256;
@@ -176,7 +178,7 @@
const tokenPrefix = 'A';
await expect(collectionHelper.methods
.createRFTCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
}
{
const MAX_TOKEN_PREFIX_LENGTH = 16;
@@ -185,7 +187,7 @@
const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
await expect(collectionHelper.methods
.createRFTCollection(collectionName, description, tokenPrefix)
- .call({value: Number(2n * UNIQUE)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
}
});
@@ -194,7 +196,7 @@
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
await expect(collectionHelper.methods
.createRFTCollection('Peasantry', 'absolutely anything', 'TWIW')
- .call({value: Number(1n * UNIQUE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+ .call({value: Number(1n * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
});
itEth('(!negative test!) Check owner', async ({helper}) => {
tests/src/eth/marketplace/marketplace.test.tsdiffbeforeafterboth--- a/tests/src/eth/marketplace/marketplace.test.ts
+++ b/tests/src/eth/marketplace/marketplace.test.ts
@@ -14,215 +14,208 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+import {usingPlaygrounds} from './../../util/playgrounds/index';
+import {IKeyringPair} from '@polkadot/types/types';
import {readFile} from 'fs/promises';
-import {getBalanceSingle} from '../../substrate/get-balance';
-import {
- addToAllowListExpectSuccess,
- confirmSponsorshipExpectSuccess,
- createCollectionExpectSuccess,
- createItemExpectSuccess,
- getTokenOwner,
- setCollectionLimitsExpectSuccess,
- setCollectionSponsorExpectSuccess,
- transferExpectSuccess,
- transferFromExpectSuccess,
- transferBalanceTo,
-} from '../../util/helpers';
-import {collectionIdToAddress, contractHelpers, createEthAccountWithBalance, executeEthTxOnSub, GAS_ARGS, itWeb3, SponsoringMode, subToEth, subToEthLowercase, transferBalanceToEth} from '../util/helpers';
-import {evmToAddress} from '@polkadot/util-crypto';
-import nonFungibleAbi from '../nonFungibleAbi.json';
+import {itEth, expect, SponsoringMode} from '../util/playgrounds';
-import {expect} from 'chai';
+describe('Matcher contract usage', () => {
+ const PRICE = 2000n;
+ let donor: IKeyringPair;
+ let alice: IKeyringPair;
+ let aliceMirror: string;
+ let aliceDoubleMirror: string;
+ let seller: IKeyringPair;
+ let sellerMirror: string;
+
+ before(async () => {
+ await usingPlaygrounds(async (_helper, privateKey) => {
+ donor = privateKey('//Alice');
+ });
+ });
+
+ beforeEach(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ [alice] = await helper.arrange.createAccounts([10000n], donor);
+ aliceMirror = helper.address.substrateToEth(alice.address).toLowerCase();
+ aliceDoubleMirror = helper.address.ethToSubstrate(aliceMirror);
+ seller = privateKey(`//Seller/${Date.now()}`);
+ sellerMirror = helper.address.substrateToEth(seller.address).toLowerCase();
-const PRICE = 2000n;
+ await helper.balance.transferToSubstrate(donor, aliceDoubleMirror, 10_000_000_000_000_000_000n);
+ });
+ });
-describe('Matcher contract usage', () => {
- itWeb3('With UNQ', async ({api, web3, privateKeyWrapper}) => {
- const alice = privateKeyWrapper('//Alice');
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const matcherOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ itEth('With UNQ', async ({helper}) => {
+ const web3 = helper.getWeb3();
+ const matcherOwner = await helper.eth.createAccountWithBalance(donor);
const matcherContract = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/MarketPlace.abi`)).toString()), undefined, {
from: matcherOwner,
- ...GAS_ARGS,
+ gas: helper.eth.DEFAULT_GAS,
});
const matcher = await matcherContract.deploy({data: (await readFile(`${__dirname}/MarketPlace.bin`)).toString(), arguments:[matcherOwner]}).send({from: matcherOwner});
- const helpers = contractHelpers(web3, matcherOwner);
+
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const helpers = helper.ethNativeContract.contractHelpers(matcherOwner);
await helpers.methods.setSponsoringMode(matcher.options.address, SponsoringMode.Allowlisted).send({from: matcherOwner});
await helpers.methods.setSponsoringRateLimit(matcher.options.address, 1).send({from: matcherOwner});
await helpers.methods.setSponsor(matcher.options.address, sponsor).send({from: matcherOwner});
await helpers.methods.confirmSponsorship(matcher.options.address).send({from: sponsor});
-
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionLimitsExpectSuccess(alice, collectionId, {sponsorApproveTimeout: 1});
- const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId), {from: matcherOwner});
- await setCollectionSponsorExpectSuccess(collectionId, alice.address);
- await transferBalanceToEth(api, alice, subToEth(alice.address));
- await confirmSponsorshipExpectSuccess(collectionId);
- await helpers.methods.toggleAllowed(matcher.options.address, subToEth(alice.address), true).send({from: matcherOwner});
- await addToAllowListExpectSuccess(alice, collectionId, evmToAddress(subToEth(alice.address)));
-
- const seller = privateKeyWrapper(`//Seller/${Date.now()}`);
- await helpers.methods.toggleAllowed(matcher.options.address, subToEth(seller.address), true).send({from: matcherOwner});
+ const collection = await helper.nft.mintCollection(alice, {limits: {sponsorApproveTimeout: 1}, pendingSponsor: alice.address});
+ await collection.confirmSponsorship(alice);
+ await collection.addToAllowList(alice, {Substrate: aliceDoubleMirror});
+ const evmCollection = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(collection.collectionId), 'nft');
+ await helper.eth.transferBalanceFromSubstrate(donor, aliceMirror);
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', seller.address);
+ await helpers.methods.toggleAllowed(matcher.options.address, aliceMirror, true).send({from: matcherOwner});
+ await helpers.methods.toggleAllowed(matcher.options.address, sellerMirror, true).send({from: matcherOwner});
- // 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)});
+ const token = await collection.mintToken(alice, {Ethereum: sellerMirror});
// Token is owned by seller initially
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(seller.address)});
+ expect(await token.getOwner()).to.be.deep.equal({Ethereum: sellerMirror});
// Ask
{
- await executeEthTxOnSub(web3, api, seller, evmCollection, m => m.approve(matcher.options.address, tokenId));
- await executeEthTxOnSub(web3, api, seller, matcher, m => m.addAsk(PRICE, '0x0000000000000000000000000000000000000001', evmCollection.options.address, tokenId));
+ await helper.eth.sendEVM(seller, evmCollection.options.address, evmCollection.methods.approve(matcher.options.address, token.tokenId).encodeABI(), '0');
+ await helper.eth.sendEVM(seller, matcher.options.address, matcher.methods.addAsk(PRICE, '0x0000000000000000000000000000000000000001', evmCollection.options.address, token.tokenId).encodeABI(), '0');
}
// Token is transferred to matcher
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: matcher.options.address.toLowerCase()});
+ expect(await token.getOwner()).to.be.deep.equal({Ethereum: matcher.options.address.toLowerCase()});
// Buy
{
- const sellerBalanceBeforePurchase = await getBalanceSingle(api, seller.address);
- await executeEthTxOnSub(web3, api, alice, matcher, m => m.buy(evmCollection.options.address, tokenId), {value: PRICE});
- expect(await getBalanceSingle(api, seller.address) - sellerBalanceBeforePurchase === PRICE);
+ const sellerBalanceBeforePurchase = await helper.balance.getSubstrate(seller.address);
+ await helper.eth.sendEVM(alice, matcher.options.address, matcher.methods.buy(evmCollection.options.address, token.tokenId).encodeABI(), PRICE.toString());
+ expect(await helper.balance.getSubstrate(seller.address) - sellerBalanceBeforePurchase === PRICE);
}
// Token is transferred to evm account of alice
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(alice.address)});
+ expect(await token.getOwner()).to.be.deep.equal({Ethereum: aliceMirror});
// Transfer token to substrate side of alice
- await transferFromExpectSuccess(collectionId, tokenId, alice, {Ethereum: subToEth(alice.address)}, {Substrate: alice.address});
+ await token.transferFrom(alice, {Ethereum: aliceMirror}, {Substrate: alice.address});
// Token is transferred to substrate account of alice, seller received funds
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Substrate: alice.address});
+ expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
-
- itWeb3('With escrow', async ({api, web3, privateKeyWrapper}) => {
- const alice = privateKeyWrapper('//Alice');
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const matcherOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const escrow = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ itEth('With escrow', async ({helper}) => {
+ const web3 = helper.getWeb3();
+ const matcherOwner = await helper.eth.createAccountWithBalance(donor);
const matcherContract = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/MarketPlace.abi`)).toString()), undefined, {
from: matcherOwner,
- ...GAS_ARGS,
+ gas: helper.eth.DEFAULT_GAS,
});
const matcher = await matcherContract.deploy({data: (await readFile(`${__dirname}/MarketPlace.bin`)).toString(), arguments: [matcherOwner]}).send({from: matcherOwner, gas: 10000000});
+
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const escrow = await helper.eth.createAccountWithBalance(donor);
await matcher.methods.setEscrow(escrow).send({from: matcherOwner});
- const helpers = contractHelpers(web3, matcherOwner);
+ const helpers = helper.ethNativeContract.contractHelpers(matcherOwner);
await helpers.methods.setSponsoringMode(matcher.options.address, SponsoringMode.Allowlisted).send({from: matcherOwner});
await helpers.methods.setSponsoringRateLimit(matcher.options.address, 1).send({from: matcherOwner});
await helpers.methods.setSponsor(matcher.options.address, sponsor).send({from: matcherOwner});
await helpers.methods.confirmSponsorship(matcher.options.address).send({from: sponsor});
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionLimitsExpectSuccess(alice, collectionId, {sponsorApproveTimeout: 1});
- const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId), {from: matcherOwner});
- await setCollectionSponsorExpectSuccess(collectionId, alice.address);
- await transferBalanceToEth(api, alice, subToEth(alice.address));
- await confirmSponsorshipExpectSuccess(collectionId);
+ const collection = await helper.nft.mintCollection(alice, {limits: {sponsorApproveTimeout: 1}, pendingSponsor: alice.address});
+ await collection.confirmSponsorship(alice);
+ await collection.addToAllowList(alice, {Substrate: aliceDoubleMirror});
+ const evmCollection = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(collection.collectionId), 'nft');
+ await helper.eth.transferBalanceFromSubstrate(donor, aliceMirror);
- await helpers.methods.toggleAllowed(matcher.options.address, subToEth(alice.address), true).send({from: matcherOwner});
- await addToAllowListExpectSuccess(alice, collectionId, evmToAddress(subToEth(alice.address)));
- const seller = privateKeyWrapper(`//Seller/${Date.now()}`);
- await helpers.methods.toggleAllowed(matcher.options.address, subToEth(seller.address), true).send({from: matcherOwner});
+ await helpers.methods.toggleAllowed(matcher.options.address, aliceMirror, true).send({from: matcherOwner});
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', seller.address);
+ await helpers.methods.toggleAllowed(matcher.options.address, sellerMirror, true).send({from: matcherOwner});
- // 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)});
+ const token = await collection.mintToken(alice, {Ethereum: sellerMirror});
// Token is owned by seller initially
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(seller.address)});
+ expect(await token.getOwner()).to.be.deep.equal({Ethereum: sellerMirror});
// Ask
{
- await executeEthTxOnSub(web3, api, seller, evmCollection, m => m.approve(matcher.options.address, tokenId));
- await executeEthTxOnSub(web3, api, seller, matcher, m => m.addAsk(PRICE, '0x0000000000000000000000000000000000000001', evmCollection.options.address, tokenId));
+ await helper.eth.sendEVM(seller, evmCollection.options.address, evmCollection.methods.approve(matcher.options.address, token.tokenId).encodeABI(), '0');
+ await helper.eth.sendEVM(seller, matcher.options.address, matcher.methods.addAsk(PRICE, '0x0000000000000000000000000000000000000001', evmCollection.options.address, token.tokenId).encodeABI(), '0');
}
// Token is transferred to matcher
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: matcher.options.address.toLowerCase()});
+ expect(await token.getOwner()).to.be.deep.equal({Ethereum: matcher.options.address.toLowerCase()});
// Give buyer KSM
- await matcher.methods.depositKSM(PRICE, subToEth(alice.address)).send({from: escrow});
+ await matcher.methods.depositKSM(PRICE, aliceMirror).send({from: escrow});
// Buy
{
- expect(await matcher.methods.balanceKSM(subToEth(seller.address)).call()).to.be.equal('0');
- expect(await matcher.methods.balanceKSM(subToEth(alice.address)).call()).to.be.equal(PRICE.toString());
+ expect(await matcher.methods.balanceKSM(sellerMirror).call()).to.be.equal('0');
+ expect(await matcher.methods.balanceKSM(aliceMirror).call()).to.be.equal(PRICE.toString());
- await executeEthTxOnSub(web3, api, alice, matcher, m => m.buyKSM(evmCollection.options.address, tokenId, subToEth(alice.address), subToEth(alice.address)));
+ await helper.eth.sendEVM(alice, matcher.options.address, matcher.methods.buyKSM(evmCollection.options.address, token.tokenId, aliceMirror, aliceMirror).encodeABI(), '0');
// Price is removed from buyer balance, and added to seller
- expect(await matcher.methods.balanceKSM(subToEth(alice.address)).call()).to.be.equal('0');
- expect(await matcher.methods.balanceKSM(subToEth(seller.address)).call()).to.be.equal(PRICE.toString());
+ expect(await matcher.methods.balanceKSM(aliceMirror).call()).to.be.equal('0');
+ expect(await matcher.methods.balanceKSM(sellerMirror).call()).to.be.equal(PRICE.toString());
}
// Token is transferred to evm account of alice
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(alice.address)});
+ expect(await token.getOwner()).to.be.deep.equal({Ethereum: aliceMirror});
// Transfer token to substrate side of alice
- await transferFromExpectSuccess(collectionId, tokenId, alice, {Ethereum: subToEth(alice.address)}, {Substrate: alice.address});
+ await token.transferFrom(alice, {Ethereum: aliceMirror}, {Substrate: alice.address});
// Token is transferred to substrate account of alice, seller received funds
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Substrate: alice.address});
+ expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
-
- itWeb3('Sell tokens from substrate user via EVM contract', async ({api, web3, privateKeyWrapper}) => {
- const alice = privateKeyWrapper('//Alice');
- const matcherOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ itEth('Sell tokens from substrate user via EVM contract', async ({helper}) => {
+ const web3 = helper.getWeb3();
+ const matcherOwner = await helper.eth.createAccountWithBalance(donor);
const matcherContract = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/MarketPlace.abi`)).toString()), undefined, {
from: matcherOwner,
- ...GAS_ARGS,
+ gas: helper.eth.DEFAULT_GAS,
});
const matcher = await matcherContract.deploy({data: (await readFile(`${__dirname}/MarketPlace.bin`)).toString(), arguments:[matcherOwner]}).send({from: matcherOwner});
- await transferBalanceToEth(api, alice, matcher.options.address);
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setCollectionLimitsExpectSuccess(alice, collectionId, {sponsorApproveTimeout: 1});
- const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId), {from: matcherOwner});
+ await helper.eth.transferBalanceFromSubstrate(donor, matcher.options.address);
+
+ const collection = await helper.nft.mintCollection(alice, {limits: {sponsorApproveTimeout: 1}});
+ const evmCollection = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(collection.collectionId), 'nft');
- const seller = privateKeyWrapper(`//Seller/${Date.now()}`);
- await transferBalanceTo(api, alice, seller.address);
+ await helper.balance.transferToSubstrate(donor, seller.address, 100_000_000_000_000_000_000n);
- 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)});
+ const token = await collection.mintToken(alice, {Ethereum: sellerMirror});
// Token is owned by seller initially
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(seller.address)});
+ expect(await token.getOwner()).to.be.deep.equal({Ethereum: sellerMirror});
// Ask
{
- await executeEthTxOnSub(web3, api, seller, evmCollection, m => m.approve(matcher.options.address, tokenId));
- await executeEthTxOnSub(web3, api, seller, matcher, m => m.addAsk(PRICE, '0x0000000000000000000000000000000000000001', evmCollection.options.address, tokenId));
+ await helper.eth.sendEVM(seller, evmCollection.options.address, evmCollection.methods.approve(matcher.options.address, token.tokenId).encodeABI(), '0');
+ await helper.eth.sendEVM(seller, matcher.options.address, matcher.methods.addAsk(PRICE, '0x0000000000000000000000000000000000000001', evmCollection.options.address, token.tokenId).encodeABI(), '0');
}
// Token is transferred to matcher
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: matcher.options.address.toLowerCase()});
+ expect(await token.getOwner()).to.be.deep.equal({Ethereum: matcher.options.address.toLowerCase()});
// Buy
{
- const sellerBalanceBeforePurchase = await getBalanceSingle(api, seller.address);
- await executeEthTxOnSub(web3, api, alice, matcher, m => m.buy(evmCollection.options.address, tokenId), {value: PRICE});
- expect(await getBalanceSingle(api, seller.address) - sellerBalanceBeforePurchase === PRICE);
+ const sellerBalanceBeforePurchase = await helper.balance.getSubstrate(seller.address);
+ await helper.eth.sendEVM(alice, matcher.options.address, matcher.methods.buy(evmCollection.options.address, token.tokenId).encodeABI(), PRICE.toString());
+ expect(await helper.balance.getSubstrate(seller.address) - sellerBalanceBeforePurchase === PRICE);
}
// Token is transferred to evm account of alice
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(alice.address)});
+ expect(await token.getOwner()).to.be.deep.equal({Ethereum: aliceMirror});
// Transfer token to substrate side of alice
- await transferFromExpectSuccess(collectionId, tokenId, alice, {Ethereum: subToEth(alice.address)}, {Substrate: alice.address});
+ await token.transferFrom(alice, {Ethereum: aliceMirror}, {Substrate: alice.address});
// Token is transferred to substrate account of alice, seller received funds
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Substrate: alice.address});
+ expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
});
});
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -17,8 +17,8 @@
import {itEth, usingEthPlaygrounds, expect, EthUniqueHelper} from './util/playgrounds';
import {IKeyringPair} from '@polkadot/types/types';
import {Contract} from 'web3-eth-contract';
-import {UNIQUE} from '../util/helpers';
+
describe('NFT: Information getting', () => {
let donor: IKeyringPair;
let alice: IKeyringPair;
@@ -84,7 +84,7 @@
const receiver = helper.eth.createAccount();
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * UNIQUE)});
+ let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
tests/src/eth/proxy/fungibleProxy.test.tsdiffbeforeafterboth--- a/tests/src/eth/proxy/fungibleProxy.test.ts
+++ b/tests/src/eth/proxy/fungibleProxy.test.ts
@@ -14,7 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {GAS_ARGS, normalizeEvents} from '../util/helpers';
import {expect} from 'chai';
import {readFile} from 'fs/promises';
import {IKeyringPair} from '@polkadot/types/types';
@@ -26,7 +25,7 @@
const web3 = helper.getWeb3();
const proxyContract = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/UniqueFungibleProxy.abi`)).toString()), undefined, {
from: owner,
- ...GAS_ARGS,
+ gas: helper.eth.DEFAULT_GAS,
});
const proxy = await proxyContract.deploy({data: (await readFile(`${__dirname}/UniqueFungibleProxy.bin`)).toString(), arguments: [wrapped.options.address]}).send({from: owner});
return proxy;
@@ -94,7 +93,7 @@
{
const result = await contract.methods.approve(spender, 100).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -131,7 +130,7 @@
{
const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
address,
@@ -177,7 +176,7 @@
{
const result = await contract.methods.transfer(receiver, 50).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
address,
tests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth--- a/tests/src/eth/proxy/nonFungibleProxy.test.ts
+++ b/tests/src/eth/proxy/nonFungibleProxy.test.ts
@@ -14,11 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {GAS_ARGS, itWeb3, normalizeEvents} from '../util/helpers';
-import {expect} from 'chai';
import {readFile} from 'fs/promises';
import {IKeyringPair} from '@polkadot/types/types';
-import {EthUniqueHelper, itEth, usingEthPlaygrounds} from '../util/playgrounds';
+import {EthUniqueHelper, itEth, usingEthPlaygrounds, expect} from '../util/playgrounds';
+
async function proxyWrap(helper: EthUniqueHelper, wrapped: any, donor: IKeyringPair) {
// Proxy owner has no special privilegies, we don't need to reuse them
@@ -26,7 +25,7 @@
const web3 = helper.getWeb3();
const proxyContract = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/UniqueNFTProxy.abi`)).toString()), undefined, {
from: owner,
- ...GAS_ARGS,
+ gas: helper.eth.DEFAULT_GAS,
});
const proxy = await proxyContract.deploy({data: (await readFile(`${__dirname}/UniqueNFTProxy.bin`)).toString(), arguments: [wrapped.options.address]}).send({from: owner});
return proxy;
@@ -119,7 +118,7 @@
nextTokenId,
'Test URI',
).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
events[0].address = events[0].address.toLocaleLowerCase();
expect(events).to.be.deep.equal([
@@ -139,20 +138,16 @@
});
//TODO: CORE-302 add eth methods
- itWeb3.skip('Can perform mintBulk()', async () => {
- /*
- const collection = await createCollectionExpectSuccess({
- mode: {type: 'NFT'},
- });
- const alice = privateKeyWrapper('//Alice');
+ itEth.skip('Can perform mintBulk()', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(donor, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
- const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const receiver = createEthAccount(web3);
+ const caller = await helper.eth.createAccountWithBalance(donor, 30n);
+ const receiver = helper.eth.createAccount();
- const address = collectionIdToAddress(collection);
- const contract = await proxyWrap(api, web3, new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS}), privateKeyWrapper);
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collection, {Ethereum: contract.options.address});
- await submitTransactionAsync(alice, changeAdminTx);
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const evmCollection = helper.ethNativeContract.collection(address, 'nft', caller);
+ const contract = await proxyWrap(helper, evmCollection, donor);
+ await collection.addAdmin(donor, {Ethereum: contract.options.address});
{
const nextTokenId = await contract.methods.nextTokenId().call();
@@ -165,7 +160,7 @@
[+nextTokenId + 2, 'Test URI 2'],
],
).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -201,7 +196,6 @@
expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');
expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');
}
- */
});
itEth('Can perform burn()', async ({helper}) => {
@@ -216,7 +210,7 @@
{
const result = await contract.methods.burn(tokenId).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -243,8 +237,8 @@
const {tokenId} = await collection.mintToken(alice, {Ethereum: contract.options.address});
{
- const result = await contract.methods.approve(spender, tokenId).send({from: caller, ...GAS_ARGS});
- const events = normalizeEvents(result.events);
+ const result = await contract.methods.approve(spender, tokenId).send({from: caller, gas: helper.eth.DEFAULT_GAS});
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -276,7 +270,7 @@
{
const result = await contract.methods.transferFrom(owner, receiver, tokenId).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
address,
@@ -313,7 +307,7 @@
{
const result = await contract.methods.transfer(receiver, tokenId).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
address,
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -18,8 +18,8 @@
import {EthUniqueHelper, expect, itEth, usingEthPlaygrounds} from './util/playgrounds';
import {IKeyringPair} from '@polkadot/types/types';
import {Contract} from 'web3-eth-contract';
-import {UNIQUE} from '../util/helpers';
+
describe('Refungible token: Information getting', () => {
let donor: IKeyringPair;
let alice: IKeyringPair;
@@ -81,7 +81,7 @@
const receiver = helper.eth.createAccount();
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * UNIQUE)});
+ let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
tests/src/eth/scheduling.test.tsdiffbeforeafterboth--- a/tests/src/eth/scheduling.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {expect} from 'chai';
-import {createEthAccountWithBalance, deployFlipper, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';
-import {scheduleExpectSuccess, waitNewBlocks, requirePallets, Pallets} from '../util/helpers';
-
-describe('Scheduing EVM smart contracts', () => {
- before(async function() {
- await requirePallets(this, [Pallets.Scheduler]);
- });
-
- itWeb3('Successfully schedules and periodically executes an EVM contract', async ({api, web3, privateKeyWrapper}) => {
- const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const flipper = await deployFlipper(web3, deployer);
- const initialValue = await flipper.methods.getValue().call();
- const alice = privateKeyWrapper('//Alice');
- await transferBalanceToEth(api, alice, subToEth(alice.address));
-
- {
- const tx = api.tx.evm.call(
- subToEth(alice.address),
- flipper.options.address,
- flipper.methods.flip().encodeABI(),
- '0',
- GAS_ARGS.gas,
- await web3.eth.getGasPrice(),
- null,
- null,
- [],
- );
- const waitForBlocks = 4;
- const periodBlocks = 2;
-
- await scheduleExpectSuccess(tx, alice, waitForBlocks, '0x' + '0'.repeat(32), periodBlocks, 2);
- expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
-
- await waitNewBlocks(waitForBlocks - 1);
- expect(await flipper.methods.getValue().call()).to.be.not.equal(initialValue);
-
- await waitNewBlocks(periodBlocks);
- expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
- }
- });
-});
tests/src/eth/sponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/sponsoring.test.ts
+++ b/tests/src/eth/sponsoring.test.ts
@@ -14,20 +14,31 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {expect} from 'chai';
-import {contractHelpers, createEthAccount, createEthAccountWithBalance, deployCollector, deployFlipper, itWeb3, SponsoringMode} from './util/helpers';
+import {IKeyringPair} from '@polkadot/types/types';
+import {itEth, expect, SponsoringMode} from '../eth/util/playgrounds';
+import {usingPlaygrounds} from './../util/playgrounds/index';
describe('EVM sponsoring', () => {
- itWeb3('Fee is deducted from contract if sponsoring is enabled', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const caller = createEthAccount(web3);
- const originalCallerBalance = await web3.eth.getBalance(caller);
- expect(originalCallerBalance).to.be.equal('0');
+ let donor: IKeyringPair;
- const flipper = await deployFlipper(web3, owner);
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ donor = privateKey('//Alice');
+ });
+ });
+
+ itEth('Fee is deducted from contract if sponsoring is enabled', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const caller = helper.eth.createAccount();
+ const originalCallerBalance = await helper.balance.getEthereum(caller);
+
+ expect(originalCallerBalance).to.be.equal(0n);
+
+ const flipper = await helper.eth.deployFlipper(owner);
+
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
- const helpers = contractHelpers(web3, owner);
await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});
await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});
@@ -39,27 +50,29 @@
await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
- const originalSponsorBalance = await web3.eth.getBalance(sponsor);
- expect(originalSponsorBalance).to.be.not.equal('0');
+ const originalSponsorBalance = await helper.balance.getEthereum(sponsor);
+ expect(originalSponsorBalance).to.be.not.equal(0n);
await flipper.methods.flip().send({from: caller});
expect(await flipper.methods.getValue().call()).to.be.true;
// Balance should be taken from flipper instead of caller
- expect(await web3.eth.getBalance(caller)).to.be.equals(originalCallerBalance);
- expect(await web3.eth.getBalance(sponsor)).to.be.not.equals(originalSponsorBalance);
+ expect(await helper.balance.getEthereum(caller)).to.be.equal(originalCallerBalance);
+ expect(await helper.balance.getEthereum(sponsor)).to.be.not.equal(originalSponsorBalance);
});
- itWeb3('...but this doesn\'t applies to payable value', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const sponsor = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const originalCallerBalance = await web3.eth.getBalance(caller);
- expect(originalCallerBalance).to.be.not.equal('0');
+ itEth('...but this doesn\'t applies to payable value', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const originalCallerBalance = await helper.balance.getEthereum(caller);
+
+ expect(originalCallerBalance).to.be.not.equal(0n);
+
+ const collector = await helper.eth.deployCollectorContract(owner);
- const collector = await deployCollector(web3, owner);
+ const helpers = helper.ethNativeContract.contractHelpers(owner);
- const helpers = contractHelpers(web3, owner);
await helpers.methods.toggleAllowlist(collector.options.address, true).send({from: owner});
await helpers.methods.toggleAllowed(collector.options.address, caller, true).send({from: owner});
@@ -71,14 +84,14 @@
await helpers.methods.setSponsor(collector.options.address, sponsor).send({from: owner});
await helpers.methods.confirmSponsorship(collector.options.address).send({from: sponsor});
- const originalSponsorBalance = await web3.eth.getBalance(sponsor);
- expect(originalSponsorBalance).to.be.not.equal('0');
+ const originalSponsorBalance = await helper.balance.getEthereum(sponsor);
+ expect(originalSponsorBalance).to.be.not.equal(0n);
await collector.methods.giveMoney().send({from: caller, value: '10000'});
// Balance will be taken from both caller (value) and from collector (fee)
- expect(await web3.eth.getBalance(caller)).to.be.equals((BigInt(originalCallerBalance) - 10000n).toString());
- expect(await web3.eth.getBalance(sponsor)).to.be.not.equals(originalSponsorBalance);
+ expect(await helper.balance.getEthereum(caller)).to.be.equals((originalCallerBalance - 10000n));
+ expect(await helper.balance.getEthereum(sponsor)).to.be.not.equals(originalSponsorBalance);
expect(await collector.methods.getCollected().call()).to.be.equal('10000');
});
});
tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {itEth, usingEthPlaygrounds, expect, cartesian} from './util/playgrounds';
+import {itEth, usingEthPlaygrounds, expect} from './util/playgrounds';
import {IKeyringPair} from '@polkadot/types/types';
describe('EVM token properties', () => {
@@ -48,16 +48,16 @@
itEth('Can be set', async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice);
+ const collection = await helper.nft.mintCollection(alice, {
+ tokenPropertyPermissions: [{
+ key: 'testKey',
+ permission: {
+ collectionAdmin: true,
+ },
+ }],
+ });
const token = await collection.mintToken(alice);
- await collection.setTokenPropertyPermissions(alice, [{
- key: 'testKey',
- permission: {
- collectionAdmin: true,
- },
- }]);
-
await collection.addAdmin(alice, {Ethereum: caller});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
@@ -71,16 +71,17 @@
itEth('Can be deleted', async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice);
+ const collection = await helper.nft.mintCollection(alice, {
+ tokenPropertyPermissions: [{
+ key: 'testKey',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ },
+ }],
+ });
+
const token = await collection.mintToken(alice);
-
- await collection.setTokenPropertyPermissions(alice, [{
- key: 'testKey',
- permission: {
- mutable: true,
- collectionAdmin: true,
- },
- }]);
await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}]);
await collection.addAdmin(alice, {Ethereum: caller});
@@ -96,15 +97,16 @@
itEth('Can be read', async({helper}) => {
const caller = helper.eth.createAccount();
- const collection = await helper.nft.mintCollection(alice);
+ const collection = await helper.nft.mintCollection(alice, {
+ tokenPropertyPermissions: [{
+ key: 'testKey',
+ permission: {
+ collectionAdmin: true,
+ },
+ }],
+ });
+
const token = await collection.mintToken(alice);
-
- await collection.setTokenPropertyPermissions(alice, [{
- key: 'testKey',
- permission: {
- collectionAdmin: true,
- },
- }]);
await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}]);
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
@@ -114,3 +116,15 @@
expect(value).to.equal(helper.getWeb3().utils.toHex('testValue'));
});
});
+
+
+type ElementOf<A> = A extends readonly (infer T)[] ? T : never;
+function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {
+ if(args.length === 0) {
+ yield internalRest as any;
+ return;
+ }
+ for(const value of args[0]) {
+ yield* cartesian([...internalRest, value], ...args.slice(1)) as any;
+ }
+}
tests/src/eth/util/helpers.d.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.d.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-declare module 'solc';
\ No newline at end of file
tests/src/eth/util/helpers.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.ts
+++ /dev/null
@@ -1,451 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// eslint-disable-next-line @typescript-eslint/triple-slash-reference
-/// <reference path="helpers.d.ts" />
-
-import {ApiPromise} from '@polkadot/api';
-import {IKeyringPair} from '@polkadot/types/types';
-import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';
-import {expect} from 'chai';
-import * as solc from 'solc';
-import Web3 from 'web3';
-import config from '../../config';
-import getBalance from '../../substrate/get-balance';
-import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';
-import waitNewBlocks from '../../substrate/wait-new-blocks';
-import {CollectionMode, CrossAccountId, getDetailedCollectionInfo, getGenericResult, UNIQUE} from '../../util/helpers';
-import collectionHelpersAbi from '../collectionHelpersAbi.json';
-import fungibleAbi from '../fungibleAbi.json';
-import nonFungibleAbi from '../nonFungibleAbi.json';
-import refungibleAbi from '../reFungibleAbi.json';
-import refungibleTokenAbi from '../reFungibleTokenAbi.json';
-import contractHelpersAbi from './contractHelpersAbi.json';
-
-export const GAS_ARGS = {gas: 2500000};
-
-export enum SponsoringMode {
- Disabled = 0,
- Allowlisted = 1,
- Generous = 2,
-}
-
-let web3Connected = false;
-export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {
- if (web3Connected) throw new Error('do not nest usingWeb3 calls');
- web3Connected = true;
-
- const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);
- const web3 = new Web3(provider);
-
- try {
- return await cb(web3);
- } finally {
- // provider.disconnect(3000, 'normal disconnect');
- provider.connection.close();
- web3Connected = false;
- }
-}
-
-function encodeIntBE(v: number): number[] {
- if (v >= 0xffffffff || v < 0) throw new Error('id overflow');
- return [
- v >> 24,
- (v >> 16) & 0xff,
- (v >> 8) & 0xff,
- v & 0xff,
- ];
-}
-
-export async function getCollectionAddressFromResult(api: ApiPromise, result: any) {
- const collectionIdAddress = normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
- const collectionId = collectionIdFromAddress(collectionIdAddress);
- const collection = (await getDetailedCollectionInfo(api, collectionId))!;
- return {collectionIdAddress, collectionId, collection};
-}
-
-export function collectionIdToAddress(collection: number): string {
- const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
- ...encodeIntBE(collection),
- ]);
- return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
-}
-export function collectionIdFromAddress(address: string): number {
- if (!address.startsWith('0x'))
- throw 'address not starts with "0x"';
- if (address.length > 42)
- throw 'address length is more than 20 bytes';
- return Number('0x' + address.substring(address.length - 8));
-}
-
-export function normalizeAddress(address: string): string {
- return '0x' + address.substring(address.length - 40);
-}
-
-export function tokenIdToAddress(collection: number, token: number): string {
- const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
- ...encodeIntBE(collection),
- ...encodeIntBE(token),
- ]);
- return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
-}
-
-export function tokenIdFromAddress(address: string) {
- if (!address.startsWith('0x'))
- throw 'address not starts with "0x"';
- if (address.length > 42)
- throw 'address length is more than 20 bytes';
- return {
- collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),
- tokenId: Number('0x' + address.substring(address.length - 8)),
- };
-}
-
-export function tokenIdToCross(collection: number, token: number): CrossAccountId {
- return {
- Ethereum: tokenIdToAddress(collection, token),
- };
-}
-
-export function createEthAccount(web3: Web3) {
- const account = web3.eth.accounts.create();
- web3.eth.accounts.wallet.add(account.privateKey);
- return account.address;
-}
-
-export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair) {
- const alice = privateKeyWrapper('//Alice');
- const account = createEthAccount(web3);
- await transferBalanceToEth(api, alice, account);
-
- return account;
-}
-
-export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {
- const tx = api.tx.balances.transfer(evmToAddress(target), amount);
- const events = await submitTransactionAsync(source, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-}
-
-export async function createRFTCollection(api: ApiPromise, web3: Web3, owner: string) {
- const collectionHelper = evmCollectionHelpers(web3, owner);
- const result = await collectionHelper.methods
- .createRFTCollection('A', 'B', 'C')
- .send({value: Number(2n * UNIQUE)});
- return await getCollectionAddressFromResult(api, result);
-}
-
-
-export async function createNonfungibleCollection(api: ApiPromise, web3: Web3, owner: string) {
- const collectionHelper = evmCollectionHelpers(web3, owner);
- const result = await collectionHelper.methods
- .createNonfungibleCollection('A', 'B', 'C')
- .send({value: Number(2n * UNIQUE)});
- return await getCollectionAddressFromResult(api, result);
-}
-
-export function uniqueNFT(web3: Web3, address: string, owner: string) {
- return new web3.eth.Contract(nonFungibleAbi as any, address, {
- from: owner,
- ...GAS_ARGS,
- });
-}
-
-export function uniqueRefungible(web3: Web3, collectionAddress: string, owner: string) {
- return new web3.eth.Contract(refungibleAbi as any, collectionAddress, {
- from: owner,
- ...GAS_ARGS,
- });
-}
-
-export function uniqueRefungibleToken(web3: Web3, tokenAddress: string, owner: string | undefined = undefined) {
- return new web3.eth.Contract(refungibleTokenAbi as any, tokenAddress, {
- from: owner,
- ...GAS_ARGS,
- });
-}
-
-export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
- let i: any = it;
- if (opts.only) i = i.only;
- else if (opts.skip) i = i.skip;
- i(name, async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- await usingWeb3(async web3 => {
- await cb({api, web3, privateKeyWrapper});
- });
- });
- });
-}
-itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {only: true});
-itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {skip: true});
-
-export async function generateSubstrateEthPair(web3: Web3) {
- const account = web3.eth.accounts.create();
- evmToAddress(account.address);
-}
-
-type NormalizedEvent = {
- address: string,
- event: string,
- args: { [key: string]: string }
-};
-
-export function normalizeEvents(events: any): NormalizedEvent[] {
- const output = [];
- for (const key of Object.keys(events)) {
- if (key.match(/^[0-9]+$/)) {
- output.push(events[key]);
- } else if (Array.isArray(events[key])) {
- output.push(...events[key]);
- } else {
- output.push(events[key]);
- }
- }
- output.sort((a, b) => a.logIndex - b.logIndex);
- return output.map(({address, event, returnValues}) => {
- const args: { [key: string]: string } = {};
- for (const key of Object.keys(returnValues)) {
- if (!key.match(/^[0-9]+$/)) {
- args[key] = returnValues[key];
- }
- }
- return {
- address,
- event,
- args,
- };
- });
-}
-
-export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {
- const out: any = [];
- contract.events.allEvents((_: any, event: any) => {
- out.push(event);
- });
- await action();
- 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 {
- return Web3.utils.toChecksumAddress(subToEthLowercase(eth));
-}
-
-export interface CompiledContract {
- abi: any,
- object: string,
-}
-
-export function compileContract(name: string, src: string) : CompiledContract {
- const out = JSON.parse(solc.compile(JSON.stringify({
- language: 'Solidity',
- sources: {
- [`${name}.sol`]: {
- content: `
- // SPDX-License-Identifier: UNLICENSED
- pragma solidity ^0.8.6;
-
- ${src}
- `,
- },
- },
- settings: {
- outputSelection: {
- '*': {
- '*': ['*'],
- },
- },
- },
- }))).contracts[`${name}.sol`][name];
-
- return {
- abi: out.abi,
- object: '0x' + out.evm.bytecode.object,
- };
-}
-
-export async function deployFlipper(web3: Web3, deployer: string) {
- const compiled = compileContract('Flipper', `
- contract Flipper {
- bool value = false;
- function flip() public {
- value = !value;
- }
- function getValue() public view returns (bool) {
- return value;
- }
- }
- `);
- const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {
- data: compiled.object,
- from: deployer,
- ...GAS_ARGS,
- });
- const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});
-
- return flipper;
-}
-
-export async function deployCollector(web3: Web3, deployer: string) {
- const compiled = compileContract('Collector', `
- contract Collector {
- uint256 collected;
- fallback() external payable {
- giveMoney();
- }
- function giveMoney() public payable {
- collected += msg.value;
- }
- function getCollected() public view returns (uint256) {
- return collected;
- }
- function getUnaccounted() public view returns (uint256) {
- return address(this).balance - collected;
- }
-
- function withdraw(address payable target) public {
- target.transfer(collected);
- collected = 0;
- }
- }
- `);
- const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {
- data: compiled.object,
- from: deployer,
- ...GAS_ARGS,
- });
- const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});
-
- return collector;
-}
-
-/**
- * pallet evm_contract_helpers
- * @param web3
- * @param caller - eth address
- * @returns
- */
-export function contractHelpers(web3: Web3, caller: string) {
- return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});
-}
-
-/**
- * evm collection helper
- * @param web3
- * @param caller - eth address
- * @returns
- */
-export function evmCollectionHelpers(web3: Web3, caller: string) {
- return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
-}
-
-/**
- * evm collection
- * @param web3
- * @param caller - eth address
- * @returns
- */
-export function evmCollection(web3: Web3, caller: string, collection: string, mode: CollectionMode = {type: 'NFT'}) {
- let abi;
- switch (mode.type) {
- case 'Fungible':
- abi = fungibleAbi;
- break;
-
- case 'NFT':
- abi = nonFungibleAbi;
- break;
-
- case 'ReFungible':
- abi = refungibleAbi;
- break;
-
- default:
- throw 'Bad collection mode';
- }
- const contract = new web3.eth.Contract(abi as any, collection, {from: caller, ...GAS_ARGS});
- return contract;
-}
-
-/**
- * Execute ethereum method call using substrate account
- * @param to target contract
- * @param mkTx - closure, receiving `contract.methods`, and returning method call,
- * to be used as following (assuming `to` = erc20 contract):
- * `m => m.transfer(to, amount)`
- *
- * # Example
- * ```ts
- * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));
- * ```
- */
-export async function executeEthTxOnSub(web3: Web3, 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,
- await web3.eth.getGasPrice(),
- null,
- null,
- [],
- );
- const events = await submitTransactionAsync(from, tx);
- expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;
-}
-
-export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {
- return (await getBalance(api, [evmToAddress(address)]))[0];
-}
-
-/**
- * Measure how much gas given closure consumes
- *
- * @param user which user balance will be checked
- */
-export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {
- const before = await ethBalanceViaSub(api, user);
-
- await call();
-
- // In dev mode, the transaction might not finish processing in time
- await waitNewBlocks(api, 1);
- const after = await ethBalanceViaSub(api, user);
-
- // Can't use .to.be.less, because chai doesn't supports bigint
- expect(after < before).to.be.true;
-
- return before - after;
-}
-
-type ElementOf<A> = A extends readonly (infer T)[] ? T : never;
-// I want a fancier api, not a memory efficiency
-export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {
- if(args.length === 0) {
- yield internalRest as any;
- return;
- }
- for(const value of args[0]) {
- yield* cartesian([...internalRest, value], ...args.slice(1)) as any;
- }
-}
\ No newline at end of file
tests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/index.ts
+++ b/tests/src/eth/util/playgrounds/index.ts
@@ -20,6 +20,12 @@
chai.use(chaiLike);
export const expect = chai.expect;
+export enum SponsoringMode {
+ Disabled = 0,
+ Allowlisted = 1,
+ Generous = 2,
+}
+
export const usingEthPlaygrounds = async (code: (helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair>) => Promise<void>) => {
const silentConsole = new SilentConsole();
silentConsole.enable();
@@ -48,7 +54,6 @@
}
finally {
await helper.disconnect();
- await helper.disconnectWeb3();
silentConsole.disable();
}
};
@@ -76,15 +81,3 @@
itEthIfWithPallet.only = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itEthIfWithPallet(name, required, cb, {only: true});
itEthIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itEthIfWithPallet(name, required, cb, {skip: true});
itEth.ifWithPallets = itEthIfWithPallet;
-
-type ElementOf<A> = A extends readonly (infer T)[] ? T : never;
-// I want a fancier api, not a memory efficiency
-export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {
- if(args.length === 0) {
- yield internalRest as any;
- return;
- }
- for(const value of args[0]) {
- yield* cartesian([...internalRest, value], ...args.slice(1)) as any;
- }
-}
tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -6,4 +6,10 @@
export interface CompiledContract {
abi: any;
object: string;
-}
\ No newline at end of file
+}
+
+export type NormalizedEvent = {
+ address: string,
+ event: string,
+ args: { [key: string]: string }
+};
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -18,7 +18,7 @@
import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';
-import {ContractImports, CompiledContract} from './types';
+import {ContractImports, CompiledContract, NormalizedEvent} from './types';
// Native contracts ABI
import collectionHelpersAbi from '../../collectionHelpersAbi.json';
@@ -27,7 +27,7 @@
import refungibleAbi from '../../reFungibleAbi.json';
import refungibleTokenAbi from '../../reFungibleTokenAbi.json';
import contractHelpersAbi from './../contractHelpersAbi.json';
-import {TEthereumAccount} from '../../../util/playgrounds/types';
+import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';
class EthGroupBase {
helper: EthUniqueHelper;
@@ -252,6 +252,42 @@
return before - after;
}
+
+ normalizeEvents(events: any): NormalizedEvent[] {
+ const output = [];
+ for (const key of Object.keys(events)) {
+ if (key.match(/^[0-9]+$/)) {
+ output.push(events[key]);
+ } else if (Array.isArray(events[key])) {
+ output.push(...events[key]);
+ } else {
+ output.push(events[key]);
+ }
+ }
+ output.sort((a, b) => a.logIndex - b.logIndex);
+ return output.map(({address, event, returnValues}) => {
+ const args: { [key: string]: string } = {};
+ for (const key of Object.keys(returnValues)) {
+ if (!key.match(/^[0-9]+$/)) {
+ args[key] = returnValues[key];
+ }
+ }
+ return {
+ address,
+ event,
+ args,
+ };
+ });
+ }
+
+ async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {
+ const wrappedCode = async () => {
+ await code();
+ // In dev mode, the transaction might not finish processing in time
+ await this.helper.wait.newBlocks(1);
+ };
+ return await this.helper.arrange.calculcateFee(address, wrappedCode);
+ }
}
class EthAddressGroup extends EthGroupBase {
@@ -285,6 +321,7 @@
}
}
+export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;
export class EthUniqueHelper extends DevUniqueHelper {
web3: Web3 | null = null;
@@ -295,8 +332,10 @@
ethNativeContract: NativeContractGroup;
ethContract: ContractGroup;
- constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
- super(logger);
+ constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
+ options.helperBase = options.helperBase ?? EthUniqueHelper;
+
+ super(logger, options);
this.eth = new EthGroup(this);
this.ethAddress = new EthAddressGroup(this);
this.ethNativeContract = new NativeContractGroup(this);
@@ -314,10 +353,23 @@
this.web3 = new Web3(this.web3Provider);
}
- async disconnectWeb3() {
+ async disconnect() {
if(this.web3 === null) return;
this.web3Provider?.connection.close();
+
+ await super.disconnect();
+ }
+
+ clearApi() {
this.web3 = null;
}
+
+ clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {
+ const newHelper = super.clone(helperCls, options) as EthUniqueHelper;
+ newHelper.web3 = this.web3;
+ newHelper.web3Provider = this.web3Provider;
+
+ return newHelper;
+ }
}
\ No newline at end of file
tests/src/flipper/flipper.wasmdiffbeforeafterbothbinary blob — no preview
tests/src/flipper/metadata.jsondiffbeforeafterboth--- a/tests/src/flipper/metadata.json
+++ /dev/null
@@ -1,110 +0,0 @@
-{
- "metadataVersion": "0.1.0",
- "source": {
- "hash": "0x5b02ceadaacee8408d3c6496394847092c099bcb897221dbe8d22c16d372fa17",
- "language": "ink! 3.0.0-rc2",
- "compiler": "rustc 1.51.0-nightly"
- },
- "contract": {
- "name": "flipper",
- "version": "0.1.0",
- "authors": [
- "[your_name] <[your_email]>"
- ]
- },
- "spec": {
- "constructors": [
- {
- "args": [
- {
- "name": "init_value",
- "type": {
- "displayName": [
- "bool"
- ],
- "type": 1
- }
- }
- ],
- "docs": [
- " Constructor that initializes the `bool` value to the given `init_value`."
- ],
- "name": [
- "new"
- ],
- "selector": "0xd183512b"
- },
- {
- "args": [],
- "docs": [
- " Constructor that initializes the `bool` value to `false`.",
- "",
- " Constructors can delegate to other constructors."
- ],
- "name": [
- "default"
- ],
- "selector": "0x6a3712e2"
- }
- ],
- "docs": [],
- "events": [],
- "messages": [
- {
- "args": [],
- "docs": [
- " A message that can be called on instantiated contracts.",
- " This one flips the value of the stored `bool` from `true`",
- " to `false` and vice versa."
- ],
- "mutates": true,
- "name": [
- "flip"
- ],
- "payable": false,
- "returnType": null,
- "selector": "0xc096a5f3"
- },
- {
- "args": [],
- "docs": [
- " Simply returns the current value of our `bool`."
- ],
- "mutates": false,
- "name": [
- "get"
- ],
- "payable": false,
- "returnType": {
- "displayName": [
- "bool"
- ],
- "type": 1
- },
- "selector": "0x1e5ca456"
- }
- ]
- },
- "storage": {
- "struct": {
- "fields": [
- {
- "layout": {
- "cell": {
- "key": "0x0000000000000000000000000000000000000000000000000000000000000000",
- "ty": 1
- }
- },
- "name": "value"
- }
- ]
- }
- },
- "types": [
- {
- "def": {
- "primitive": "bool"
- }
- }
- ]
-}
\ No newline at end of file
tests/src/inflation.test.tsdiffbeforeafterboth--- a/tests/src/inflation.test.ts
+++ b/tests/src/inflation.test.ts
@@ -40,9 +40,9 @@
const tx = helper.constructApiCall('api.tx.inflation.startInflation', [1]);
await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [tx])).to.not.be.rejected;
- const blockInterval = (helper.api!.consts.inflation.inflationBlockInterval as any).toBigInt();
- const totalIssuanceStart = ((await helper.api!.query.inflation.startingYearTotalIssuance()) as any).toBigInt();
- const blockInflation = (await helper.api!.query.inflation.blockInflation() as any).toBigInt();
+ const blockInterval = (helper.getApi().consts.inflation.inflationBlockInterval as any).toBigInt();
+ const totalIssuanceStart = ((await helper.callRpc('api.query.inflation.startingYearTotalIssuance', [])) as any).toBigInt();
+ const blockInflation = (await helper.callRpc('api.query.inflation.blockInflation', []) as any).toBigInt();
const YEAR = 5259600n; // 6-second block. Blocks in one year
// const YEAR = 2629800n; // 12-second block. Blocks in one year
tests/src/load_test_sc/loadtester.wasmdiffbeforeafterbothbinary blob — no preview
tests/src/load_test_sc/metadata.jsondiffbeforeafterboth--- a/tests/src/load_test_sc/metadata.json
+++ /dev/null
@@ -1,125 +0,0 @@
-{
- "metadataVersion": "0.1.0",
- "source": {
- "hash": "0x168cc3cba9657ad3950fb506e568751f99b90fb097685107f6101675662a8303",
- "language": "ink! 3.0.0-rc2",
- "compiler": "rustc 1.49.0-nightly"
- },
- "contract": {
- "name": "loadtester",
- "version": "0.1.0",
- "authors": [
- "[your_name] <[your_email]>"
- ]
- },
- "spec": {
- "constructors": [
- {
- "args": [],
- "docs": [],
- "name": [
- "new"
- ],
- "selector": "0xd183512b"
- }
- ],
- "docs": [],
- "events": [],
- "messages": [
- {
- "args": [
- {
- "name": "count",
- "type": {
- "displayName": [
- "u64"
- ],
- "type": 2
- }
- }
- ],
- "docs": [],
- "mutates": true,
- "name": [
- "bloat"
- ],
- "payable": false,
- "returnType": null,
- "selector": "0x49891c2a"
- },
- {
- "args": [],
- "docs": [],
- "mutates": false,
- "name": [
- "get"
- ],
- "payable": false,
- "returnType": {
- "displayName": [
- "u128"
- ],
- "type": 3
- },
- "selector": "0x1e5ca456"
- }
- ]
- },
- "storage": {
- "struct": {
- "fields": [
- {
- "layout": {
- "struct": {
- "fields": [
- {
- "layout": {
- "cell": {
- "key": "0x0000000000000000000000000000000000000000000000000000000000000000",
- "ty": 1
- }
- },
- "name": "len"
- },
- {
- "layout": {
- "array": {
- "cellsPerElem": 1,
- "layout": {
- "cell": {
- "key": "0x0000000001000000000000000000000000000000000000000000000000000000",
- "ty": 2
- }
- },
- "len": 4294967295,
- "offset": "0x0100000000000000000000000000000000000000000000000000000000000000"
- }
- },
- "name": "elems"
- }
- ]
- }
- },
- "name": "vector"
- }
- ]
- }
- },
- "types": [
- {
- "def": {
- "primitive": "u32"
- }
- },
- {
- "def": {
- "primitive": "u64"
- }
- },
- {
- "def": {
- "primitive": "u128"
- }
- }
- ]
-}
\ No newline at end of file
tests/src/nesting/migration-check.test.tsdiffbeforeafterboth--- a/tests/src/nesting/migration-check.test.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import {expect} from 'chai';
-import usingApi, {executeTransaction, submitTransactionAsync} from '../substrate/substrate-api';
-import {getCreateCollectionResult, getCreateItemResult, normalizeAccountId} from '../util/helpers';
-import {IKeyringPair} from '@polkadot/types/types';
-import {strToUTF16} from '../util/util';
-import waitNewBlocks from '../substrate/wait-new-blocks';
-// Used for polkadot-launch signalling
-import find from 'find-process';
-
-// todo un-skip for migrations
-// todo:playgrounds skipped, this one is outdated. Probably to be deleted/replaced.
-describe.skip('Migration testing: Properties', () => {
- let alice: IKeyringPair;
-
- before(async() => {
- await usingApi(async (_, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- });
- });
-
- it('Preserves collection settings after migration', async () => {
- let oldVersion: number;
- let collectionId: number;
- let collectionOld: any;
- let nftId: number;
- let nftOld: any;
-
- await usingApi(async api => {
- // ----------- Collection pre-upgrade ------------
- const txCollection = api.tx.unique.createCollectionEx({
- mode: 'NFT',
- access: 'AllowList',
- name: strToUTF16('Mojave Pictures'),
- description: strToUTF16('$2.2 billion power plant!'),
- tokenPrefix: '0x0002030',
- offchainSchema: '0x111111',
- schemaVersion: 'Unique',
- limits: {
- accountTokenOwnershipLimit: 3,
- },
- constOnChainSchema: '0x333333',
- variableOnChainSchema: '0x22222',
- });
- const events0 = await submitTransactionAsync(alice, txCollection);
- const result0 = getCreateCollectionResult(events0);
- collectionId = result0.collectionId;
-
- // Get the pre-upgrade collection info
- collectionOld = (await api.query.common.collectionById(collectionId)).toJSON();
-
- // ---------- NFT pre-upgrade ------------
- const txNft = api.tx.unique.createItem(
- collectionId,
- normalizeAccountId(alice),
- {
- NFT: {
- owner: {substrate: alice.address},
- constData: '0x0000',
- variableData: '0x1111',
- },
- },
- );
- const events1 = await executeTransaction(api, alice, txNft);
- const result1 = getCreateItemResult(events1);
- nftId = result1.itemId;
-
- // Get the pre-upgrade NFT data
- nftOld = (await api.query.nonfungible.tokenData(collectionId, nftId)).toJSON();
-
- // Get the pre-upgrade spec version
- oldVersion = (api.consts.system.version.toJSON() as any).specVersion;
- });
-
- console.log(`Now waiting for the parachain upgrade from ${oldVersion!}...`);
-
- let newVersion = oldVersion!;
- let connectionFailCounter = 0;
-
- // Cooperate with polkadot-launch if it's running (assuming custom name change to 'polkadot-launch'), and send a custom signal
- find('name', 'polkadot-launch', true).then((list) => {
- for (const proc of list) {
- process.kill(proc.pid, 'SIGUSR1');
- }
- });
-
- // And wait for the parachain upgrade
- {
- // Catch warnings like 'RPC methods not decorated' and keep the 'waiting' message in front
- const stdlog = console.warn.bind(console);
- let warnCount = 0;
- console.warn = function(...args){
- if (arguments.length <= 2 || !args[2].includes('RPC methods not decorated')) {
- warnCount++;
- stdlog.apply(console, args as any);
- }
- };
-
- let oldWarnCount = 0;
- while (newVersion == oldVersion! && connectionFailCounter < 5) {
- await new Promise(resolve => setTimeout(resolve, 12000));
- try {
- await usingApi(async api => {
- await waitNewBlocks(api);
- newVersion = (api.consts.system.version.toJSON() as any).specVersion;
- if (warnCount > oldWarnCount) {
- console.log(`Still waiting for the parachain upgrade from ${oldVersion!}...`);
- oldWarnCount = warnCount;
- }
- });
- } catch (_) {
- connectionFailCounter++;
- }
- }
- }
-
- await usingApi(async api => {
- // ---------- Collection comparison -----------
- const collectionNew = (await api.query.common.collectionById(collectionId)).toJSON() as any;
-
- // Make sure the extra fields are what they should be
- expect((
- await api.rpc.unique.collectionProperties(collectionId, ['_old_constOnChainSchema'])
- )[0].value.toHex()).to.be.equal(collectionOld.constOnChainSchema);
-
- expect((
- await api.rpc.unique.collectionProperties(collectionId, ['_old_variableOnChainSchema'])
- )[0].value.toHex()).to.be.equal(collectionOld.variableOnChainSchema);
-
- expect((
- await api.rpc.unique.collectionProperties(collectionId, ['_old_offchainSchema'])
- )[0].value.toHex()).to.be.equal(collectionOld.offchainSchema);
-
- expect((
- await api.rpc.unique.collectionProperties(collectionId, ['_old_schemaVersion'])
- )[0].value.toHuman()).to.be.equal(collectionOld.schemaVersion);
-
- expect(collectionNew.permissions).to.be.deep.equal({
- access: collectionOld.access,
- mintMode: collectionOld.mintMode,
- nesting: null,
- });
-
- expect(collectionNew.externalCollection).to.be.equal(false);
-
- // Get rid of extra fields to perform comparison on the rest of the collection
- delete collectionNew.permissions;
- delete collectionNew.externalCollection;
- delete collectionOld.schemaVersion;
- delete collectionOld.constOnChainSchema;
- delete collectionOld.variableOnChainSchema;
- delete collectionOld.offchainSchema;
- delete collectionOld.mintMode;
- delete collectionOld.access;
- delete collectionOld.metaUpdatePermission; // todo look into, doesn't migrate
-
- expect(collectionNew).to.be.deep.equal(collectionOld);
-
- // ---------- NFT comparison -----------
- const nftNew = (await api.query.nonfungible.tokenData(collectionId, nftId)).toJSON() as any;
-
- // Make sure the extra fields are what they should be
- expect((await api.rpc.unique.tokenProperties(collectionId, nftId, ['_old_constData']))[0].value.toHex()).to.be.equal(nftOld.constData);
-
- expect((await api.rpc.unique.tokenProperties(collectionId, nftId, ['_old_variableData']))[0].value.toHex()).to.be.equal(nftOld.variableData);
-
- // Get rid of extra fields to perform comparison on the rest of the NFT
- delete nftOld.constData;
- delete nftOld.variableData;
-
- expect(nftNew).to.be.deep.equal(nftOld);
- });
- });
-});
tests/src/nesting/properties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -276,7 +276,7 @@
itSub('Reads access rights to properties of a collection', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice);
- const propertyRights = (await helper.api!.query.common.collectionPropertyPermissions(collection.collectionId)).toJSON();
+ const propertyRights = (await helper.callRpc('api.query.common.collectionPropertyPermissions', [collection.collectionId])).toJSON();
expect(propertyRights).to.be.empty;
});
@@ -817,7 +817,7 @@
).to.be.fulfilled;
}
- const originalSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const originalSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
return originalSpace;
}
@@ -840,7 +840,7 @@
).to.be.rejectedWith(/common\.NoPermission/);
}
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -875,7 +875,7 @@
).to.be.rejectedWith(/common\.NoPermission/);
}
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -911,7 +911,7 @@
expect(await token.getProperties(['non-existent', 'now-existent'])).to.be.empty;
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -951,7 +951,7 @@
])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
expect(await token.getProperties(['a_holy_book', 'young_years'])).to.be.empty;
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
tests/src/overflow.test.tsdiffbeforeafterboth--- a/tests/src/overflow.test.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {IKeyringPair} from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import usingApi from './substrate/substrate-api';
-import {approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, getAllowance, getBalance, transferExpectFailure, transferExpectSuccess, transferFromExpectFail, transferFromExpectSuccess, U128_MAX} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-// todo:playgrounds skipped ~ postponed
-describe.skip('Integration Test fungible overflows', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
-
- before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- charlie = privateKeyWrapper('//Charlie');
- });
- });
-
- it('fails when overflows on transfer', async () => {
- await usingApi(async api => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
-
- await createFungibleItemExpectSuccess(alice, fungibleCollectionId, {Value: U128_MAX});
- await transferExpectSuccess(fungibleCollectionId, 0, alice, bob, U128_MAX, 'Fungible');
-
- await createFungibleItemExpectSuccess(alice, fungibleCollectionId, {Value: 1n});
- await transferExpectFailure(fungibleCollectionId, 0, alice, bob, 1);
-
- expect(await getBalance(api, fungibleCollectionId, alice.address, 0)).to.equal(1n);
- expect(await getBalance(api, fungibleCollectionId, bob.address, 0)).to.equal(U128_MAX);
- });
- });
-
- it('fails when overflows on transferFrom', async () => {
- await usingApi(async api => {
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- await createFungibleItemExpectSuccess(alice, fungibleCollectionId, {Value: U128_MAX});
- await approveExpectSuccess(fungibleCollectionId, 0, alice, bob.address, U128_MAX);
- await transferFromExpectSuccess(fungibleCollectionId, 0, bob, alice, charlie, U128_MAX, 'Fungible');
-
- expect(await getBalance(api, fungibleCollectionId, charlie.address, 0)).to.equal(U128_MAX);
- expect(await getAllowance(api, fungibleCollectionId, alice.address, bob.address, 0)).to.equal(0n);
-
- await createFungibleItemExpectSuccess(alice, fungibleCollectionId, {Value: U128_MAX});
- await approveExpectSuccess(fungibleCollectionId, 0, alice, bob.address, 1n);
- await transferFromExpectFail(fungibleCollectionId, 0, bob, alice, charlie, 1);
-
- expect(await getBalance(api, fungibleCollectionId, charlie.address, 0)).to.equal(U128_MAX);
- expect(await getAllowance(api, fungibleCollectionId, alice.address, bob.address, 0)).to.equal(1n);
- });
- });
-});
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -59,7 +59,7 @@
describe('Pallet presence', () => {
before(async () => {
await usingPlaygrounds(async helper => {
- const chain = await helper.api!.rpc.system.chain();
+ const chain = await helper.callRpc('api.rpc.system.chain', []);
const refungible = 'refungible';
const scheduler = 'scheduler';
tests/src/removeFromContractAllowList.test.tsdiffbeforeafterboth--- a/tests/src/removeFromContractAllowList.test.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import usingApi from './substrate/substrate-api';
-import {deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess} from './util/contracthelpers';
-import {addToContractAllowListExpectSuccess, isAllowlistedInContract, removeFromContractAllowListExpectFailure, removeFromContractAllowListExpectSuccess, toggleContractAllowlistExpectSuccess} from './util/helpers';
-import {IKeyringPair} from '@polkadot/types/types';
-import {expect} from 'chai';
-
-// todo:playgrounds skipped again
-describe.skip('Integration Test removeFromContractAllowList', () => {
- let bob: IKeyringPair;
-
- before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- bob = privateKeyWrapper('//Bob');
- });
- });
-
- it('user is no longer allowlisted after removal', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
-
- await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
-
- expect(await isAllowlistedInContract(flipper.address, bob.address)).to.be.false;
- });
- });
-
- it('user can\'t execute contract after removal', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
- await toggleContractAllowlistExpectSuccess(deployer, flipper.address.toString(), true);
-
- await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- await toggleFlipValueExpectSuccess(bob, flipper);
-
- await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- await toggleFlipValueExpectFailure(bob, flipper);
- });
- });
-
- it('can be called twice', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
-
- await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- });
- });
-});
-
-describe.skip('Negative Integration Test removeFromContractAllowList', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
-
- before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- });
- });
-
- it('fails when called with non-contract address', async () => {
- await usingApi(async () => {
- await removeFromContractAllowListExpectFailure(alice, alice.address, bob.address);
- });
- });
-
- it('fails when executed by non owner', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [flipper] = await deployFlipper(api, privateKeyWrapper);
-
- await removeFromContractAllowListExpectFailure(alice, flipper.address.toString(), bob.address);
- });
- });
-});
tests/src/rmrk/acceptNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/acceptNft.test.ts
+++ b/tests/src/rmrk/acceptNft.test.ts
@@ -8,7 +8,7 @@
} from './util/tx';
import {NftIdTuple} from './util/fetch';
import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
describe('integration test: accept NFT', () => {
let api: any;
tests/src/rmrk/addResource.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/addResource.test.ts
+++ b/tests/src/rmrk/addResource.test.ts
@@ -12,7 +12,7 @@
addNftComposableResource,
} from './util/tx';
import {RmrkTraitsResourceResourceInfo as ResourceInfo} from '@polkadot/types/lookup';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
describe('integration test: add NFT resource', () => {
const Alice = '//Alice';
tests/src/rmrk/addTheme.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/addTheme.test.ts
+++ b/tests/src/rmrk/addTheme.test.ts
@@ -3,7 +3,7 @@
import {createBase, addTheme} from './util/tx';
import {expectTxFailure} from './util/helpers';
import {getThemeNames} from './util/fetch';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
describe('integration test: add Theme to Base', () => {
let api: any;
tests/src/rmrk/burnNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/burnNft.test.ts
+++ b/tests/src/rmrk/burnNft.test.ts
@@ -5,7 +5,7 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
tests/src/rmrk/changeCollectionIssuer.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/changeCollectionIssuer.test.ts
+++ b/tests/src/rmrk/changeCollectionIssuer.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {
changeIssuer,
tests/src/rmrk/createBase.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/createBase.test.ts
+++ b/tests/src/rmrk/createBase.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {createCollection, createBase} from './util/tx';
describe('integration test: create new Base', () => {
tests/src/rmrk/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/createCollection.test.ts
+++ b/tests/src/rmrk/createCollection.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {createCollection} from './util/tx';
describe('Integration test: create new collection', () => {
tests/src/rmrk/deleteCollection.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/deleteCollection.test.ts
+++ b/tests/src/rmrk/deleteCollection.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, deleteCollection} from './util/tx';
tests/src/rmrk/equipNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/equipNft.test.ts
+++ b/tests/src/rmrk/equipNft.test.ts
@@ -1,7 +1,7 @@
import {ApiPromise} from '@polkadot/api';
import {expect} from 'chai';
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {getNft, getParts, NftIdTuple} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {
tests/src/rmrk/getOwnedNfts.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/getOwnedNfts.test.ts
+++ b/tests/src/rmrk/getOwnedNfts.test.ts
@@ -1,6 +1,6 @@
import {expect} from 'chai';
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {getOwnedNfts} from './util/fetch';
import {mintNft, createCollection} from './util/tx';
tests/src/rmrk/lockCollection.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/lockCollection.test.ts
+++ b/tests/src/rmrk/lockCollection.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, lockCollection, mintNft} from './util/tx';
tests/src/rmrk/mintNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/mintNft.test.ts
+++ b/tests/src/rmrk/mintNft.test.ts
@@ -1,6 +1,6 @@
import {expect} from 'chai';
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {getNft} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {createCollection, mintNft} from './util/tx';
tests/src/rmrk/rejectNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/rejectNft.test.ts
+++ b/tests/src/rmrk/rejectNft.test.ts
@@ -8,7 +8,7 @@
} from './util/tx';
import {getChildren, NftIdTuple} from './util/fetch';
import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
describe('integration test: reject NFT', () => {
let api: any;
tests/src/rmrk/removeResource.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/removeResource.test.ts
+++ b/tests/src/rmrk/removeResource.test.ts
@@ -1,7 +1,7 @@
import {expect} from 'chai';
import privateKey from '../substrate/privateKey';
import {executeTransaction, getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {getNft, NftIdTuple} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {
tests/src/rmrk/rmrkIsolation.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/rmrkIsolation.test.ts
+++ b/tests/src/rmrk/rmrkIsolation.test.ts
@@ -9,7 +9,7 @@
requirePallets,
normalizeAccountId,
Pallets,
-} from '../util/helpers';
+} from '../deprecated-helpers/helpers';
import {IKeyringPair} from '@polkadot/types/types';
import {ApiPromise} from '@polkadot/api';
import {it} from 'mocha';
tests/src/rmrk/sendNft.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/sendNft.test.ts
+++ b/tests/src/rmrk/sendNft.test.ts
@@ -3,7 +3,7 @@
import {createCollection, mintNft, sendNft} from './util/tx';
import {NftIdTuple} from './util/fetch';
import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
describe('integration test: send NFT', () => {
let api: any;
tests/src/rmrk/setCollectionProperty.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setCollectionProperty.test.ts
+++ b/tests/src/rmrk/setCollectionProperty.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, setPropertyCollection} from './util/tx';
tests/src/rmrk/setEquippableList.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setEquippableList.test.ts
+++ b/tests/src/rmrk/setEquippableList.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {createCollection, createBase, setEquippableList} from './util/tx';
tests/src/rmrk/setNftProperty.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setNftProperty.test.ts
+++ b/tests/src/rmrk/setNftProperty.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {NftIdTuple} from './util/fetch';
import {expectTxFailure} from './util/helpers';
import {createCollection, mintNft, sendNft, setNftProperty} from './util/tx';
tests/src/rmrk/setResourcePriorities.test.tsdiffbeforeafterboth--- a/tests/src/rmrk/setResourcePriorities.test.ts
+++ b/tests/src/rmrk/setResourcePriorities.test.ts
@@ -1,5 +1,5 @@
import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
import {expectTxFailure} from './util/helpers';
import {mintNft, createCollection, setResourcePriorities} from './util/tx';
tests/src/rpc.load.tsdiffbeforeafterboth--- a/tests/src/rpc.load.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import usingApi, {submitTransactionAsync} from './substrate/substrate-api';
-import {IKeyringPair} from '@polkadot/types/types';
-import {Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract} from '@polkadot/api-contract';
-import {ApiPromise, Keyring} from '@polkadot/api';
-import {findUnusedAddress} from './util/helpers';
-import fs from 'fs';
-
-const value = 0;
-const gasLimit = 500000n * 1000000n;
-const endowment = '1000000000000000';
-
-/*eslint no-async-promise-executor: "off"*/
-function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {
- return new Promise<Blueprint>(async (resolve) => {
- const unsub = await code
- .createBlueprint()
- .signAndSend(alice, (result) => {
- if (result.status.isInBlock || result.status.isFinalized) {
- // here we have an additional field in the result, containing the blueprint
- resolve(result.blueprint);
- unsub();
- }
- });
- });
-}
-
-/*eslint no-async-promise-executor: "off"*/
-function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {
- return new Promise<any>(async (resolve) => {
- const unsub = await blueprint.tx
- .new(endowment, gasLimit)
- .signAndSend(alice, (result) => {
- if (result.status.isInBlock || result.status.isFinalized) {
- unsub();
- resolve(result);
- }
- });
- });
-}
-
-async function prepareDeployer(api: ApiPromise, privateKeyWrapper: ((account: string) => IKeyringPair)) {
- // Find unused address
- const deployer = await findUnusedAddress(api, privateKeyWrapper);
-
- // Transfer balance to it
- const alice = privateKeyWrapper('//Alice');
- const amount = BigInt(endowment) + 10n**15n;
- const tx = api.tx.balances.transfer(deployer.address, amount);
- await submitTransactionAsync(alice, tx);
-
- return deployer;
-}
-
-async function deployLoadTester(api: ApiPromise, privateKeyWrapper: ((account: string) => IKeyringPair)): Promise<[Contract, IKeyringPair]> {
- const metadata = JSON.parse(fs.readFileSync('./src/load_test_sc/metadata.json').toString('utf-8'));
- const abi = new Abi(metadata);
-
- const deployer = await prepareDeployer(api, privateKeyWrapper);
-
- const wasm = fs.readFileSync('./src/load_test_sc/loadtester.wasm');
-
- const code = new CodePromise(api, abi, wasm);
-
- const blueprint = await deployBlueprint(deployer, code);
- const contract = (await deployContract(deployer, blueprint))['contract'] as Contract;
-
- return [contract, deployer];
-}
-
-async function getScData(contract: Contract, deployer: IKeyringPair) {
- const result = await contract.query.get(deployer.address, value, gasLimit);
-
- if(!result.result.isSuccess) {
- throw 'Failed to get value';
- }
- return result.result.asSuccess.data;
-}
-
-
-describe('RPC Tests', () => {
- it('Simple RPC Load Test', async () => {
- await usingApi(async api => {
- let count = 0;
- let hrTime = process.hrtime();
- let microsec1 = hrTime[0] * 1000000 + hrTime[1] / 1000;
- let rate = 0;
- const checkPoint = 1000;
-
- /* eslint no-constant-condition: "off" */
- while (true) {
- await api.rpc.system.chain();
- count++;
- process.stdout.write(`RPC reads: ${count} times at rate ${rate} r/s \r`);
-
- if (count % checkPoint == 0) {
- hrTime = process.hrtime();
- const microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;
- rate = 1000000*checkPoint/(microsec2 - microsec1);
- microsec1 = microsec2;
- }
- }
- });
- });
-
- it('Smart Contract RPC Load Test', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Deploy smart contract
- const [contract, deployer] = await deployLoadTester(api, privateKeyWrapper);
-
- // Fill smart contract up with data
- const bob = privateKeyWrapper('//Bob');
- const tx = contract.tx.bloat(value, gasLimit, 200);
- await submitTransactionAsync(bob, tx);
-
- // Run load test
- let count = 0;
- let hrTime = process.hrtime();
- let microsec1 = hrTime[0] * 1000000 + hrTime[1] / 1000;
- let rate = 0;
- const checkPoint = 10;
-
- /* eslint no-constant-condition: "off" */
- while (true) {
- await getScData(contract, deployer);
- count++;
- process.stdout.write(`SC reads: ${count} times at rate ${rate} r/s \r`);
-
- if (count % checkPoint == 0) {
- hrTime = process.hrtime();
- const microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;
- rate = 1000000*checkPoint/(microsec2 - microsec1);
- microsec1 = microsec2;
- }
- }
- });
- });
-
-});
tests/src/scheduler.test.tsdiffbeforeafterboth--- a/tests/src/scheduler.test.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import chai, {expect} from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {
- default as usingApi,
- submitTransactionAsync,
-} from './substrate/substrate-api';
-import {
- createItemExpectSuccess,
- createCollectionExpectSuccess,
- scheduleTransferExpectSuccess,
- scheduleTransferAndWaitExpectSuccess,
- setCollectionSponsorExpectSuccess,
- confirmSponsorshipExpectSuccess,
- findUnusedAddress,
- UNIQUE,
- enablePublicMintingExpectSuccess,
- addToAllowListExpectSuccess,
- waitNewBlocks,
- normalizeAccountId,
- getTokenOwner,
- getGenericResult,
- scheduleTransferFundsPeriodicExpectSuccess,
- getFreeBalance,
- confirmSponsorshipByKeyExpectSuccess,
- scheduleExpectFailure,
-} from './util/helpers';
-import {IKeyringPair} from '@polkadot/types/types';
-
-chai.use(chaiAsPromised);
-
-// todo:playgrounds skipped ~ postponed
-describe.skip('Scheduling token and balance transfers', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let scheduledIdBase: string;
- let scheduledIdSlider: number;
-
- before(async() => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- });
-
- scheduledIdBase = '0x' + '0'.repeat(31);
- scheduledIdSlider = 0;
- });
-
- // Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.
- function makeScheduledId(): string {
- return scheduledIdBase + ((scheduledIdSlider++) % 10);
- }
-
- it('Can schedule a transfer of an owned token with delay', async () => {
- await usingApi(async () => {
- const nftCollectionId = await createCollectionExpectSuccess();
- const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
- await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);
- await confirmSponsorshipExpectSuccess(nftCollectionId);
-
- await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4, makeScheduledId());
- });
- });
-
- it('Can transfer funds periodically', async () => {
- await usingApi(async () => {
- const waitForBlocks = 4;
- const period = 2;
- await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, makeScheduledId(), period, 2);
- const bobsBalanceBefore = await getFreeBalance(bob);
-
- // discounting already waited-for operations
- await waitNewBlocks(waitForBlocks - 2);
- const bobsBalanceAfterFirst = await getFreeBalance(bob);
- expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
-
- await waitNewBlocks(period);
- const bobsBalanceAfterSecond = await getFreeBalance(bob);
- expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst).to.be.true;
- });
- });
-
- it('Can sponsor scheduling a transaction', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
-
- await usingApi(async () => {
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
-
- const bobBalanceBefore = await getFreeBalance(bob);
- const waitForBlocks = 4;
- // no need to wait to check, fees must be deducted on scheduling, immediately
- await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());
- const bobBalanceAfter = await getFreeBalance(bob);
- // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
- expect(bobBalanceAfter < bobBalanceBefore).to.be.true;
- // wait for sequentiality matters
- await waitNewBlocks(waitForBlocks - 1);
- });
- });
-
- it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- // Find an empty, unused account
- const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
-
- const collectionId = await createCollectionExpectSuccess();
-
- // Add zeroBalance address to allow list
- await enablePublicMintingExpectSuccess(alice, collectionId);
- await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
-
- // Grace zeroBalance with money, enough to cover future transactions
- const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
- await submitTransactionAsync(alice, balanceTx);
-
- // Mint a fresh NFT
- const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
-
- // Schedule transfer of the NFT a few blocks ahead
- const waitForBlocks = 5;
- await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, makeScheduledId());
-
- // Get rid of the account's funds before the scheduled transaction takes place
- const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);
- const events = await submitTransactionAsync(zeroBalance, balanceTx2);
- expect(getGenericResult(events).success).to.be.true;
- /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
- const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);
- const events = await submitTransactionAsync(alice, sudoTx);
- expect(getGenericResult(events).success).to.be.true;*/
-
- // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
- await waitNewBlocks(waitForBlocks - 3);
-
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
- });
- });
-
- it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
- const collectionId = await createCollectionExpectSuccess();
-
- await usingApi(async (api, privateKeyWrapper) => {
- const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
- const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
- await submitTransactionAsync(alice, balanceTx);
-
- await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);
- await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);
-
- const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
-
- const waitForBlocks = 5;
- await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());
-
- const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
- const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
- const events = await submitTransactionAsync(alice, sudoTx);
- expect(getGenericResult(events).success).to.be.true;
-
- // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
- await waitNewBlocks(waitForBlocks - 3);
-
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
- });
- });
-
- it.skip('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
-
- await usingApi(async (api, privateKeyWrapper) => {
- const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
-
- await enablePublicMintingExpectSuccess(alice, collectionId);
- await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
-
- const bobBalanceBefore = await getFreeBalance(bob);
-
- const createData = {nft: {const_data: [], variable_data: []}};
- const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);
-
- /*const badTransaction = async function () {
- await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
- };
- await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/
-
- await scheduleExpectFailure(creationTx, zeroBalance, 3, makeScheduledId(), 1, 3);
-
- expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);
- });
- });
-});
tests/src/setChainLimits.test.tsdiffbeforeafterboth--- a/tests/src/setChainLimits.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {IKeyringPair} from '@polkadot/types/types';
-import usingApi from './substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- addCollectionAdminExpectSuccess,
- setChainLimitsExpectFailure,
- IChainLimits,
-} from './util/helpers';
-
-// todo:playgrounds skipped ~ postponed
-describe.skip('Negative Integration Test setChainLimits', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let dave: IKeyringPair;
- let limits: IChainLimits;
-
- before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- dave = privateKeyWrapper('//Dave');
- limits = {
- collectionNumbersLimit : 1,
- accountTokenOwnershipLimit: 1,
- collectionsAdminsLimit: 1,
- customDataLimit: 1,
- nftSponsorTransferTimeout: 1,
- fungibleSponsorTransferTimeout: 1,
- refungibleSponsorTransferTimeout: 1,
- };
- });
- });
-
- it('Collection owner cannot set chain limits', async () => {
- await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await setChainLimitsExpectFailure(alice, limits);
- });
-
- it('Collection admin cannot set chain limits', async () => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await setChainLimitsExpectFailure(bob, limits);
- });
-
- it('Regular user cannot set chain limits', async () => {
- await setChainLimitsExpectFailure(dave, limits);
- });
-});
tests/src/setContractSponsoringRateLimit.test.tsdiffbeforeafterboth--- a/tests/src/setContractSponsoringRateLimit.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {IKeyringPair} from '@polkadot/types/types';
-import usingApi from './substrate/substrate-api';
-import waitNewBlocks from './substrate/wait-new-blocks';
-import {deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess} from './util/contracthelpers';
-import {
- enableContractSponsoringExpectSuccess,
- findUnusedAddress,
- setContractSponsoringRateLimitExpectFailure,
- setContractSponsoringRateLimitExpectSuccess,
-} from './util/helpers';
-
-// todo:playgrounds skipped~postponed test
-describe.skip('Integration Test setContractSponsoringRateLimit', () => {
- it('ensure sponsored contract can\'t be called twice without pause for free', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const user = await findUnusedAddress(api, privateKeyWrapper);
-
- const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
- await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
- await setContractSponsoringRateLimitExpectSuccess(deployer, flipper.address, 10);
- await toggleFlipValueExpectSuccess(user, flipper);
- await toggleFlipValueExpectFailure(user, flipper);
- });
- });
-
- it('ensure sponsored contract can be called twice with pause for free', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const user = await findUnusedAddress(api, privateKeyWrapper);
-
- const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
- await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
- await setContractSponsoringRateLimitExpectSuccess(deployer, flipper.address, 1);
- await toggleFlipValueExpectSuccess(user, flipper);
- await waitNewBlocks(api, 1);
- await toggleFlipValueExpectSuccess(user, flipper);
- });
- });
-});
-
-describe.skip('Negative Integration Test setContractSponsoringRateLimit', () => {
- let alice: IKeyringPair;
-
- before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- });
- });
-
- it('fails when called for non-contract address', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const user = await findUnusedAddress(api, privateKeyWrapper);
-
- await setContractSponsoringRateLimitExpectFailure(alice, user.address, 1);
- });
- });
-
- it('fails when called by non-owning user', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [flipper] = await deployFlipper(api, privateKeyWrapper);
-
- await setContractSponsoringRateLimitExpectFailure(alice, flipper.address, 1);
- });
- });
-});
tests/src/substrate/get-balance.tsdiffbeforeafterboth--- a/tests/src/substrate/get-balance.ts
+++ b/tests/src/substrate/get-balance.ts
@@ -19,7 +19,7 @@
import promisifySubstrate from './promisify-substrate';
import {IKeyringPair} from '@polkadot/types/types';
import {submitTransactionAsync} from './substrate-api';
-import {getGenericResult} from '../util/helpers';
+import {getGenericResult} from '../deprecated-helpers/helpers';
import {expect} from 'chai';
export default async function getBalance(api: ApiPromise, accounts: string[]): Promise<Array<bigint>> {
tests/src/toggleContractAllowList.test.tsdiffbeforeafterboth--- a/tests/src/toggleContractAllowList.test.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import usingApi, {submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {
- deployFlipper,
- getFlipValue,
-} from './util/contracthelpers';
-import {
- getGenericResult,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-const value = 0;
-const gasLimit = 3000n * 1000000n;
-
-// todo:playgrounds skipped ~ postpone
-describe.skip('Integration Test toggleContractAllowList', () => {
-
- it('Enable allow list contract mode', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
-
- const enabledBefore = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
- const enableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, true);
- const enableEvents = await submitTransactionAsync(deployer, enableAllowListTx);
- const enabled = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
-
- expect(getGenericResult(enableEvents).success).to.be.true;
- expect(enabledBefore).to.be.false;
- expect(enabled).to.be.true;
- });
- });
-
- it('Only allowlisted account can call contract', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const bob = privateKeyWrapper('//Bob');
-
- const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
-
- let flipValueBefore = await getFlipValue(contract, deployer);
- const flip = contract.tx.flip({value, gasLimit});
- await submitTransactionAsync(bob, flip);
- const flipValueAfter = await getFlipValue(contract,deployer);
- expect(flipValueAfter).to.be.eq(!flipValueBefore, 'Anyone can call new contract.');
-
- const deployerCanFlip = async () => {
- const flipValueBefore = await getFlipValue(contract, deployer);
- const deployerFlip = contract.tx.flip({value, gasLimit});
- await submitTransactionAsync(deployer, deployerFlip);
- const aliceFlip1Response = await getFlipValue(contract, deployer);
- expect(aliceFlip1Response).to.be.eq(!flipValueBefore, 'Deployer always can flip.');
- };
- await deployerCanFlip();
-
- flipValueBefore = await getFlipValue(contract, deployer);
- const enableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, true);
- await submitTransactionAsync(deployer, enableAllowListTx);
- const flipWithEnabledAllowList = contract.tx.flip({value, gasLimit});
- await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledAllowList)).to.be.rejected;
- const flipValueAfterEnableAllowList = await getFlipValue(contract, deployer);
- expect(flipValueAfterEnableAllowList).to.be.eq(flipValueBefore, 'Enabling allowlist doesn\'t make it possible to call contract for everyone.');
-
- await deployerCanFlip();
-
- flipValueBefore = await getFlipValue(contract, deployer);
- const addBobToAllowListTx = api.tx.unique.addToContractAllowList(contract.address, bob.address);
- await submitTransactionAsync(deployer, addBobToAllowListTx);
- const flipWithAllowlistedBob = contract.tx.flip({value, gasLimit});
- await submitTransactionAsync(bob, flipWithAllowlistedBob);
- const flipAfterAllowListed = await getFlipValue(contract,deployer);
- expect(flipAfterAllowListed).to.be.eq(!flipValueBefore, 'Bob was allowlisted, now he can flip.');
-
- await deployerCanFlip();
-
- flipValueBefore = await getFlipValue(contract, deployer);
- const removeBobFromAllowListTx = api.tx.unique.removeFromContractAllowList(contract.address, bob.address);
- await submitTransactionAsync(deployer, removeBobFromAllowListTx);
- const bobRemoved = contract.tx.flip({value, gasLimit});
- await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;
- const afterBobRemoved = await getFlipValue(contract, deployer);
- expect(afterBobRemoved).to.be.eq(flipValueBefore, 'Bob can\'t call contract, now when he is removeed from allow list.');
-
- await deployerCanFlip();
-
- flipValueBefore = await getFlipValue(contract, deployer);
- const disableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, false);
- await submitTransactionAsync(deployer, disableAllowListTx);
- const allowListDisabledFlip = contract.tx.flip({value, gasLimit});
- await submitTransactionAsync(bob, allowListDisabledFlip);
- const afterAllowListDisabled = await getFlipValue(contract,deployer);
- expect(afterAllowListDisabled).to.be.eq(!flipValueBefore, 'Anyone can call contract with disabled allowlist.');
-
- });
- });
-
- it('Enabling allow list repeatedly should not produce errors', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
-
- const enabledBefore = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
- const enableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, true);
- const enableEvents = await submitTransactionAsync(deployer, enableAllowListTx);
- const enabled = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
- const enableAgainEvents = await submitTransactionAsync(deployer, enableAllowListTx);
- const enabledAgain = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
-
- expect(getGenericResult(enableEvents).success).to.be.true;
- expect(enabledBefore).to.be.false;
- expect(enabled).to.be.true;
- expect(getGenericResult(enableAgainEvents).success).to.be.true;
- expect(enabledAgain).to.be.true;
- });
- });
-
-});
-
-describe.skip('Negative Integration Test toggleContractAllowList', () => {
-
- it('Enable allow list for a non-contract', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const alice = privateKeyWrapper('//Alice');
- const bobGuineaPig = privateKeyWrapper('//Bob');
-
- const enabledBefore = (await api.query.unique.contractAllowListEnabled(bobGuineaPig.address)).toJSON();
- const enableAllowListTx = api.tx.unique.toggleContractAllowList(bobGuineaPig.address, true);
- await expect(submitTransactionExpectFailAsync(alice, enableAllowListTx)).to.be.rejected;
- const enabled = (await api.query.unique.contractAllowListEnabled(bobGuineaPig.address)).toJSON();
-
- expect(enabledBefore).to.be.false;
- expect(enabled).to.be.false;
- });
- });
-
- it('Enable allow list using a non-owner address', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- const bob = privateKeyWrapper('//Bob');
- const [contract] = await deployFlipper(api, privateKeyWrapper);
-
- const enabledBefore = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
- const enableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, true);
- await expect(submitTransactionExpectFailAsync(bob, enableAllowListTx)).to.be.rejected;
- const enabled = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
-
- expect(enabledBefore).to.be.false;
- expect(enabled).to.be.false;
- });
- });
-
-});
tests/src/transfer.nload.tsdiffbeforeafterboth--- a/tests/src/transfer.nload.ts
+++ b/tests/src/transfer.nload.ts
@@ -18,10 +18,24 @@
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {submitTransactionAsync} from './substrate/substrate-api';
import waitNewBlocks from './substrate/wait-new-blocks';
-import {findUnusedAddresses} from './util/helpers';
import * as cluster from 'cluster';
import os from 'os';
+async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {
+ let bal = 0n;
+ let unused;
+ do {
+ const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;
+ unused = privateKeyWrapper(`//${randomSeed}`);
+ bal = (await api.query.system.account(unused.address)).data.free.toBigInt();
+ } while (bal !== 0n);
+ return unused;
+}
+
+function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {
+ return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));
+}
+
// Innacurate transfer fee
const FEE = 10n ** 8n;
tests/src/transfer_contract/metadata.jsondiffbeforeafterboth--- a/tests/src/transfer_contract/metadata.json
+++ /dev/null
@@ -1,469 +0,0 @@
-{
- "metadataVersion": "0.1.0",
- "source": {
- "hash": "0xc6c3f47adeafe86d1674ed72c7179605787842f2f05a2d7da0dbabf3c4fa1aa8",
- "language": "ink! 3.0.0-rc3",
- "compiler": "rustc 1.52.0-nightly"
- },
- "contract": {
- "name": "nft_transfer",
- "version": "0.1.0",
- "authors": [
- "[Greg Zaitsev] <[your_email]>"
- ]
- },
- "spec": {
- "constructors": [
- {
- "args": [],
- "docs": [
- "Default Constructor",
- "",
- "Constructors can delegate to other constructors."
- ],
- "name": [
- "default"
- ],
- "selector": "0xed4b9d1b"
- }
- ],
- "docs": [],
- "events": [],
- "messages": [
- {
- "args": [
- {
- "name": "recipient",
- "type": {
- "displayName": [
- "AccountId"
- ],
- "type": 1
- }
- },
- {
- "name": "collection_id",
- "type": {
- "displayName": [
- "u32"
- ],
- "type": 4
- }
- },
- {
- "name": "token_id",
- "type": {
- "displayName": [
- "u32"
- ],
- "type": 4
- }
- },
- {
- "name": "amount",
- "type": {
- "displayName": [
- "u128"
- ],
- "type": 5
- }
- }
- ],
- "docs": [
- " Transfer one NFT token"
- ],
- "mutates": true,
- "name": [
- "transfer"
- ],
- "payable": false,
- "returnType": null,
- "selector": "0x84a15da1"
- },
- {
- "args": [
- {
- "name": "recipient",
- "type": {
- "displayName": [
- "AccountId"
- ],
- "type": 1
- }
- },
- {
- "name": "collection_id",
- "type": {
- "displayName": [
- "u32"
- ],
- "type": 4
- }
- },
- {
- "name": "data",
- "type": {
- "displayName": [
- "CreateItemData"
- ],
- "type": 6
- }
- }
- ],
- "docs": [],
- "mutates": true,
- "name": [
- "create_item"
- ],
- "payable": false,
- "returnType": null,
- "selector": "0xd7c3f083"
- },
- {
- "args": [
- {
- "name": "owner",
- "type": {
- "displayName": [
- "AccountId"
- ],
- "type": 1
- }
- },
- {
- "name": "collection_id",
- "type": {
- "displayName": [
- "u32"
- ],
- "type": 4
- }
- },
- {
- "name": "data",
- "type": {
- "displayName": [
- "Vec"
- ],
- "type": 8
- }
- }
- ],
- "docs": [],
- "mutates": true,
- "name": [
- "create_multiple_items"
- ],
- "payable": false,
- "returnType": null,
- "selector": "0x15f9a1eb"
- },
- {
- "args": [
- {
- "name": "spender",
- "type": {
- "displayName": [
- "AccountId"
- ],
- "type": 1
- }
- },
- {
- "name": "collection_id",
- "type": {
- "displayName": [
- "u32"
- ],
- "type": 4
- }
- },
- {
- "name": "item_id",
- "type": {
- "displayName": [
- "u32"
- ],
- "type": 4
- }
- },
- {
- "name": "amount",
- "type": {
- "displayName": [
- "u128"
- ],
- "type": 5
- }
- }
- ],
- "docs": [],
- "mutates": true,
- "name": [
- "approve"
- ],
- "payable": false,
- "returnType": null,
- "selector": "0x681266a0"
- },
- {
- "args": [
- {
- "name": "owner",
- "type": {
- "displayName": [
- "AccountId"
- ],
- "type": 1
- }
- },
- {
- "name": "recipient",
- "type": {
- "displayName": [
- "AccountId"
- ],
- "type": 1
- }
- },
- {
- "name": "collection_id",
- "type": {
- "displayName": [
- "u32"
- ],
- "type": 4
- }
- },
- {
- "name": "item_id",
- "type": {
- "displayName": [
- "u32"
- ],
- "type": 4
- }
- },
- {
- "name": "amount",
- "type": {
- "displayName": [
- "u128"
- ],
- "type": 5
- }
- }
- ],
- "docs": [],
- "mutates": true,
- "name": [
- "transfer_from"
- ],
- "payable": false,
- "returnType": null,
- "selector": "0x0b396f18"
- },
- {
- "args": [
- {
- "name": "collection_id",
- "type": {
- "displayName": [
- "u32"
- ],
- "type": 4
- }
- },
- {
- "name": "item_id",
- "type": {
- "displayName": [
- "u32"
- ],
- "type": 4
- }
- },
- {
- "name": "data",
- "type": {
- "displayName": [
- "Vec"
- ],
- "type": 7
- }
- }
- ],
- "docs": [],
- "mutates": true,
- "name": [
- "set_variable_meta_data"
- ],
- "payable": false,
- "returnType": null,
- "selector": "0xb0b26da2"
- },
- {
- "args": [
- {
- "name": "collection_id",
- "type": {
- "displayName": [
- "u32"
- ],
- "type": 4
- }
- },
- {
- "name": "address",
- "type": {
- "displayName": [
- "AccountId"
- ],
- "type": 1
- }
- },
- {
- "name": "allowlisted",
- "type": {
- "displayName": [
- "bool"
- ],
- "type": 9
- }
- }
- ],
- "docs": [],
- "mutates": true,
- "name": [
- "toggle_allow_list"
- ],
- "payable": false,
- "returnType": null,
- "selector": "0x98574dac"
- }
- ]
- },
- "storage": {
- "struct": {
- "fields": []
- }
- },
- "types": [
- {
- "def": {
- "composite": {
- "fields": [
- {
- "type": 2,
- "typeName": "[u8; 32]"
- }
- ]
- }
- },
- "path": [
- "ink_env",
- "types",
- "AccountId"
- ]
- },
- {
- "def": {
- "array": {
- "len": 32,
- "type": 3
- }
- }
- },
- {
- "def": {
- "primitive": "u8"
- }
- },
- {
- "def": {
- "primitive": "u32"
- }
- },
- {
- "def": {
- "primitive": "u128"
- }
- },
- {
- "def": {
- "variant": {
- "variants": [
- {
- "fields": [
- {
- "name": "const_data",
- "type": 7,
- "typeName": "Vec<u8>"
- },
- {
- "name": "variable_data",
- "type": 7,
- "typeName": "Vec<u8>"
- }
- ],
- "name": "Nft"
- },
- {
- "fields": [
- {
- "name": "value",
- "type": 5,
- "typeName": "u128"
- }
- ],
- "name": "Fungible"
- },
- {
- "fields": [
- {
- "name": "const_data",
- "type": 7,
- "typeName": "Vec<u8>"
- },
- {
- "name": "variable_data",
- "type": 7,
- "typeName": "Vec<u8>"
- },
- {
- "name": "pieces",
- "type": 5,
- "typeName": "u128"
- }
- ],
- "name": "ReFungible"
- }
- ]
- }
- },
- "path": [
- "nft_transfer",
- "CreateItemData"
- ]
- },
- {
- "def": {
- "sequence": {
- "type": 3
- }
- }
- },
- {
- "def": {
- "sequence": {
- "type": 6
- }
- }
- },
- {
- "def": {
- "primitive": "bool"
- }
- }
- ]
-}
\ No newline at end of file
tests/src/transfer_contract/nft_transfer.wasmdiffbeforeafterbothbinary blob — no preview
tests/src/tx-version-presence.test.tsdiffbeforeafterboth--- a/tests/src/tx-version-presence.test.ts
+++ b/tests/src/tx-version-presence.test.ts
@@ -22,7 +22,7 @@
describe('TxVersion is present', () => {
before(async () => {
await usingPlaygrounds(async helper => {
- metadata = await helper.api!.rpc.state.getMetadata();
+ metadata = await helper.callRpc('api.rpc.state.getMetadata', []);
});
});
tests/src/util/contracthelpers.tsdiffbeforeafterboth--- a/tests/src/util/contracthelpers.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
-import fs from 'fs';
-import {Abi, CodePromise, ContractPromise as Contract} from '@polkadot/api-contract';
-import {IKeyringPair} from '@polkadot/types/types';
-import {ApiPromise} from '@polkadot/api';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-import {findUnusedAddress, getGenericResult} from '../util/helpers';
-
-const value = 0;
-const gasLimit = '200000000000';
-const endowment = '100000000000000000';
-
-/* eslint no-async-promise-executor: "off" */
-function deployContract(alice: IKeyringPair, code: CodePromise, constructor = 'default', ...args: any[]): Promise<Contract> {
- return new Promise<Contract>(async (resolve) => {
- const unsub = await (code as any)
- .tx[constructor]({value: endowment, gasLimit}, ...args)
- .signAndSend(alice, (result: any) => {
- if (result.status.isInBlock || result.status.isFinalized) {
- // here we have an additional field in the result, containing the blueprint
- resolve((result as any).contract);
- unsub();
- }
- });
- });
-}
-
-async function prepareDeployer(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) {
- // Find unused address
- const deployer = await findUnusedAddress(api, privateKeyWrapper);
-
- // Transfer balance to it
- const alice = privateKeyWrapper('//Alice');
- const amount = BigInt(endowment) + 10n**15n;
- const tx = api.tx.balances.transfer(deployer.address, amount);
- await submitTransactionAsync(alice, tx);
-
- return deployer;
-}
-
-export async function deployFlipper(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
- const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));
- const abi = new Abi(metadata);
-
- const deployer = await prepareDeployer(api, privateKeyWrapper);
-
- const wasm = fs.readFileSync('./src/flipper/flipper.wasm');
-
- const code = new CodePromise(api, abi, wasm);
-
- const contract = (await deployContract(deployer, code, 'new', true)) as Contract;
-
- const initialGetResponse = await getFlipValue(contract, deployer);
- expect(initialGetResponse).to.be.true;
-
- return [contract, deployer];
-}
-
-export async function getFlipValue(contract: Contract, deployer: IKeyringPair) {
- const result = await contract.query.get(deployer.address, {value, gasLimit});
-
- if(!result.result.isOk) {
- throw 'Failed to get flipper value';
- }
- return (result.result.asOk.data[0] == 0x00) ? false : true;
-}
-
-export async function toggleFlipValueExpectSuccess(sender: IKeyringPair, contract: Contract) {
- const tx = contract.tx.flip({value, gasLimit});
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
-}
-
-export async function toggleFlipValueExpectFailure(sender: IKeyringPair, contract: Contract) {
- const tx = contract.tx.flip({value, gasLimit});
- await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-}
-
-export async function deployTransferContract(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
- const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));
- const abi = new Abi(metadata);
-
- const deployer = await prepareDeployer(api, privateKeyWrapper);
-
- const wasm = fs.readFileSync('./src/transfer_contract/nft_transfer.wasm');
-
- const code = new CodePromise(api, abi, wasm);
-
- const contract = await deployContract(deployer, code);
-
- return [contract, deployer];
-}
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ /dev/null
@@ -1,1879 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import '../interfaces/augment-api-rpc';
-import '../interfaces/augment-api-query';
-import {ApiPromise, Keyring} from '@polkadot/api';
-import type {AccountId, EventRecord, Event, BlockNumber} from '@polkadot/types/interfaces';
-import type {GenericEventData} from '@polkadot/types';
-import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';
-import {evmToAddress} from '@polkadot/util-crypto';
-import {AnyNumber} from '@polkadot/types-codec/types';
-import BN from 'bn.js';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
-import {hexToStr, strToUTF16, utf16ToStr} from './util';
-import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';
-import {UpDataStructsTokenChild} from '../interfaces';
-import {Context} from 'mocha';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-export type CrossAccountId = {
- Substrate: string,
-} | {
- Ethereum: string,
-};
-
-
-export enum Pallets {
- Inflation = 'inflation',
- RmrkCore = 'rmrkcore',
- RmrkEquip = 'rmrkequip',
- ReFungible = 'refungible',
- Fungible = 'fungible',
- NFT = 'nonfungible',
- Scheduler = 'scheduler',
- AppPromotion = 'apppromotion',
-}
-
-export async function isUnique(): Promise<boolean> {
- return usingApi(async api => {
- const chain = await api.rpc.system.chain();
-
- return chain.eq('UNIQUE');
- });
-}
-
-export async function isQuartz(): Promise<boolean> {
- return usingApi(async api => {
- const chain = await api.rpc.system.chain();
-
- return chain.eq('QUARTZ');
- });
-}
-
-let modulesNames: any;
-export function getModuleNames(api: ApiPromise): string[] {
- if (typeof modulesNames === 'undefined')
- modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());
- return modulesNames;
-}
-
-export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {
- return await usingApi(async api => {
- const pallets = getModuleNames(api);
-
- return requiredPallets.filter(p => !pallets.includes(p));
- });
-}
-
-export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {
- return (await missingRequiredPallets(requiredPallets)).length == 0;
-}
-
-export async function requirePallets(mocha: Context, requiredPallets: string[]) {
- const missingPallets = await missingRequiredPallets(requiredPallets);
-
- if (missingPallets.length > 0) {
- const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;
- const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;
- const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;
-
- console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);
-
- mocha.skip();
- }
-}
-
-export function bigIntToSub(api: ApiPromise, number: bigint) {
- return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();
-}
-
-export function bigIntToDecimals(number: bigint, decimals = 18): string {
- const numberStr = number.toString();
- const dotPos = numberStr.length - decimals;
-
- if (dotPos <= 0) {
- return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;
- } else {
- const intPart = numberStr.substring(0, dotPos);
- const fractPart = numberStr.substring(dotPos);
- return intPart + '.' + fractPart;
- }
-}
-
-export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {
- if (typeof input === 'string') {
- if (input.length >= 47) {
- return {Substrate: input};
- } else if (input.length === 42 && input.startsWith('0x')) {
- return {Ethereum: input.toLowerCase()};
- } else if (input.length === 40 && !input.startsWith('0x')) {
- return {Ethereum: '0x' + input.toLowerCase()};
- } else {
- throw new Error(`Unknown address format: "${input}"`);
- }
- }
- if ('address' in input) {
- return {Substrate: input.address};
- }
- if ('Ethereum' in input) {
- return {
- Ethereum: input.Ethereum.toLowerCase(),
- };
- } else if ('ethereum' in input) {
- return {
- Ethereum: (input as any).ethereum.toLowerCase(),
- };
- } else if ('Substrate' in input) {
- return input;
- } else if ('substrate' in input) {
- return {
- Substrate: (input as any).substrate,
- };
- }
-
- // AccountId
- return {Substrate: input.toString()};
-}
-export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {
- input = normalizeAccountId(input);
- if ('Substrate' in input) {
- return input.Substrate;
- } else {
- return evmToAddress(input.Ethereum);
- }
-}
-
-export const U128_MAX = (1n << 128n) - 1n;
-
-const MICROUNIQUE = 1_000_000_000_000n;
-const MILLIUNIQUE = 1_000n * MICROUNIQUE;
-const CENTIUNIQUE = 10n * MILLIUNIQUE;
-export const UNIQUE = 100n * CENTIUNIQUE;
-
-interface GenericResult<T> {
- success: boolean;
- data: T | null;
-}
-
-interface CreateCollectionResult {
- success: boolean;
- collectionId: number;
-}
-
-interface CreateItemResult {
- success: boolean;
- collectionId: number;
- itemId: number;
- recipient?: CrossAccountId;
- amount?: number;
-}
-
-interface DestroyItemResult {
- success: boolean;
- collectionId: number;
- itemId: number;
- owner: CrossAccountId;
- amount: number;
-}
-
-interface TransferResult {
- collectionId: number;
- itemId: number;
- sender?: CrossAccountId;
- recipient?: CrossAccountId;
- value: bigint;
-}
-
-interface IReFungibleOwner {
- fraction: BN;
- owner: number[];
-}
-
-interface IGetMessage {
- checkMsgUnqMethod: string;
- checkMsgTrsMethod: string;
- checkMsgSysMethod: string;
-}
-
-export interface IFungibleTokenDataType {
- value: number;
-}
-
-export interface IChainLimits {
- collectionNumbersLimit: number;
- accountTokenOwnershipLimit: number;
- collectionsAdminsLimit: number;
- customDataLimit: number;
- nftSponsorTransferTimeout: number;
- fungibleSponsorTransferTimeout: number;
- refungibleSponsorTransferTimeout: number;
- //offchainSchemaLimit: number;
- //constOnChainSchemaLimit: number;
-}
-
-export interface IReFungibleTokenDataType {
- owner: IReFungibleOwner[];
-}
-
-export function uniqueEventMessage(events: EventRecord[]): IGetMessage {
- let checkMsgUnqMethod = '';
- let checkMsgTrsMethod = '';
- let checkMsgSysMethod = '';
- events.forEach(({event: {method, section}}) => {
- if (section === 'common') {
- checkMsgUnqMethod = method;
- } else if (section === 'treasury') {
- checkMsgTrsMethod = method;
- } else if (section === 'system') {
- checkMsgSysMethod = method;
- } else { return null; }
- });
- const result: IGetMessage = {
- checkMsgUnqMethod,
- checkMsgTrsMethod,
- checkMsgSysMethod,
- };
- return result;
-}
-
-export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {
- const event = events.find(r => check(r.event));
- if (!event) return;
- return event.event as T;
-}
-
-export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;
-export function getGenericResult<T>(
- events: EventRecord[],
- expectSection: string,
- expectMethod: string,
- extractAction: (data: GenericEventData) => T
-): GenericResult<T>;
-
-export function getGenericResult<T>(
- events: EventRecord[],
- expectSection?: string,
- expectMethod?: string,
- extractAction?: (data: GenericEventData) => T,
-): GenericResult<T> {
- let success = false;
- let successData = null;
-
- events.forEach(({event: {data, method, section}}) => {
- // console.log(` ${phase}: ${section}.${method}:: ${data}`);
- if (method === 'ExtrinsicSuccess') {
- success = true;
- } else if ((expectSection == section) && (expectMethod == method)) {
- successData = extractAction!(data as any);
- }
- });
-
- const result: GenericResult<T> = {
- success,
- data: successData,
- };
- return result;
-}
-
-export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {
- const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));
- const result: CreateCollectionResult = {
- success: genericResult.success,
- collectionId: genericResult.data ?? 0,
- };
- return result;
-}
-
-export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {
- const results: CreateItemResult[] = [];
-
- const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {
- const collectionId = parseInt(data[0].toString(), 10);
- const itemId = parseInt(data[1].toString(), 10);
- const recipient = normalizeAccountId(data[2].toJSON() as any);
- const amount = parseInt(data[3].toString(), 10);
-
- const itemRes: CreateItemResult = {
- success: true,
- collectionId,
- itemId,
- recipient,
- amount,
- };
-
- results.push(itemRes);
- return results;
- });
-
- if (!genericResult.success) return [];
- return results;
-}
-
-export function getCreateItemResult(events: EventRecord[]): CreateItemResult {
- const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));
-
- if (genericResult.data == null)
- return {
- success: genericResult.success,
- collectionId: 0,
- itemId: 0,
- amount: 0,
- };
- else
- return {
- success: genericResult.success,
- collectionId: genericResult.data[0] as number,
- itemId: genericResult.data[1] as number,
- recipient: normalizeAccountId(genericResult.data![2] as any),
- amount: genericResult.data[3] as number,
- };
-}
-
-export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {
- const results: DestroyItemResult[] = [];
-
- const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {
- const collectionId = parseInt(data[0].toString(), 10);
- const itemId = parseInt(data[1].toString(), 10);
- const owner = normalizeAccountId(data[2].toJSON() as any);
- const amount = parseInt(data[3].toString(), 10);
-
- const itemRes: DestroyItemResult = {
- success: true,
- collectionId,
- itemId,
- owner,
- amount,
- };
-
- results.push(itemRes);
- return results;
- });
-
- if (!genericResult.success) return [];
- return results;
-}
-
-export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {
- for (const {event} of events) {
- if (api.events.common.Transfer.is(event)) {
- const [collection, token, sender, recipient, value] = event.data;
- return {
- collectionId: collection.toNumber(),
- itemId: token.toNumber(),
- sender: normalizeAccountId(sender.toJSON() as any),
- recipient: normalizeAccountId(recipient.toJSON() as any),
- value: value.toBigInt(),
- };
- }
- }
- throw new Error('no transfer event');
-}
-
-interface Nft {
- type: 'NFT';
-}
-
-interface Fungible {
- type: 'Fungible';
- decimalPoints: number;
-}
-
-interface ReFungible {
- type: 'ReFungible';
-}
-
-export type CollectionMode = Nft | Fungible | ReFungible;
-
-export type Property = {
- key: any,
- value: any,
-};
-
-type Permission = {
- mutable: boolean;
- collectionAdmin: boolean;
- tokenOwner: boolean;
-}
-
-type PropertyPermission = {
- key: any;
- permission: Permission;
-}
-
-export type CreateCollectionParams = {
- mode: CollectionMode,
- name: string,
- description: string,
- tokenPrefix: string,
- properties?: Array<Property>,
- propPerm?: Array<PropertyPermission>
-};
-
-const defaultCreateCollectionParams: CreateCollectionParams = {
- description: 'description',
- mode: {type: 'NFT'},
- name: 'name',
- tokenPrefix: 'prefix',
-};
-
-export async function
-createCollection(
- api: ApiPromise,
- sender: IKeyringPair,
- params: Partial<CreateCollectionParams> = {},
-): Promise<CreateCollectionResult> {
- const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
- let modeprm = {};
- if (mode.type === 'NFT') {
- modeprm = {nft: null};
- } else if (mode.type === 'Fungible') {
- modeprm = {fungible: mode.decimalPoints};
- } else if (mode.type === 'ReFungible') {
- modeprm = {refungible: null};
- }
-
- const tx = api.tx.unique.createCollectionEx({
- name: strToUTF16(name),
- description: strToUTF16(description),
- tokenPrefix: strToUTF16(tokenPrefix),
- mode: modeprm as any,
- });
- const events = await executeTransaction(api, sender, tx);
- return getCreateCollectionResult(events);
-}
-
-export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
- const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
- let collectionId = 0;
- await usingApi(async (api, privateKeyWrapper) => {
- // Get number of collections before the transaction
- const collectionCountBefore = await getCreatedCollectionCount(api);
-
- // Run the CreateCollection transaction
- const alicePrivateKey = privateKeyWrapper('//Alice');
-
- const result = await createCollection(api, alicePrivateKey, params);
-
- // Get number of collections after the transaction
- const collectionCountAfter = await getCreatedCollectionCount(api);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, result.collectionId);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- expect(result.collectionId).to.be.equal(collectionCountAfter);
- // tslint:disable-next-line:no-unused-expression
- expect(collection).to.be.not.null;
- expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');
- expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));
- expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);
- expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);
- expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);
-
- collectionId = result.collectionId;
- });
-
- return collectionId;
-}
-
-export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
- const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
- let collectionId = 0;
- await usingApi(async (api, privateKeyWrapper) => {
- // Get number of collections before the transaction
- const collectionCountBefore = await getCreatedCollectionCount(api);
-
- // Run the CreateCollection transaction
- const alicePrivateKey = privateKeyWrapper('//Alice');
-
- let modeprm = {};
- if (mode.type === 'NFT') {
- modeprm = {nft: null};
- } else if (mode.type === 'Fungible') {
- modeprm = {fungible: mode.decimalPoints};
- } else if (mode.type === 'ReFungible') {
- modeprm = {refungible: null};
- }
-
- const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});
- const events = await submitTransactionAsync(alicePrivateKey, tx);
- const result = getCreateCollectionResult(events);
-
- // Get number of collections after the transaction
- const collectionCountAfter = await getCreatedCollectionCount(api);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, result.collectionId);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- expect(result.collectionId).to.be.equal(collectionCountAfter);
- // tslint:disable-next-line:no-unused-expression
- expect(collection).to.be.not.null;
- expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');
- expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));
- expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);
- expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);
- expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);
-
-
- collectionId = result.collectionId;
- });
-
- return collectionId;
-}
-
-export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {
- const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
- await usingApi(async (api, privateKeyWrapper) => {
- // Get number of collections before the transaction
- const collectionCountBefore = await getCreatedCollectionCount(api);
-
- // Run the CreateCollection transaction
- const alicePrivateKey = privateKeyWrapper('//Alice');
-
- let modeprm = {};
- if (mode.type === 'NFT') {
- modeprm = {nft: null};
- } else if (mode.type === 'Fungible') {
- modeprm = {fungible: mode.decimalPoints};
- } else if (mode.type === 'ReFungible') {
- modeprm = {refungible: null};
- }
-
- const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});
- await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
-
-
- // Get number of collections after the transaction
- const collectionCountAfter = await getCreatedCollectionCount(api);
-
- expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
- });
-}
-
-export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {
- const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
- let modeprm = {};
- if (mode.type === 'NFT') {
- modeprm = {nft: null};
- } else if (mode.type === 'Fungible') {
- modeprm = {fungible: mode.decimalPoints};
- } else if (mode.type === 'ReFungible') {
- modeprm = {refungible: null};
- }
-
- await usingApi(async (api, privateKeyWrapper) => {
- // Get number of collections before the transaction
- const collectionCountBefore = await getCreatedCollectionCount(api);
-
- // Run the CreateCollection transaction
- const alicePrivateKey = privateKeyWrapper('//Alice');
- const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
- await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
-
- // Get number of collections after the transaction
- const collectionCountAfter = await getCreatedCollectionCount(api);
-
- // What to expect
- expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
- });
-}
-
-export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {
- let bal = 0n;
- let unused;
- do {
- const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;
- unused = privateKeyWrapper(`//${randomSeed}`);
- bal = (await api.query.system.account(unused.address)).data.free.toBigInt();
- } while (bal !== 0n);
- return unused;
-}
-
-export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {
- return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();
-}
-
-export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {
- return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));
-}
-
-export async function findNotExistingCollection(api: ApiPromise): Promise<number> {
- const totalNumber = await getCreatedCollectionCount(api);
- const newCollection: number = totalNumber + 1;
- return newCollection;
-}
-
-function getDestroyResult(events: EventRecord[]): boolean {
- let success = false;
- events.forEach(({event: {method}}) => {
- if (method == 'ExtrinsicSuccess') {
- success = true;
- }
- });
- return success;
-}
-
-export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
- // Run the DestroyCollection transaction
- const alicePrivateKey = privateKeyWrapper(senderSeed);
- const tx = api.tx.unique.destroyCollection(collectionId);
- await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
- });
-}
-
-export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
- // Run the DestroyCollection transaction
- const alicePrivateKey = privateKeyWrapper(senderSeed);
- const tx = api.tx.unique.destroyCollection(collectionId);
- const events = await submitTransactionAsync(alicePrivateKey, tx);
- const result = getDestroyResult(events);
- expect(result).to.be.true;
-
- // What to expect
- expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;
- });
-}
-
-export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.setCollectionLimits(collectionId, limits);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {
- await usingApi(async(api) => {
- const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-};
-
-export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.setCollectionLimits(collectionId, limits);
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const senderPrivateKey = privateKeyWrapper(sender);
- const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);
- const events = await submitTransactionAsync(senderPrivateKey, tx);
- const result = getGenericResult(events);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, collectionId);
-
- // What to expect
- expect(result.success).to.be.true;
- expect(collection.sponsorship.toJSON()).to.deep.equal({
- unconfirmed: sponsor,
- });
- });
-}
-
-export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const alicePrivateKey = privateKeyWrapper(sender);
- const tx = api.tx.unique.removeCollectionSponsor(collectionId);
- const events = await submitTransactionAsync(alicePrivateKey, tx);
- const result = getGenericResult(events);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, collectionId);
-
- // What to expect
- expect(result.success).to.be.true;
- expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});
- });
-}
-
-export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const alicePrivateKey = privateKeyWrapper(senderSeed);
- const tx = api.tx.unique.removeCollectionSponsor(collectionId);
- await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
- });
-}
-
-export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const alicePrivateKey = privateKeyWrapper(senderSeed);
- const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);
- await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
- });
-}
-
-export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const sender = privateKeyWrapper(senderSeed);
- await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);
- });
-}
-
-export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const tx = api.tx.unique.confirmSponsorship(collectionId);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, collectionId);
-
- // What to expect
- expect(result.success).to.be.true;
- expect(collection.sponsorship.toJSON()).to.be.deep.equal({
- confirmed: sender.address,
- });
- });
-}
-
-
-export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {
- await usingApi(async (api, privateKeyWrapper) => {
-
- // Run the transaction
- const sender = privateKeyWrapper(senderSeed);
- const tx = api.tx.unique.confirmSponsorship(collectionId);
- await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- });
-}
-
-export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {
-
- await usingApi(async (api) => {
-
- const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
-
- await usingApi(async (api) => {
-
- const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function getNextSponsored(
- api: ApiPromise,
- collectionId: number,
- account: string | CrossAccountId,
- tokenId: number,
-): Promise<number> {
- return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));
-}
-
-export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {
- let allowlisted = false;
- await usingApi(async (api) => {
- allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;
- });
- return allowlisted;
-}
-
-export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- expect(result.success).to.be.true;
- });
-}
-
-export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export interface CreateFungibleData {
- readonly Value: bigint;
-}
-
-export interface CreateReFungibleData { }
-export interface CreateNftData { }
-
-export type CreateItemData = {
- NFT: CreateNftData;
-} | {
- Fungible: CreateFungibleData;
-} | {
- ReFungible: CreateReFungibleData;
-};
-
-export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {
- const tx = api.tx.unique.burnItem(collectionId, tokenId, value);
- const events = await submitTransactionAsync(sender, tx);
- return getGenericResult(events).success;
-}
-
-export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {
- await usingApi(async (api) => {
- const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);
- // if burning token by admin - use adminButnItemExpectSuccess
- expect(balanceBefore >= BigInt(value)).to.be.true;
-
- expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;
-
- const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);
- expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);
- });
-}
-
-export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.burnItem(collectionId, tokenId, value);
-
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);
- const events = await submitTransactionAsync(sender, tx);
- return getGenericResult(events).success;
- });
-}
-
-export async function
-approve(
- api: ApiPromise,
- collectionId: number,
- tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,
-) {
- const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
- const events = await submitTransactionAsync(owner, approveUniqueTx);
- return getGenericResult(events).success;
-}
-
-export async function
-approveExpectSuccess(
- collectionId: number,
- tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const result = await approve(api, collectionId, tokenId, owner, approved, amount);
- expect(result).to.be.true;
-
- expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));
- });
-}
-
-export async function adminApproveFromExpectSuccess(
- collectionId: number,
- tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
- const events = await submitTransactionAsync(admin, approveUniqueTx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));
- });
-}
-
-export async function
-transferFrom(
- api: ApiPromise,
- collectionId: number,
- tokenId: number,
- accountApproved: IKeyringPair,
- accountFrom: IKeyringPair | CrossAccountId,
- accountTo: IKeyringPair | CrossAccountId,
- value: number | bigint,
-) {
- const from = normalizeAccountId(accountFrom);
- const to = normalizeAccountId(accountTo);
- const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);
- const events = await submitTransactionAsync(accountApproved, transferFromTx);
- return getGenericResult(events).success;
-}
-
-export async function
-transferFromExpectSuccess(
- collectionId: number,
- tokenId: number,
- accountApproved: IKeyringPair,
- accountFrom: IKeyringPair | CrossAccountId,
- accountTo: IKeyringPair | CrossAccountId,
- value: number | bigint = 1,
- type = 'NFT',
-) {
- await usingApi(async (api: ApiPromise) => {
- const from = normalizeAccountId(accountFrom);
- const to = normalizeAccountId(accountTo);
- let balanceBefore = 0n;
- if (type === 'Fungible' || type === 'ReFungible') {
- balanceBefore = await getBalance(api, collectionId, to, tokenId);
- }
- expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;
- if (type === 'NFT') {
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);
- }
- if (type === 'Fungible') {
- const balanceAfter = await getBalance(api, collectionId, to, tokenId);
- if (JSON.stringify(to) !== JSON.stringify(from)) {
- expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));
- } else {
- expect(balanceAfter).to.be.equal(balanceBefore);
- }
- }
- if (type === 'ReFungible') {
- expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));
- }
- });
-}
-
-export async function
-transferFromExpectFail(
- collectionId: number,
- tokenId: number,
- accountApproved: IKeyringPair,
- accountFrom: IKeyringPair,
- accountTo: IKeyringPair,
- value: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);
- const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;
- const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-/* eslint no-async-promise-executor: "off" */
-export async function getBlockNumber(api: ApiPromise): Promise<number> {
- return new Promise<number>(async (resolve) => {
- const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {
- unsubscribe();
- resolve(head.number.toNumber());
- });
- });
-}
-
-export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {
- await usingApi(async (api) => {
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));
- const events = await submitTransactionAsync(sender, changeAdminTx);
- const result = getCreateCollectionResult(events);
- expect(result.success).to.be.true;
- });
-}
-
-export async function adminApproveFromExpectFail(
- collectionId: number,
- tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
- const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;
- const result = getGenericResult(events);
- expect(result.success).to.be.false;
- });
-}
-
-export async function
-getFreeBalance(account: IKeyringPair): Promise<bigint> {
- let balance = 0n;
- await usingApi(async (api) => {
- balance = BigInt((await api.query.system.account(account.address)).data.free.toString());
- });
-
- return balance;
-}
-
-export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {
- return usingApi(async api => {
- // We are getting a *sibling* parachain sovereign account,
- // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c
- const siblingPrefix = '0x7369626c';
-
- const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);
- const suffix = '000000000000000000000000000000000000000000000000';
-
- return siblingPrefix + encodedParaId + suffix;
- });
-}
-
-export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {
- const tx = api.tx.balances.transfer(target, amount);
- const events = await submitTransactionAsync(source, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-}
-
-export async function
-scheduleExpectSuccess(
- operationTx: any,
- sender: IKeyringPair,
- blockSchedule: number,
- scheduledId: string,
- period = 1,
- repetitions = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const blockNumber: number | undefined = await getBlockNumber(api);
- const expectedBlockNumber = blockNumber + blockSchedule;
-
- expect(blockNumber).to.be.greaterThan(0);
- const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
- scheduledId,
- expectedBlockNumber,
- repetitions > 1 ? [period, repetitions] : null,
- 0,
- {Value: operationTx as any},
- );
-
- const events = await submitTransactionAsync(sender, scheduleTx);
- expect(getGenericResult(events).success).to.be.true;
- });
-}
-
-export async function
-scheduleExpectFailure(
- operationTx: any,
- sender: IKeyringPair,
- blockSchedule: number,
- scheduledId: string,
- period = 1,
- repetitions = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const blockNumber: number | undefined = await getBlockNumber(api);
- const expectedBlockNumber = blockNumber + blockSchedule;
-
- expect(blockNumber).to.be.greaterThan(0);
- const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
- scheduledId,
- expectedBlockNumber,
- repetitions <= 1 ? null : [period, repetitions],
- 0,
- {Value: operationTx as any},
- );
-
- //const events =
- await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;
- //expect(getGenericResult(events).success).to.be.false;
- });
-}
-
-export async function
-scheduleTransferAndWaitExpectSuccess(
- collectionId: number,
- tokenId: number,
- sender: IKeyringPair,
- recipient: IKeyringPair,
- value: number | bigint = 1,
- blockSchedule: number,
- scheduledId: string,
-) {
- await usingApi(async (api: ApiPromise) => {
- await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);
-
- const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
-
- // sleep for n + 1 blocks
- await waitNewBlocks(blockSchedule + 1);
-
- const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
-
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
- expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
- });
-}
-
-export async function
-scheduleTransferExpectSuccess(
- collectionId: number,
- tokenId: number,
- sender: IKeyringPair,
- recipient: IKeyringPair,
- value: number | bigint = 1,
- blockSchedule: number,
- scheduledId: string,
-) {
- await usingApi(async (api: ApiPromise) => {
- const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
-
- await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);
-
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
- });
-}
-
-export async function
-scheduleTransferFundsPeriodicExpectSuccess(
- amount: bigint,
- sender: IKeyringPair,
- recipient: IKeyringPair,
- blockSchedule: number,
- scheduledId: string,
- period: number,
- repetitions: number,
-) {
- await usingApi(async (api: ApiPromise) => {
- const transferTx = api.tx.balances.transfer(recipient.address, amount);
-
- const balanceBefore = await getFreeBalance(recipient);
-
- await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);
-
- expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
- });
-}
-
-export async function
-transfer(
- api: ApiPromise,
- collectionId: number,
- tokenId: number,
- sender: IKeyringPair,
- recipient: IKeyringPair | CrossAccountId,
- value: number | bigint,
-) : Promise<boolean> {
- const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
- const events = await executeTransaction(api, sender, transferTx);
- return getGenericResult(events).success;
-}
-
-export async function
-transferExpectSuccess(
- collectionId: number,
- tokenId: number,
- sender: IKeyringPair,
- recipient: IKeyringPair | CrossAccountId,
- value: number | bigint = 1,
- type = 'NFT',
-) {
- await usingApi(async (api: ApiPromise) => {
- const from = normalizeAccountId(sender);
- const to = normalizeAccountId(recipient);
-
- let balanceBefore = 0n;
- if (type === 'Fungible' || type === 'ReFungible') {
- balanceBefore = await getBalance(api, collectionId, to, tokenId);
- }
-
- const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
- const events = await executeTransaction(api, sender, transferTx);
- const result = getTransferResult(api, events);
-
- expect(result.collectionId).to.be.equal(collectionId);
- expect(result.itemId).to.be.equal(tokenId);
- expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));
- expect(result.recipient).to.be.deep.equal(to);
- expect(result.value).to.be.equal(BigInt(value));
-
- if (type === 'NFT') {
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);
- }
- if (type === 'Fungible' || type === 'ReFungible') {
- const balanceAfter = await getBalance(api, collectionId, to, tokenId);
- if (JSON.stringify(to) !== JSON.stringify(from)) {
- expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));
- } else {
- expect(balanceAfter).to.be.equal(balanceBefore);
- }
- }
- });
-}
-
-export async function
-transferExpectFailure(
- collectionId: number,
- tokenId: number,
- sender: IKeyringPair,
- recipient: IKeyringPair | CrossAccountId,
- value: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
- const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;
- const result = getGenericResult(events);
- // if (events && Array.isArray(events)) {
- // const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- //}
- });
-}
-
-export async function
-approveExpectFail(
- collectionId: number,
- tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,
-) {
- await usingApi(async (api: ApiPromise) => {
- const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);
- const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;
- const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function getBalance(
- api: ApiPromise,
- collectionId: number,
- owner: string | CrossAccountId | IKeyringPair,
- token: number,
-): Promise<bigint> {
- return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();
-}
-export async function getTokenOwner(
- api: ApiPromise,
- collectionId: number,
- token: number,
-): Promise<CrossAccountId> {
- const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;
- if (owner == null) throw new Error('owner == null');
- return normalizeAccountId(owner);
-}
-export async function getTopmostTokenOwner(
- api: ApiPromise,
- collectionId: number,
- token: number,
-): Promise<CrossAccountId> {
- const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;
- if (owner == null) throw new Error('owner == null');
- return normalizeAccountId(owner);
-}
-export async function getTokenChildren(
- api: ApiPromise,
- collectionId: number,
- tokenId: number,
-): Promise<UpDataStructsTokenChild[]> {
- return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;
-}
-export async function isTokenExists(
- api: ApiPromise,
- collectionId: number,
- token: number,
-): Promise<boolean> {
- return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();
-}
-export async function getLastTokenId(
- api: ApiPromise,
- collectionId: number,
-): Promise<number> {
- return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();
-}
-export async function getAdminList(
- api: ApiPromise,
- collectionId: number,
-): Promise<string[]> {
- return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;
-}
-export async function getTokenProperties(
- api: ApiPromise,
- collectionId: number,
- tokenId: number,
- propertyKeys: string[],
-): Promise<UpDataStructsProperty[]> {
- return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;
-}
-
-export async function createFungibleItemExpectSuccess(
- sender: IKeyringPair,
- collectionId: number,
- data: CreateFungibleData,
- owner: CrossAccountId | string = sender.address,
-) {
- return await usingApi(async (api) => {
- const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});
-
- const events = await submitTransactionAsync(sender, tx);
- const result = getCreateItemResult(events);
-
- expect(result.success).to.be.true;
- return result.itemId;
- });
-}
-
-export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {
- await usingApi(async (api) => {
- const to = normalizeAccountId(owner);
- const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);
-
- const events = await submitTransactionAsync(sender, tx);
- expect(getGenericResult(events).success).to.be.true;
- });
-}
-
-export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {
- await usingApi(async (api) => {
- const to = normalizeAccountId(owner);
- const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);
-
- const events = await submitTransactionAsync(sender, tx);
- const result = getCreateItemsResult(events);
-
- for (const res of result) {
- expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;
- }
- });
-}
-
-export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);
-
- const events = await submitTransactionAsync(sender, tx);
- const result = getCreateItemsResult(events);
-
- for (const res of result) {
- expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;
- }
- });
-}
-
-export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {
- let newItemId = 0;
- await usingApi(async (api) => {
- const to = normalizeAccountId(owner);
- const itemCountBefore = await getLastTokenId(api, collectionId);
- const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);
-
- let tx;
- if (createMode === 'Fungible') {
- const createData = {fungible: {value: 10}};
- tx = api.tx.unique.createItem(collectionId, to, createData as any);
- } else if (createMode === 'ReFungible') {
- const createData = {refungible: {pieces: 100}};
- tx = api.tx.unique.createItem(collectionId, to, createData as any);
- } else {
- const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});
- tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);
- }
-
- const events = await submitTransactionAsync(sender, tx);
- const result = getCreateItemResult(events);
-
- const itemCountAfter = await getLastTokenId(api, collectionId);
- const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);
-
- if (createMode === 'NFT') {
- expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;
- }
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- if (createMode === 'Fungible') {
- expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
- } else {
- expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
- }
- expect(collectionId).to.be.equal(result.collectionId);
- expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());
- expect(to).to.be.deep.equal(result.recipient);
- newItemId = result.itemId;
- });
- return newItemId;
-}
-
-export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {
- await usingApi(async (api) => {
-
- let tx;
- if (createMode === 'NFT') {
- const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;
- tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);
- } else {
- tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);
- }
-
-
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;
- const result = getCreateItemResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {
- let newItemId = 0;
- await usingApi(async (api) => {
- const to = normalizeAccountId(owner);
- const itemCountBefore = await getLastTokenId(api, collectionId);
- const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);
-
- let tx;
- if (createMode === 'Fungible') {
- const createData = {fungible: {value: 10}};
- tx = api.tx.unique.createItem(collectionId, to, createData as any);
- } else if (createMode === 'ReFungible') {
- const createData = {refungible: {pieces: 100}};
- tx = api.tx.unique.createItem(collectionId, to, createData as any);
- } else {
- const createData = {nft: {}};
- tx = api.tx.unique.createItem(collectionId, to, createData as any);
- }
-
- const events = await executeTransaction(api, sender, tx);
- const result = getCreateItemResult(events);
-
- const itemCountAfter = await getLastTokenId(api, collectionId);
- const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- if (createMode === 'Fungible') {
- expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
- } else {
- expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
- }
- expect(collectionId).to.be.equal(result.collectionId);
- expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());
- expect(to).to.be.deep.equal(result.recipient);
- newItemId = result.itemId;
- });
- return newItemId;
-}
-
-export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {
- const createData = {refungible: {pieces: amount}};
- const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);
-
- const events = await submitTransactionAsync(sender, tx);
- return getCreateItemResult(events);
-}
-
-export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {
- await usingApi(async (api) => {
- const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);
-
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getCreateItemResult(events);
-
- expect(result.success).to.be.false;
- });
-}
-
-export async function setPublicAccessModeExpectSuccess(
- sender: IKeyringPair, collectionId: number,
- accessMode: 'Normal' | 'AllowList',
-) {
- await usingApi(async (api) => {
-
- // Run the transaction
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, collectionId);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);
- });
-}
-
-export async function setPublicAccessModeExpectFail(
- sender: IKeyringPair, collectionId: number,
- accessMode: 'Normal' | 'AllowList',
-) {
- await usingApi(async (api) => {
-
- // Run the transaction
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
- await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');
-}
-
-export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {
- await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');
-}
-
-export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
- await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');
-}
-
-export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {
- await usingApi(async (api) => {
-
- // Run the transaction
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- // Get the collection
- const collection = await queryCollectionExpectSuccess(api, collectionId);
-
- expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);
- });
-}
-
-export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {
- await setMintPermissionExpectSuccess(sender, collectionId, true);
-}
-
-export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
- await usingApi(async (api) => {
- // Run the transaction
- const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {
- await usingApi(async (api) => {
- // Run the transaction
- const tx = api.tx.unique.setChainLimits(limits);
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getCreateCollectionResult(events);
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {
- return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();
-}
-
-export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {
- await usingApi(async (api) => {
- expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;
-
- // Run the transaction
- const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
- });
-}
-
-export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
- await usingApi(async (api) => {
-
- expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
-
- // Run the transaction
- const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
-
- expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
- });
-}
-
-export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
- await usingApi(async (api) => {
-
- // Run the transaction
- const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
- await usingApi(async (api) => {
- // Run the transaction
- const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.true;
- });
-}
-
-export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
- await usingApi(async (api) => {
- // Run the transaction
- const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));
- const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
- const result = getGenericResult(events);
-
- // What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
- });
-}
-
-export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)
- : Promise<UpDataStructsRpcCollection | null> => {
- return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);
-};
-
-export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {
- // set global object - collectionsCount
- return (await api.rpc.unique.collectionStats()).created.toNumber();
-};
-
-export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {
- return (await api.rpc.unique.collectionById(collectionId)).unwrap();
-}
-
-export const describe_xcm = (
- process.env.RUN_XCM_TESTS
- ? describe
- : describe.skip
-);
-
-export async function waitNewBlocks(blocksCount = 1): Promise<void> {
- await usingApi(async (api) => {
- const promise = new Promise<void>(async (resolve) => {
- const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {
- if (blocksCount > 0) {
- blocksCount--;
- } else {
- unsubscribe();
- resolve();
- }
- });
- });
- return promise;
- });
-}
-
-export async function waitEvent(
- api: ApiPromise,
- maxBlocksToWait: number,
- eventSection: string,
- eventMethod: string,
-): Promise<EventRecord | null> {
-
- const promise = new Promise<EventRecord | null>(async (resolve) => {
- const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {
- const blockNumber = header.number.toHuman();
- const blockHash = header.hash;
- const eventIdStr = `${eventSection}.${eventMethod}`;
- const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;
-
- console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);
-
- const apiAt = await api.at(blockHash);
- const eventRecords = await apiAt.query.system.events();
-
- const neededEvent = eventRecords.find(r => {
- return r.event.section == eventSection && r.event.method == eventMethod;
- });
-
- if (neededEvent) {
- unsubscribe();
- resolve(neededEvent);
- } else if (maxBlocksToWait > 0) {
- maxBlocksToWait--;
- } else {
- console.log(`Event \`${eventIdStr}\` is NOT found`);
-
- unsubscribe();
- resolve(null);
- }
- });
- });
- return promise;
-}
-
-export async function repartitionRFT(
- api: ApiPromise,
- collectionId: number,
- sender: IKeyringPair,
- tokenId: number,
- amount: bigint,
-): Promise<boolean> {
- const tx = api.tx.unique.repartition(collectionId, tokenId, amount);
- const events = await submitTransactionAsync(sender, tx);
- const result = getGenericResult(events);
-
- return result.success;
-}
-
-export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
- let i: any = it;
- if (opts.only) i = i.only;
- else if (opts.skip) i = i.skip;
- i(name, async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- await cb({api, privateKeyWrapper});
- });
- });
-}
-
-itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});
-itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});
-
-let accountSeed = 10000;
-export function generateKeyringPair(keyring: Keyring) {
- const privateKey = `0xDEADBEEF${(Date.now() + (accountSeed++)).toString(16).padStart(64 - 8, '0')}`;
- return keyring.addFromUri(privateKey);
-}
-
-export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {
- const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
- const subEvents = (await api.query.system.events.at(blockHash))
- .filter(x => x.event.section === section)
- .map((x) => x.toHuman());
- const events = methods.map((m) => {
- return {
- event: {
- method: m,
- section,
- },
- };
- });
- if (!dryRun) {
- expect(subEvents).to.be.like(events);
- }
- return subEvents;
-}
tests/src/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -62,6 +62,7 @@
Fungible = 'fungible',
NFT = 'nonfungible',
Scheduler = 'scheduler',
+ AppPromotion = 'apppromotion',
}
export function requirePalletsOrSkip(test: Context, helper: DevUniqueHelper, requiredPallets: string[]) {
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -14,6 +14,7 @@
export interface ITransactionResult {
status: 'Fail' | 'Success';
result: {
+ dispatchError: any,
events: {
phase: any, // {ApplyExtrinsic: number} | 'Initialization',
event: IEvent;
@@ -47,6 +48,7 @@
call: string;
params: any[];
moduleError?: string;
+ dispatchError?: any;
events?: any;
}
@@ -162,6 +164,14 @@
amount: bigint,
}
+export interface ISchedulerOptions {
+ priority?: number,
+ periodic?: {
+ period: number,
+ repetitions: number,
+ },
+}
+
export type TSubstrateAccount = string;
export type TEthereumAccount = string;
export type TApiAllowedListeners = 'connected' | 'disconnected' | 'error' | 'ready' | 'decorated';
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -8,7 +8,6 @@
import {IKeyringPair} from '@polkadot/types/types';
import {ICrossAccountId} from './types';
-
export class SilentLogger {
log(_msg: any, _level: any): void { }
level = {
@@ -63,8 +62,10 @@
wait: WaitGroup;
admin: AdminGroup;
- constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
- super(logger);
+ constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
+ options.helperBase = options.helperBase ?? DevUniqueHelper;
+
+ super(logger, options);
this.arrange = new ArrangeGroup(this);
this.wait = new WaitGroup(this);
this.admin = new AdminGroup(this);
@@ -108,9 +109,9 @@
}
class ArrangeGroup {
- helper: UniqueHelper;
+ helper: DevUniqueHelper;
- constructor(helper: UniqueHelper) {
+ constructor(helper: DevUniqueHelper) {
this.helper = helper;
}
@@ -215,8 +216,8 @@
};
isDevNode = async () => {
- const block1 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(1));
- const block2 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(2));
+ const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [1])]);
+ const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [2])]);
const findCreationDate = async (block: any) => {
const humanBlock = block.toHuman();
let date;
@@ -245,21 +246,21 @@
}
class WaitGroup {
- helper: UniqueHelper;
+ helper: DevUniqueHelper;
- constructor(helper: UniqueHelper) {
+ constructor(helper: DevUniqueHelper) {
this.helper = helper;
}
/**
- * Wait for specified bnumber of blocks
+ * Wait for specified number of blocks
* @param blocksCount number of blocks to wait
* @returns
*/
async newBlocks(blocksCount = 1): Promise<void> {
// eslint-disable-next-line no-async-promise-executor
const promise = new Promise<void>(async (resolve) => {
- const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {
+ const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {
if (blocksCount > 0) {
blocksCount--;
} else {
@@ -274,7 +275,7 @@
async forParachainBlockNumber(blockNumber: bigint) {
// eslint-disable-next-line no-async-promise-executor
return new Promise<void>(async (resolve) => {
- const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {
+ const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {
if (data.number.toNumber() >= blockNumber) {
unsubscribe();
resolve();
@@ -286,7 +287,7 @@
async forRelayBlockNumber(blockNumber: bigint) {
// eslint-disable-next-line no-async-promise-executor
return new Promise<void>(async (resolve) => {
- const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {
+ const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {
if (data.value.relayParentNumber.toNumber() >= blockNumber) {
// @ts-ignore
unsubscribe();
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 // If ith character is 8 to f then make it uppercase84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255}256257class UniqueEventHelper {258 private static extractIndex(index: any): [number, number] | string {259 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];260 return index.toJSON();261 }262263 private static extractSub(data: any, subTypes: any): {[key: string]: any} {264 let obj: any = {};265 let index = 0;266267 if (data.entries) {268 for(const [key, value] of data.entries()) {269 obj[key] = this.extractData(value, subTypes[index]);270 index++;271 }272 } else obj = data.toJSON();273274 return obj;275 }276 277 private static extractData(data: any, type: any): any {278 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();279 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();280 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);281 return data.toHuman();282 }283284 public static extractEvents(records: ITransactionResult): IEvent[] {285 const parsedEvents: IEvent[] = [];286287 records.result.events.forEach((record) => {288 const {event, phase} = record;289 const types = (event as any).typeDef;290291 const eventData: IEvent = {292 section: event.section.toString(),293 method: event.method.toString(),294 index: this.extractIndex(event.index),295 data: [],296 phase: phase.toJSON(),297 };298299 event.data.forEach((val: any, index: number) => {300 eventData.data.push(this.extractData(val, types[index]));301 });302303 parsedEvents.push(eventData);304 });305306 return parsedEvents;307 }308}309310class ChainHelperBase {311 transactionStatus = UniqueUtil.transactionStatus;312 chainLogType = UniqueUtil.chainLogType;313 util: typeof UniqueUtil;314 eventHelper: typeof UniqueEventHelper;315 logger: ILogger;316 api: ApiPromise | null;317 forcedNetwork: TUniqueNetworks | null;318 network: TUniqueNetworks | null;319 chainLog: IUniqueHelperLog[];320321 constructor(logger?: ILogger) {322 this.util = UniqueUtil;323 this.eventHelper = UniqueEventHelper;324 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();325 this.logger = logger;326 this.api = null;327 this.forcedNetwork = null;328 this.network = null;329 this.chainLog = [];330 }331332 clearChainLog(): void {333 this.chainLog = [];334 }335336 forceNetwork(value: TUniqueNetworks): void {337 this.forcedNetwork = value;338 }339340 async connect(wsEndpoint: string, listeners?: IApiListeners) {341 if (this.api !== null) throw Error('Already connected');342 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);343 this.api = api;344 this.network = network;345 }346347 async disconnect() {348 if (this.api === null) return;349 await this.api.disconnect();350 this.api = null;351 this.network = null;352 }353354 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {355 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;356 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;357 return 'opal';358 }359360 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {361 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});362 await api.isReady;363364 const network = await this.detectNetwork(api);365366 await api.disconnect();367368 return network;369 }370371 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{372 api: ApiPromise;373 network: TUniqueNetworks;374 }> {375 if(typeof network === 'undefined' || network === null) network = 'opal';376 const supportedRPC = {377 opal: {378 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,379 },380 quartz: {381 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,382 },383 unique: {384 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,385 },386 };387 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);388 const rpc = supportedRPC[network];389390 // TODO: investigate how to replace rpc in runtime391 // api._rpcCore.addUserInterfaces(rpc);392393 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});394395 await api.isReadyOrError;396397 if (typeof listeners === 'undefined') listeners = {};398 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {399 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;400 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);401 }402403 return {api, network};404 }405406 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {407 const {events, status} = data;408 if (status.isReady) {409 return this.transactionStatus.NOT_READY;410 }411 if (status.isBroadcast) {412 return this.transactionStatus.NOT_READY;413 }414 if (status.isInBlock || status.isFinalized) {415 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');416 if (errors.length > 0) {417 return this.transactionStatus.FAIL;418 }419 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {420 return this.transactionStatus.SUCCESS;421 }422 }423424 return this.transactionStatus.FAIL;425 }426427 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {428 const sign = (callback: any) => {429 if(options !== null) return transaction.signAndSend(sender, options, callback);430 return transaction.signAndSend(sender, callback);431 };432 // eslint-disable-next-line no-async-promise-executor433 return new Promise(async (resolve, reject) => {434 try {435 const unsub = await sign((result: any) => {436 const status = this.getTransactionStatus(result);437438 if (status === this.transactionStatus.SUCCESS) {439 this.logger.log(`${label} successful`);440 unsub();441 resolve({result, status});442 } else if (status === this.transactionStatus.FAIL) {443 let moduleError = null;444445 if (result.hasOwnProperty('dispatchError')) {446 const dispatchError = result['dispatchError'];447448 if (dispatchError) {449 if (dispatchError.isModule) {450 const modErr = dispatchError.asModule;451 const errorMeta = dispatchError.registry.findMetaError(modErr);452453 moduleError = `${errorMeta.section}.${errorMeta.name}`;454 } else {455 moduleError = dispatchError.toHuman();456 }457 } else {458 this.logger.log(result, this.logger.level.ERROR);459 }460 }461462 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);463 unsub();464 reject({status, moduleError, result});465 }466 });467 } catch (e) {468 this.logger.log(e, this.logger.level.ERROR);469 reject(e);470 }471 });472 }473474 constructApiCall(apiCall: string, params: any[]) {475 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);476 let call = this.api as any;477 for(const part of apiCall.slice(4).split('.')) {478 call = call[part];479 }480 return call(...params);481 }482483 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {484 if(this.api === null) throw Error('API not initialized');485 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);486487 const startTime = (new Date()).getTime();488 let result: ITransactionResult;489 let events: IEvent[] = [];490 try {491 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;492 events = this.eventHelper.extractEvents(result);493 }494 catch(e) {495 if(!(e as object).hasOwnProperty('status')) throw e;496 result = e as ITransactionResult;497 }498499 const endTime = (new Date()).getTime();500501 const log = {502 executedAt: endTime,503 executionTime: endTime - startTime,504 type: this.chainLogType.EXTRINSIC,505 status: result.status,506 call: extrinsic,507 signer: this.getSignerAddress(sender),508 params,509 } as IUniqueHelperLog;510511 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;512 if(events.length > 0) log.events = events;513514 this.chainLog.push(log);515516 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);517 return result;518 }519520 async callRpc(rpc: string, params?: any[]) {521 if(typeof params === 'undefined') params = [];522 if(this.api === null) throw Error('API not initialized');523 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);524525 const startTime = (new Date()).getTime();526 let result;527 let error = null;528 const log = {529 type: this.chainLogType.RPC,530 call: rpc,531 params,532 } as IUniqueHelperLog;533534 try {535 result = await this.constructApiCall(rpc, params);536 }537 catch(e) {538 error = e;539 }540541 const endTime = (new Date()).getTime();542543 log.executedAt = endTime;544 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';545 log.executionTime = endTime - startTime;546547 this.chainLog.push(log);548549 if(error !== null) throw error;550551 return result;552 }553554 getSignerAddress(signer: IKeyringPair | string): string {555 if(typeof signer === 'string') return signer;556 return signer.address;557 }558559 fetchAllPalletNames(): string[] {560 if(this.api === null) throw Error('API not initialized');561 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());562 }563564 fetchMissingPalletNames(requiredPallets: string[]): string[] {565 const palletNames = this.fetchAllPalletNames();566 return requiredPallets.filter(p => !palletNames.includes(p));567 }568}569570571class HelperGroup {572 helper: UniqueHelper;573574 constructor(uniqueHelper: UniqueHelper) {575 this.helper = uniqueHelper;576 }577}578579580class CollectionGroup extends HelperGroup {581 /**582 * Get number of blocks when sponsored transaction is available.583 *584 * @param collectionId ID of collection585 * @param tokenId ID of token586 * @param addressObj address for which the sponsorship is checked587 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});588 * @returns number of blocks or null if sponsorship hasn't been set589 */590 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {591 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();592 }593594 /**595 * Get the number of created collections.596 *597 * @returns number of created collections598 */599 async getTotalCount(): Promise<number> {600 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();601 }602603 /**604 * Get information about the collection with additional data,605 * including the number of tokens it contains, its administrators,606 * the normalized address of the collection's owner, and decoded name and description.607 *608 * @param collectionId ID of collection609 * @example await getData(2)610 * @returns collection information object611 */612 async getData(collectionId: number): Promise<{613 id: number;614 name: string;615 description: string;616 tokensCount: number;617 admins: CrossAccountId[];618 normalizedOwner: TSubstrateAccount;619 raw: any620 } | null> {621 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);622 const humanCollection = collection.toHuman(), collectionData = {623 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],624 raw: humanCollection,625 } as any, jsonCollection = collection.toJSON();626 if (humanCollection === null) return null;627 collectionData.raw.limits = jsonCollection.limits;628 collectionData.raw.permissions = jsonCollection.permissions;629 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);630 for (const key of ['name', 'description']) {631 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);632 }633634 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))635 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)636 : 0;637 collectionData.admins = await this.getAdmins(collectionId);638639 return collectionData;640 }641642 /**643 * Get the addresses of the collection's administrators, optionally normalized.644 *645 * @param collectionId ID of collection646 * @param normalize whether to normalize the addresses to the default ss58 format647 * @example await getAdmins(1)648 * @returns array of administrators649 */650 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {651 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();652653 return normalize654 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())655 : admins;656 }657658 /**659 * Get the addresses added to the collection allow-list, optionally normalized.660 * @param collectionId ID of collection661 * @param normalize whether to normalize the addresses to the default ss58 format662 * @example await getAllowList(1)663 * @returns array of allow-listed addresses664 */665 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {666 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();667 return normalize668 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())669 : allowListed;670 }671672 /**673 * Get the effective limits of the collection instead of null for default values674 *675 * @param collectionId ID of collection676 * @example await getEffectiveLimits(2)677 * @returns object of collection limits678 */679 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {680 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();681 }682683 /**684 * Burns the collection if the signer has sufficient permissions and collection is empty.685 *686 * @param signer keyring of signer687 * @param collectionId ID of collection688 * @example await helper.collection.burn(aliceKeyring, 3);689 * @returns ```true``` if extrinsic success, otherwise ```false```690 */691 async burn(signer: TSigner, collectionId: number): Promise<boolean> {692 const result = await this.helper.executeExtrinsic(693 signer,694 'api.tx.unique.destroyCollection', [collectionId],695 true,696 );697698 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');699 }700701 /**702 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.703 *704 * @param signer keyring of signer705 * @param collectionId ID of collection706 * @param sponsorAddress Sponsor substrate address707 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")708 * @returns ```true``` if extrinsic success, otherwise ```false```709 */710 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {711 const result = await this.helper.executeExtrinsic(712 signer,713 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],714 true,715 );716717 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');718 }719720 /**721 * Confirms consent to sponsor the collection on behalf of the signer.722 *723 * @param signer keyring of signer724 * @param collectionId ID of collection725 * @example confirmSponsorship(aliceKeyring, 10)726 * @returns ```true``` if extrinsic success, otherwise ```false```727 */728 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {729 const result = await this.helper.executeExtrinsic(730 signer,731 'api.tx.unique.confirmSponsorship', [collectionId],732 true,733 );734735 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');736 }737738 /**739 * Removes the sponsor of a collection, regardless if it consented or not.740 *741 * @param signer keyring of signer742 * @param collectionId ID of collection743 * @example removeSponsor(aliceKeyring, 10)744 * @returns ```true``` if extrinsic success, otherwise ```false```745 */746 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {747 const result = await this.helper.executeExtrinsic(748 signer,749 'api.tx.unique.removeCollectionSponsor', [collectionId],750 true,751 );752753 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');754 }755756 /**757 * Sets the limits of the collection. At least one limit must be specified for a correct call.758 *759 * @param signer keyring of signer760 * @param collectionId ID of collection761 * @param limits collection limits object762 * @example763 * await setLimits(764 * aliceKeyring,765 * 10,766 * {767 * sponsorTransferTimeout: 0,768 * ownerCanDestroy: false769 * }770 * )771 * @returns ```true``` if extrinsic success, otherwise ```false```772 */773 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {774 const result = await this.helper.executeExtrinsic(775 signer,776 'api.tx.unique.setCollectionLimits', [collectionId, limits],777 true,778 );779780 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');781 }782783 /**784 * Changes the owner of the collection to the new Substrate address.785 *786 * @param signer keyring of signer787 * @param collectionId ID of collection788 * @param ownerAddress substrate address of new owner789 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")790 * @returns ```true``` if extrinsic success, otherwise ```false```791 */792 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {793 const result = await this.helper.executeExtrinsic(794 signer,795 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],796 true,797 );798799 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');800 }801802 /**803 * Adds a collection administrator.804 *805 * @param signer keyring of signer806 * @param collectionId ID of collection807 * @param adminAddressObj Administrator address (substrate or ethereum)808 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})809 * @returns ```true``` if extrinsic success, otherwise ```false```810 */811 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {812 const result = await this.helper.executeExtrinsic(813 signer,814 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],815 true,816 );817818 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');819 }820821 /**822 * Removes a collection administrator.823 *824 * @param signer keyring of signer825 * @param collectionId ID of collection826 * @param adminAddressObj Administrator address (substrate or ethereum)827 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})828 * @returns ```true``` if extrinsic success, otherwise ```false```829 */830 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {831 const result = await this.helper.executeExtrinsic(832 signer,833 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],834 true,835 );836837 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');838 }839840 /**841 * Check if user is in allow list.842 * 843 * @param collectionId ID of collection844 * @param user Account to check845 * @example await getAdmins(1)846 * @returns is user in allow list847 */848 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {849 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();850 }851852 /**853 * Adds an address to allow list854 * @param signer keyring of signer855 * @param collectionId ID of collection856 * @param addressObj address to add to the allow list857 * @returns ```true``` if extrinsic success, otherwise ```false```858 */859 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {860 const result = await this.helper.executeExtrinsic(861 signer,862 'api.tx.unique.addToAllowList', [collectionId, addressObj],863 true,864 );865866 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');867 }868869 /**870 * Removes an address from allow list871 *872 * @param signer keyring of signer873 * @param collectionId ID of collection874 * @param addressObj address to remove from the allow list875 * @returns ```true``` if extrinsic success, otherwise ```false```876 */877 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {878 const result = await this.helper.executeExtrinsic(879 signer,880 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],881 true,882 );883884 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');885 }886887 /**888 * Sets onchain permissions for selected collection.889 *890 * @param signer keyring of signer891 * @param collectionId ID of collection892 * @param permissions collection permissions object893 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});894 * @returns ```true``` if extrinsic success, otherwise ```false```895 */896 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {897 const result = await this.helper.executeExtrinsic(898 signer,899 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],900 true,901 );902903 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');904 }905906 /**907 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.908 *909 * @param signer keyring of signer910 * @param collectionId ID of collection911 * @param permissions nesting permissions object912 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});913 * @returns ```true``` if extrinsic success, otherwise ```false```914 */915 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {916 return await this.setPermissions(signer, collectionId, {nesting: permissions});917 }918919 /**920 * Disables nesting for selected collection.921 *922 * @param signer keyring of signer923 * @param collectionId ID of collection924 * @example disableNesting(aliceKeyring, 10);925 * @returns ```true``` if extrinsic success, otherwise ```false```926 */927 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {928 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});929 }930931 /**932 * Sets onchain properties to the collection.933 *934 * @param signer keyring of signer935 * @param collectionId ID of collection936 * @param properties array of property objects937 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);938 * @returns ```true``` if extrinsic success, otherwise ```false```939 */940 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {941 const result = await this.helper.executeExtrinsic(942 signer,943 'api.tx.unique.setCollectionProperties', [collectionId, properties],944 true,945 );946947 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');948 }949950 /**951 * Get collection properties.952 * 953 * @param collectionId ID of collection954 * @param propertyKeys optionally filter the returned properties to only these keys955 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);956 * @returns array of key-value pairs957 */958 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {959 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();960 }961962 /**963 * Deletes onchain properties from the collection.964 *965 * @param signer keyring of signer966 * @param collectionId ID of collection967 * @param propertyKeys array of property keys to delete968 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);969 * @returns ```true``` if extrinsic success, otherwise ```false```970 */971 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {972 const result = await this.helper.executeExtrinsic(973 signer,974 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],975 true,976 );977978 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');979 }980981 /**982 * Changes the owner of the token.983 *984 * @param signer keyring of signer985 * @param collectionId ID of collection986 * @param tokenId ID of token987 * @param addressObj address of a new owner988 * @param amount amount of tokens to be transfered. For NFT must be set to 1n989 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})990 * @returns true if the token success, otherwise false991 */992 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {993 const result = await this.helper.executeExtrinsic(994 signer,995 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],996 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,997 );998999 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1000 }10011002 /**1003 *1004 * Change ownership of a token(s) on behalf of the owner.1005 *1006 * @param signer keyring of signer1007 * @param collectionId ID of collection1008 * @param tokenId ID of token1009 * @param fromAddressObj address on behalf of which the token will be sent1010 * @param toAddressObj new token owner1011 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1012 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1013 * @returns true if the token success, otherwise false1014 */1015 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1016 const result = await this.helper.executeExtrinsic(1017 signer,1018 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1019 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1020 );1021 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1022 }10231024 /**1025 *1026 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1027 *1028 * @param signer keyring of signer1029 * @param collectionId ID of collection1030 * @param tokenId ID of token1031 * @param amount amount of tokens to be burned. For NFT must be set to 1n1032 * @example burnToken(aliceKeyring, 10, 5);1033 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1034 */1035 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1036 const burnResult = await this.helper.executeExtrinsic(1037 signer,1038 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1039 true, // `Unable to burn token for ${label}`,1040 );1041 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1042 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1043 return burnedTokens.success;1044 }10451046 /**1047 * Destroys a concrete instance of NFT on behalf of the owner1048 *1049 * @param signer keyring of signer1050 * @param collectionId ID of collection1051 * @param tokenId ID of token1052 * @param fromAddressObj address on behalf of which the token will be burnt1053 * @param amount amount of tokens to be burned. For NFT must be set to 1n1054 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1055 * @returns ```true``` if extrinsic success, otherwise ```false```1056 */1057 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1058 const burnResult = await this.helper.executeExtrinsic(1059 signer,1060 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1061 true, // `Unable to burn token from for ${label}`,1062 );1063 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1064 return burnedTokens.success && burnedTokens.tokens.length > 0;1065 }10661067 /**1068 * Set, change, or remove approved address to transfer the ownership of the NFT.1069 *1070 * @param signer keyring of signer1071 * @param collectionId ID of collection1072 * @param tokenId ID of token1073 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1074 * @param amount amount of token to be approved. For NFT must be set to 1n1075 * @returns ```true``` if extrinsic success, otherwise ```false```1076 */1077 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1078 const approveResult = await this.helper.executeExtrinsic(1079 signer,1080 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1081 true, // `Unable to approve token for ${label}`,1082 );10831084 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1085 }10861087 /**1088 * Get the amount of token pieces approved to transfer or burn. Normally 0.1089 *1090 * @param collectionId ID of collection1091 * @param tokenId ID of token1092 * @param toAccountObj address which is approved to use token pieces1093 * @param fromAccountObj address which may have allowed the use of its owned tokens1094 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1095 * @returns number of approved to transfer pieces1096 */1097 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1098 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1099 }11001101 /**1102 * Get the last created token ID in a collection1103 *1104 * @param collectionId ID of collection1105 * @example getLastTokenId(10);1106 * @returns id of the last created token1107 */1108 async getLastTokenId(collectionId: number): Promise<number> {1109 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1110 }11111112 /**1113 * Check if token exists1114 *1115 * @param collectionId ID of collection1116 * @param tokenId ID of token1117 * @example doesTokenExist(10, 20);1118 * @returns true if the token exists, otherwise false1119 */1120 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1121 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1122 }1123}11241125class NFTnRFT extends CollectionGroup {1126 /**1127 * Get tokens owned by account1128 *1129 * @param collectionId ID of collection1130 * @param addressObj tokens owner1131 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1132 * @returns array of token ids owned by account1133 */1134 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1135 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1136 }11371138 /**1139 * Get token data1140 *1141 * @param collectionId ID of collection1142 * @param tokenId ID of token1143 * @param propertyKeys optionally filter the token properties to only these keys1144 * @param blockHashAt optionally query the data at some block with this hash1145 * @example getToken(10, 5);1146 * @returns human readable token data1147 */1148 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1149 properties: IProperty[];1150 owner: CrossAccountId;1151 normalizedOwner: CrossAccountId;1152 }| null> {1153 let tokenData;1154 if(typeof blockHashAt === 'undefined') {1155 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1156 }1157 else {1158 if(propertyKeys.length == 0) {1159 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1160 if(!collection) return null;1161 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1162 }1163 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1164 }1165 tokenData = tokenData.toHuman();1166 if (tokenData === null || tokenData.owner === null) return null;1167 const owner = {} as any;1168 for (const key of Object.keys(tokenData.owner)) {1169 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1170 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1171 : tokenData.owner[key];1172 }1173 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1174 return tokenData;1175 }11761177 /**1178 * Set permissions to change token properties1179 *1180 * @param signer keyring of signer1181 * @param collectionId ID of collection1182 * @param permissions permissions to change a property by the collection admin or token owner1183 * @example setTokenPropertyPermissions(1184 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1185 * )1186 * @returns true if extrinsic success otherwise false1187 */1188 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1189 const result = await this.helper.executeExtrinsic(1190 signer,1191 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1192 true,1193 );11941195 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1196 }11971198 /**1199 * Get token property permissions.1200 * 1201 * @param collectionId ID of collection1202 * @param propertyKeys optionally filter the returned property permissions to only these keys1203 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1204 * @returns array of key-permission pairs1205 */1206 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1207 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1208 }12091210 /**1211 * Set token properties1212 *1213 * @param signer keyring of signer1214 * @param collectionId ID of collection1215 * @param tokenId ID of token1216 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1217 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1218 * @returns ```true``` if extrinsic success, otherwise ```false```1219 */1220 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1221 const result = await this.helper.executeExtrinsic(1222 signer,1223 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1224 true,1225 );12261227 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1228 }12291230 /**1231 * Get properties, metadata assigned to a token.1232 * 1233 * @param collectionId ID of collection1234 * @param tokenId ID of token1235 * @param propertyKeys optionally filter the returned properties to only these keys1236 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1237 * @returns array of key-value pairs1238 */1239 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1240 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1241 }12421243 /**1244 * Delete the provided properties of a token1245 * @param signer keyring of signer1246 * @param collectionId ID of collection1247 * @param tokenId ID of token1248 * @param propertyKeys property keys to be deleted1249 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1250 * @returns ```true``` if extrinsic success, otherwise ```false```1251 */1252 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1253 const result = await this.helper.executeExtrinsic(1254 signer,1255 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1256 true,1257 );12581259 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1260 }12611262 /**1263 * Mint new collection1264 *1265 * @param signer keyring of signer1266 * @param collectionOptions basic collection options and properties1267 * @param mode NFT or RFT type of a collection1268 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1269 * @returns object of the created collection1270 */1271 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1272 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1273 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1274 for (const key of ['name', 'description', 'tokenPrefix']) {1275 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1276 }1277 const creationResult = await this.helper.executeExtrinsic(1278 signer,1279 'api.tx.unique.createCollectionEx', [collectionOptions],1280 true, // errorLabel,1281 );1282 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1283 }12841285 getCollectionObject(_collectionId: number): any {1286 return null;1287 }12881289 getTokenObject(_collectionId: number, _tokenId: number): any {1290 return null;1291 }1292}129312941295class NFTGroup extends NFTnRFT {1296 /**1297 * Get collection object1298 * @param collectionId ID of collection1299 * @example getCollectionObject(2);1300 * @returns instance of UniqueNFTCollection1301 */1302 getCollectionObject(collectionId: number): UniqueNFTCollection {1303 return new UniqueNFTCollection(collectionId, this.helper);1304 }13051306 /**1307 * Get token object1308 * @param collectionId ID of collection1309 * @param tokenId ID of token1310 * @example getTokenObject(10, 5);1311 * @returns instance of UniqueNFTToken1312 */1313 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1314 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1315 }13161317 /**1318 * Get token's owner1319 * @param collectionId ID of collection1320 * @param tokenId ID of token1321 * @param blockHashAt optionally query the data at the block with this hash1322 * @example getTokenOwner(10, 5);1323 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1324 */1325 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1326 let owner;1327 if (typeof blockHashAt === 'undefined') {1328 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1329 } else {1330 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1331 }1332 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1333 }13341335 /**1336 * Is token approved to transfer1337 * @param collectionId ID of collection1338 * @param tokenId ID of token1339 * @param toAccountObj address to be approved1340 * @returns ```true``` if extrinsic success, otherwise ```false```1341 */1342 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1343 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1344 }13451346 /**1347 * Changes the owner of the token.1348 *1349 * @param signer keyring of signer1350 * @param collectionId ID of collection1351 * @param tokenId ID of token1352 * @param addressObj address of a new owner1353 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1354 * @returns ```true``` if extrinsic success, otherwise ```false```1355 */1356 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1357 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1358 }13591360 /**1361 *1362 * Change ownership of a NFT on behalf of the owner.1363 *1364 * @param signer keyring of signer1365 * @param collectionId ID of collection1366 * @param tokenId ID of token1367 * @param fromAddressObj address on behalf of which the token will be sent1368 * @param toAddressObj new token owner1369 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1370 * @returns ```true``` if extrinsic success, otherwise ```false```1371 */1372 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1373 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1374 }13751376 /**1377 * Recursively find the address that owns the token1378 * @param collectionId ID of collection1379 * @param tokenId ID of token1380 * @param blockHashAt1381 * @example getTokenTopmostOwner(10, 5);1382 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1383 */1384 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1385 let owner;1386 if (typeof blockHashAt === 'undefined') {1387 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1388 } else {1389 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1390 }13911392 if (owner === null) return null;13931394 return owner.toHuman();1395 }13961397 /**1398 * Get tokens nested in the provided token1399 * @param collectionId ID of collection1400 * @param tokenId ID of token1401 * @param blockHashAt optionally query the data at the block with this hash1402 * @example getTokenChildren(10, 5);1403 * @returns tokens whose depth of nesting is <= 51404 */1405 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1406 let children;1407 if(typeof blockHashAt === 'undefined') {1408 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1409 } else {1410 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1411 }14121413 return children.toJSON().map((x: any) => {1414 return {collectionId: x.collection, tokenId: x.token};1415 });1416 }14171418 /**1419 * Nest one token into another1420 * @param signer keyring of signer1421 * @param tokenObj token to be nested1422 * @param rootTokenObj token to be parent1423 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1424 * @returns ```true``` if extrinsic success, otherwise ```false```1425 */1426 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1427 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1428 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1429 if(!result) {1430 throw Error('Unable to nest token!');1431 }1432 return result;1433 }14341435 /**1436 * Remove token from nested state1437 * @param signer keyring of signer1438 * @param tokenObj token to unnest1439 * @param rootTokenObj parent of a token1440 * @param toAddressObj address of a new token owner1441 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1442 * @returns ```true``` if extrinsic success, otherwise ```false```1443 */1444 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1445 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1446 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1447 if(!result) {1448 throw Error('Unable to unnest token!');1449 }1450 return result;1451 }14521453 /**1454 * Mint new collection1455 * @param signer keyring of signer1456 * @param collectionOptions Collection options1457 * @example1458 * mintCollection(aliceKeyring, {1459 * name: 'New',1460 * description: 'New collection',1461 * tokenPrefix: 'NEW',1462 * })1463 * @returns object of the created collection1464 */1465 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1466 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1467 }14681469 /**1470 * Mint new token1471 * @param signer keyring of signer1472 * @param data token data1473 * @returns created token object1474 */1475 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1476 const creationResult = await this.helper.executeExtrinsic(1477 signer,1478 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1479 nft: {1480 properties: data.properties,1481 },1482 }],1483 true,1484 );1485 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1486 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1487 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1488 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1489 }14901491 /**1492 * Mint multiple NFT tokens1493 * @param signer keyring of signer1494 * @param collectionId ID of collection1495 * @param tokens array of tokens with owner and properties1496 * @example1497 * mintMultipleTokens(aliceKeyring, 10, [{1498 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1499 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1500 * },{1501 * owner: {Ethereum: "0x9F0583DbB855d..."},1502 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1503 * }]);1504 * @returns ```true``` if extrinsic success, otherwise ```false```1505 */1506 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1507 const creationResult = await this.helper.executeExtrinsic(1508 signer,1509 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1510 true,1511 );1512 const collection = this.getCollectionObject(collectionId);1513 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1514 }15151516 /**1517 * Mint multiple NFT tokens with one owner1518 * @param signer keyring of signer1519 * @param collectionId ID of collection1520 * @param owner tokens owner1521 * @param tokens array of tokens with owner and properties1522 * @example1523 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1524 * properties: [{1525 * key: "gender",1526 * value: "female",1527 * },{1528 * key: "age",1529 * value: "33",1530 * }],1531 * }]);1532 * @returns array of newly created tokens1533 */1534 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1535 const rawTokens = [];1536 for (const token of tokens) {1537 const raw = {NFT: {properties: token.properties}};1538 rawTokens.push(raw);1539 }1540 const creationResult = await this.helper.executeExtrinsic(1541 signer,1542 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1543 true,1544 );1545 const collection = this.getCollectionObject(collectionId);1546 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1547 }15481549 /**1550 * Set, change, or remove approved address to transfer the ownership of the NFT.1551 *1552 * @param signer keyring of signer1553 * @param collectionId ID of collection1554 * @param tokenId ID of token1555 * @param toAddressObj address to approve1556 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1557 * @returns ```true``` if extrinsic success, otherwise ```false```1558 */1559 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1560 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1561 }1562}156315641565class RFTGroup extends NFTnRFT {1566 /**1567 * Get collection object1568 * @param collectionId ID of collection1569 * @example getCollectionObject(2);1570 * @returns instance of UniqueRFTCollection1571 */1572 getCollectionObject(collectionId: number): UniqueRFTCollection {1573 return new UniqueRFTCollection(collectionId, this.helper);1574 }15751576 /**1577 * Get token object1578 * @param collectionId ID of collection1579 * @param tokenId ID of token1580 * @example getTokenObject(10, 5);1581 * @returns instance of UniqueNFTToken1582 */1583 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1584 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1585 }15861587 /**1588 * Get top 10 token owners with the largest number of pieces1589 * @param collectionId ID of collection1590 * @param tokenId ID of token1591 * @example getTokenTop10Owners(10, 5);1592 * @returns array of top 10 owners1593 */1594 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1595 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1596 }15971598 /**1599 * Get number of pieces owned by address1600 * @param collectionId ID of collection1601 * @param tokenId ID of token1602 * @param addressObj address token owner1603 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1604 * @returns number of pieces ownerd by address1605 */1606 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1607 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1608 }16091610 /**1611 * Transfer pieces of token to another address1612 * @param signer keyring of signer1613 * @param collectionId ID of collection1614 * @param tokenId ID of token1615 * @param addressObj address of a new owner1616 * @param amount number of pieces to be transfered1617 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1618 * @returns ```true``` if extrinsic success, otherwise ```false```1619 */1620 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1621 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1622 }16231624 /**1625 * Change ownership of some pieces of RFT on behalf of the owner.1626 * @param signer keyring of signer1627 * @param collectionId ID of collection1628 * @param tokenId ID of token1629 * @param fromAddressObj address on behalf of which the token will be sent1630 * @param toAddressObj new token owner1631 * @param amount number of pieces to be transfered1632 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1633 * @returns ```true``` if extrinsic success, otherwise ```false```1634 */1635 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1636 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1637 }16381639 /**1640 * Mint new collection1641 * @param signer keyring of signer1642 * @param collectionOptions Collection options1643 * @example1644 * mintCollection(aliceKeyring, {1645 * name: 'New',1646 * description: 'New collection',1647 * tokenPrefix: 'NEW',1648 * })1649 * @returns object of the created collection1650 */1651 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1652 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1653 }16541655 /**1656 * Mint new token1657 * @param signer keyring of signer1658 * @param data token data1659 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1660 * @returns created token object1661 */1662 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1663 const creationResult = await this.helper.executeExtrinsic(1664 signer,1665 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1666 refungible: {1667 pieces: data.pieces,1668 properties: data.properties,1669 },1670 }],1671 true,1672 );1673 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1674 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1675 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1676 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1677 }16781679 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1680 throw Error('Not implemented');1681 const creationResult = await this.helper.executeExtrinsic(1682 signer,1683 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1684 true, // `Unable to mint RFT tokens for ${label}`,1685 );1686 const collection = this.getCollectionObject(collectionId);1687 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1688 }16891690 /**1691 * Mint multiple RFT tokens with one owner1692 * @param signer keyring of signer1693 * @param collectionId ID of collection1694 * @param owner tokens owner1695 * @param tokens array of tokens with properties and pieces1696 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1697 * @returns array of newly created RFT tokens1698 */1699 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1700 const rawTokens = [];1701 for (const token of tokens) {1702 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1703 rawTokens.push(raw);1704 }1705 const creationResult = await this.helper.executeExtrinsic(1706 signer,1707 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1708 true,1709 );1710 const collection = this.getCollectionObject(collectionId);1711 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1712 }17131714 /**1715 * Destroys a concrete instance of RFT.1716 * @param signer keyring of signer1717 * @param collectionId ID of collection1718 * @param tokenId ID of token1719 * @param amount number of pieces to be burnt1720 * @example burnToken(aliceKeyring, 10, 5);1721 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1722 */1723 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1724 return await super.burnToken(signer, collectionId, tokenId, amount);1725 }17261727 /**1728 * Destroys a concrete instance of RFT on behalf of the owner.1729 * @param signer keyring of signer1730 * @param collectionId ID of collection1731 * @param tokenId ID of token1732 * @param fromAddressObj address on behalf of which the token will be burnt1733 * @param amount number of pieces to be burnt1734 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1735 * @returns ```true``` if extrinsic success, otherwise ```false```1736 */1737 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1738 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1739 }17401741 /**1742 * Set, change, or remove approved address to transfer the ownership of the RFT.1743 *1744 * @param signer keyring of signer1745 * @param collectionId ID of collection1746 * @param tokenId ID of token1747 * @param toAddressObj address to approve1748 * @param amount number of pieces to be approved1749 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1750 * @returns true if the token success, otherwise false1751 */1752 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1753 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1754 }17551756 /**1757 * Get total number of pieces1758 * @param collectionId ID of collection1759 * @param tokenId ID of token1760 * @example getTokenTotalPieces(10, 5);1761 * @returns number of pieces1762 */1763 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1764 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1765 }17661767 /**1768 * Change number of token pieces. Signer must be the owner of all token pieces.1769 * @param signer keyring of signer1770 * @param collectionId ID of collection1771 * @param tokenId ID of token1772 * @param amount new number of pieces1773 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1774 * @returns true if the repartion was success, otherwise false1775 */1776 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1777 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1778 const repartitionResult = await this.helper.executeExtrinsic(1779 signer,1780 'api.tx.unique.repartition', [collectionId, tokenId, amount],1781 true,1782 );1783 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1784 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1785 }1786}178717881789class FTGroup extends CollectionGroup {1790 /**1791 * Get collection object1792 * @param collectionId ID of collection1793 * @example getCollectionObject(2);1794 * @returns instance of UniqueFTCollection1795 */1796 getCollectionObject(collectionId: number): UniqueFTCollection {1797 return new UniqueFTCollection(collectionId, this.helper);1798 }17991800 /**1801 * Mint new fungible collection1802 * @param signer keyring of signer1803 * @param collectionOptions Collection options1804 * @param decimalPoints number of token decimals1805 * @example1806 * mintCollection(aliceKeyring, {1807 * name: 'New',1808 * description: 'New collection',1809 * tokenPrefix: 'NEW',1810 * }, 18)1811 * @returns newly created fungible collection1812 */1813 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1814 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1815 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1816 collectionOptions.mode = {fungible: decimalPoints};1817 for (const key of ['name', 'description', 'tokenPrefix']) {1818 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1819 }1820 const creationResult = await this.helper.executeExtrinsic(1821 signer,1822 'api.tx.unique.createCollectionEx', [collectionOptions],1823 true,1824 );1825 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1826 }18271828 /**1829 * Mint tokens1830 * @param signer keyring of signer1831 * @param collectionId ID of collection1832 * @param owner address owner of new tokens1833 * @param amount amount of tokens to be meanted1834 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1835 * @returns ```true``` if extrinsic success, otherwise ```false```1836 */1837 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1838 const creationResult = await this.helper.executeExtrinsic(1839 signer,1840 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1841 fungible: {1842 value: amount,1843 },1844 }],1845 true, // `Unable to mint fungible tokens for ${label}`,1846 );1847 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1848 }18491850 /**1851 * Mint multiple Fungible tokens with one owner1852 * @param signer keyring of signer1853 * @param collectionId ID of collection1854 * @param owner tokens owner1855 * @param tokens array of tokens with properties and pieces1856 * @returns ```true``` if extrinsic success, otherwise ```false```1857 */1858 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1859 const rawTokens = [];1860 for (const token of tokens) {1861 const raw = {Fungible: {Value: token.value}};1862 rawTokens.push(raw);1863 }1864 const creationResult = await this.helper.executeExtrinsic(1865 signer,1866 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1867 true,1868 );1869 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1870 }18711872 /**1873 * Get the top 10 owners with the largest balance for the Fungible collection1874 * @param collectionId ID of collection1875 * @example getTop10Owners(10);1876 * @returns array of ```ICrossAccountId```1877 */1878 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1879 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1880 }18811882 /**1883 * Get account balance1884 * @param collectionId ID of collection1885 * @param addressObj address of owner1886 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1887 * @returns amount of fungible tokens owned by address1888 */1889 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1890 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1891 }18921893 /**1894 * Transfer tokens to address1895 * @param signer keyring of signer1896 * @param collectionId ID of collection1897 * @param toAddressObj address recipient1898 * @param amount amount of tokens to be sent1899 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1900 * @returns ```true``` if extrinsic success, otherwise ```false```1901 */1902 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1903 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1904 }19051906 /**1907 * Transfer some tokens on behalf of the owner.1908 * @param signer keyring of signer1909 * @param collectionId ID of collection1910 * @param fromAddressObj address on behalf of which tokens will be sent1911 * @param toAddressObj address where token to be sent1912 * @param amount number of tokens to be sent1913 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1914 * @returns ```true``` if extrinsic success, otherwise ```false```1915 */1916 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1917 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1918 }19191920 /**1921 * Destroy some amount of tokens1922 * @param signer keyring of signer1923 * @param collectionId ID of collection1924 * @param amount amount of tokens to be destroyed1925 * @example burnTokens(aliceKeyring, 10, 1000n);1926 * @returns ```true``` if extrinsic success, otherwise ```false```1927 */1928 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1929 return await super.burnToken(signer, collectionId, 0, amount);1930 }19311932 /**1933 * Burn some tokens on behalf of the owner.1934 * @param signer keyring of signer1935 * @param collectionId ID of collection1936 * @param fromAddressObj address on behalf of which tokens will be burnt1937 * @param amount amount of tokens to be burnt1938 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1939 * @returns ```true``` if extrinsic success, otherwise ```false```1940 */1941 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1942 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1943 }19441945 /**1946 * Get total collection supply1947 * @param collectionId1948 * @returns1949 */1950 async getTotalPieces(collectionId: number): Promise<bigint> {1951 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1952 }19531954 /**1955 * Set, change, or remove approved address to transfer tokens.1956 *1957 * @param signer keyring of signer1958 * @param collectionId ID of collection1959 * @param toAddressObj address to be approved1960 * @param amount amount of tokens to be approved1961 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1962 * @returns ```true``` if extrinsic success, otherwise ```false```1963 */1964 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1965 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1966 }19671968 /**1969 * Get amount of fungible tokens approved to transfer1970 * @param collectionId ID of collection1971 * @param fromAddressObj owner of tokens1972 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1973 * @returns number of tokens approved for the transfer1974 */1975 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1976 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1977 }1978}197919801981class ChainGroup extends HelperGroup {1982 /**1983 * Get system properties of a chain1984 * @example getChainProperties();1985 * @returns ss58Format, token decimals, and token symbol1986 */1987 getChainProperties(): IChainProperties {1988 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1989 return {1990 ss58Format: properties.ss58Format.toJSON(),1991 tokenDecimals: properties.tokenDecimals.toJSON(),1992 tokenSymbol: properties.tokenSymbol.toJSON(),1993 };1994 }19951996 /**1997 * Get chain header1998 * @example getLatestBlockNumber();1999 * @returns the number of the last block2000 */2001 async getLatestBlockNumber(): Promise<number> {2002 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2003 }20042005 /**2006 * Get block hash by block number2007 * @param blockNumber number of block2008 * @example getBlockHashByNumber(12345);2009 * @returns hash of a block2010 */2011 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2012 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2013 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2014 return blockHash;2015 }20162017 // TODO add docs2018 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2019 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2020 if (!blockHash) return null;2021 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2022 }20232024 /**2025 * Get account nonce2026 * @param address substrate address2027 * @example getNonce("5GrwvaEF5zXb26Fz...");2028 * @returns number, account's nonce2029 */2030 async getNonce(address: TSubstrateAccount): Promise<number> {2031 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();2032 }2033}203420352036class BalanceGroup extends HelperGroup {2037 getCollectionCreationPrice(): bigint {2038 return 2n * this.helper.balance.getOneTokenNominal();2039 }2040 /**2041 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2042 * @example getOneTokenNominal()2043 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2044 */2045 getOneTokenNominal(): bigint {2046 const chainProperties = this.helper.chain.getChainProperties();2047 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2048 }20492050 /**2051 * Get substrate address balance2052 * @param address substrate address2053 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2054 * @returns amount of tokens on address2055 */2056 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2057 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2058 }20592060 /**2061 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2062 * @param address substrate address2063 * @returns2064 */2065 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2066 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2067 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2068 }20692070 /**2071 * Get ethereum address balance2072 * @param address ethereum address2073 * @example getEthereum("0x9F0583DbB855d...")2074 * @returns amount of tokens on address2075 */2076 async getEthereum(address: TEthereumAccount): Promise<bigint> {2077 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2078 }20792080 /**2081 * Transfer tokens to substrate address2082 * @param signer keyring of signer2083 * @param address substrate address of a recipient2084 * @param amount amount of tokens to be transfered2085 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2086 * @returns ```true``` if extrinsic success, otherwise ```false```2087 */2088 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2089 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);20902091 let transfer = {from: null, to: null, amount: 0n} as any;2092 result.result.events.forEach(({event: {data, method, section}}) => {2093 if ((section === 'balances') && (method === 'Transfer')) {2094 transfer = {2095 from: this.helper.address.normalizeSubstrate(data[0]),2096 to: this.helper.address.normalizeSubstrate(data[1]),2097 amount: BigInt(data[2]),2098 };2099 }2100 });2101 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2102 && this.helper.address.normalizeSubstrate(address) === transfer.to 2103 && BigInt(amount) === transfer.amount;2104 return isSuccess;2105 }2106}210721082109class AddressGroup extends HelperGroup {2110 /**2111 * Normalizes the address to the specified ss58 format, by default ```42```.2112 * @param address substrate address2113 * @param ss58Format format for address conversion, by default ```42```2114 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2115 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2116 */2117 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2118 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2119 }21202121 /**2122 * Get address in the connected chain format2123 * @param address substrate address2124 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2125 * @returns address in chain format2126 */2127 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2128 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2129 }21302131 /**2132 * Get substrate mirror of an ethereum address2133 * @param ethAddress ethereum address2134 * @param toChainFormat false for normalized account2135 * @example ethToSubstrate('0x9F0583DbB855d...')2136 * @returns substrate mirror of a provided ethereum address2137 */2138 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2139 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2140 }21412142 /**2143 * Get ethereum mirror of a substrate address2144 * @param subAddress substrate account2145 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2146 * @returns ethereum mirror of a provided substrate address2147 */2148 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2149 return CrossAccountId.translateSubToEth(subAddress);2150 }2151}21522153class StakingGroup extends HelperGroup {2154 /**2155 * Stake tokens for App Promotion2156 * @param signer keyring of signer2157 * @param amountToStake amount of tokens to stake2158 * @param label extra label for log2159 * @returns2160 */2161 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2162 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2163 const stakeResult = await this.helper.executeExtrinsic(2164 signer, 'api.tx.appPromotion.stake',2165 [amountToStake], true,2166 );2167 // TODO extract info from stakeResult2168 return true;2169 }21702171 /**2172 * Unstake tokens for App Promotion2173 * @param signer keyring of signer2174 * @param amountToUnstake amount of tokens to unstake2175 * @param label extra label for log2176 * @returns block number where balances will be unlocked2177 */2178 async unstake(signer: TSigner, label?: string): Promise<number> {2179 if(typeof label === 'undefined') label = `${signer.address}`;2180 const unstakeResult = await this.helper.executeExtrinsic(2181 signer, 'api.tx.appPromotion.unstake',2182 [], true,2183 );2184 // TODO extract block number fron events2185 return 1;2186 }21872188 /**2189 * Get total staked amount for address2190 * @param address substrate or ethereum address2191 * @returns total staked amount2192 */2193 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2194 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2195 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2196 }21972198 /**2199 * Get total staked per block2200 * @param address substrate or ethereum address2201 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2202 */2203 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2204 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2205 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2206 return { 2207 block: block.toBigInt(),2208 amount: amount.toBigInt(),2209 };2210 });2211 }22122213 /**2214 * Get total pending unstake amount for address2215 * @param address substrate or ethereum address2216 * @returns total pending unstake amount2217 */2218 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2219 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2220 }22212222 /**2223 * Get pending unstake amount per block for address2224 * @param address substrate or ethereum address2225 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2226 */2227 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2228 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2229 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2230 return {2231 block: block.toBigInt(),2232 amount: amount.toBigInt(),2233 };2234 });2235 return result;2236 }2237}22382239export class UniqueHelper extends ChainHelperBase {2240 chain: ChainGroup;2241 balance: BalanceGroup;2242 address: AddressGroup;2243 collection: CollectionGroup;2244 nft: NFTGroup;2245 rft: RFTGroup;2246 ft: FTGroup;2247 staking: StakingGroup;22482249 constructor(logger?: ILogger) {2250 super(logger);2251 this.chain = new ChainGroup(this);2252 this.balance = new BalanceGroup(this);2253 this.address = new AddressGroup(this);2254 this.collection = new CollectionGroup(this);2255 this.nft = new NFTGroup(this);2256 this.rft = new RFTGroup(this);2257 this.ft = new FTGroup(this);2258 this.staking = new StakingGroup(this);2259 }2260}226122622263export class UniqueBaseCollection {2264 helper: UniqueHelper;2265 collectionId: number;22662267 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2268 this.collectionId = collectionId;2269 this.helper = uniqueHelper;2270 }22712272 async getData() {2273 return await this.helper.collection.getData(this.collectionId);2274 }22752276 async getLastTokenId() {2277 return await this.helper.collection.getLastTokenId(this.collectionId);2278 }22792280 async doesTokenExist(tokenId: number) {2281 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2282 }22832284 async getAdmins() {2285 return await this.helper.collection.getAdmins(this.collectionId);2286 }22872288 async getAllowList() {2289 return await this.helper.collection.getAllowList(this.collectionId);2290 }22912292 async getEffectiveLimits() {2293 return await this.helper.collection.getEffectiveLimits(this.collectionId);2294 }22952296 async getProperties(propertyKeys?: string[] | null) {2297 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2298 }22992300 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2301 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2302 }23032304 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2305 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2306 }23072308 async confirmSponsorship(signer: TSigner) {2309 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2310 }23112312 async removeSponsor(signer: TSigner) {2313 return await this.helper.collection.removeSponsor(signer, this.collectionId);2314 }23152316 async setLimits(signer: TSigner, limits: ICollectionLimits) {2317 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2318 }23192320 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2321 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2322 }23232324 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2325 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2326 }23272328 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2329 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2330 }23312332 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2333 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2334 }23352336 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2337 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2338 }23392340 async setProperties(signer: TSigner, properties: IProperty[]) {2341 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2342 }23432344 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2345 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2346 }23472348 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2349 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2350 }23512352 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2353 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2354 }23552356 async disableNesting(signer: TSigner) {2357 return await this.helper.collection.disableNesting(signer, this.collectionId);2358 }23592360 async burn(signer: TSigner) {2361 return await this.helper.collection.burn(signer, this.collectionId);2362 }2363}236423652366export class UniqueNFTCollection extends UniqueBaseCollection {2367 getTokenObject(tokenId: number) {2368 return new UniqueNFToken(tokenId, this);2369 }23702371 async getTokensByAddress(addressObj: ICrossAccountId) {2372 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2373 }23742375 async getToken(tokenId: number, blockHashAt?: string) {2376 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2377 }23782379 async getTokenOwner(tokenId: number, blockHashAt?: string) {2380 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2381 }23822383 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2384 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2385 }23862387 async getTokenChildren(tokenId: number, blockHashAt?: string) {2388 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2389 }23902391 async getPropertyPermissions(propertyKeys: string[] | null = null) {2392 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2393 }23942395 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2396 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2397 }23982399 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2400 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2401 }24022403 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2404 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2405 }24062407 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2408 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2409 }24102411 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2412 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2413 }24142415 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2416 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2417 }24182419 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2420 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2421 }24222423 async burnToken(signer: TSigner, tokenId: number) {2424 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2425 }24262427 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2428 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2429 }24302431 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2432 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2433 }24342435 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2436 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2437 }24382439 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2440 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2441 }24422443 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2444 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2445 }24462447 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2448 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2449 }2450}245124522453export class UniqueRFTCollection extends UniqueBaseCollection {2454 getTokenObject(tokenId: number) {2455 return new UniqueRFToken(tokenId, this);2456 }24572458 async getToken(tokenId: number, blockHashAt?: string) {2459 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2460 }24612462 async getTokensByAddress(addressObj: ICrossAccountId) {2463 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2464 }24652466 async getTop10TokenOwners(tokenId: number) {2467 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2468 }24692470 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2471 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2472 }24732474 async getTokenTotalPieces(tokenId: number) {2475 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2476 }24772478 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2479 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2480 }24812482 async getPropertyPermissions(propertyKeys: string[] | null = null) {2483 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2484 }24852486 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2487 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2488 }24892490 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2491 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2492 }24932494 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2495 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2496 }24972498 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2499 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2500 }25012502 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2503 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2504 }25052506 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2507 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2508 }25092510 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2511 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2512 }25132514 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2515 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2516 }25172518 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2519 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2520 }25212522 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2523 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2524 }25252526 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2527 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2528 }25292530 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2531 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2532 }2533}253425352536export class UniqueFTCollection extends UniqueBaseCollection {2537 async getBalance(addressObj: ICrossAccountId) {2538 return await this.helper.ft.getBalance(this.collectionId, addressObj);2539 }25402541 async getTotalPieces() {2542 return await this.helper.ft.getTotalPieces(this.collectionId);2543 }25442545 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2546 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2547 }25482549 async getTop10Owners() {2550 return await this.helper.ft.getTop10Owners(this.collectionId);2551 }25522553 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2554 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2555 }25562557 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2558 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2559 }25602561 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2562 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2563 }25642565 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2566 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2567 }25682569 async burnTokens(signer: TSigner, amount=1n) {2570 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2571 }25722573 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2574 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2575 }25762577 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2578 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2579 }2580}258125822583export class UniqueBaseToken {2584 collection: UniqueNFTCollection | UniqueRFTCollection;2585 collectionId: number;2586 tokenId: number;25872588 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2589 this.collection = collection;2590 this.collectionId = collection.collectionId;2591 this.tokenId = tokenId;2592 }25932594 async getNextSponsored(addressObj: ICrossAccountId) {2595 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2596 }25972598 async getProperties(propertyKeys?: string[] | null) {2599 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2600 }26012602 async setProperties(signer: TSigner, properties: IProperty[]) {2603 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2604 }26052606 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2607 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2608 }26092610 async doesExist() {2611 return await this.collection.doesTokenExist(this.tokenId);2612 }26132614 nestingAccount() {2615 return this.collection.helper.util.getTokenAccount(this);2616 }2617}261826192620export class UniqueNFToken extends UniqueBaseToken {2621 collection: UniqueNFTCollection;26222623 constructor(tokenId: number, collection: UniqueNFTCollection) {2624 super(tokenId, collection);2625 this.collection = collection;2626 }26272628 async getData(blockHashAt?: string) {2629 return await this.collection.getToken(this.tokenId, blockHashAt);2630 }26312632 async getOwner(blockHashAt?: string) {2633 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2634 }26352636 async getTopmostOwner(blockHashAt?: string) {2637 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2638 }26392640 async getChildren(blockHashAt?: string) {2641 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2642 }26432644 async nest(signer: TSigner, toTokenObj: IToken) {2645 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2646 }26472648 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2649 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2650 }26512652 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2653 return await this.collection.transferToken(signer, this.tokenId, addressObj);2654 }26552656 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2657 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2658 }26592660 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2661 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2662 }26632664 async isApproved(toAddressObj: ICrossAccountId) {2665 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2666 }26672668 async burn(signer: TSigner) {2669 return await this.collection.burnToken(signer, this.tokenId);2670 }26712672 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2673 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2674 }2675}26762677export class UniqueRFToken extends UniqueBaseToken {2678 collection: UniqueRFTCollection;26792680 constructor(tokenId: number, collection: UniqueRFTCollection) {2681 super(tokenId, collection);2682 this.collection = collection;2683 }26842685 async getData(blockHashAt?: string) {2686 return await this.collection.getToken(this.tokenId, blockHashAt);2687 }26882689 async getTop10Owners() {2690 return await this.collection.getTop10TokenOwners(this.tokenId);2691 }26922693 async getBalance(addressObj: ICrossAccountId) {2694 return await this.collection.getTokenBalance(this.tokenId, addressObj);2695 }26962697 async getTotalPieces() {2698 return await this.collection.getTokenTotalPieces(this.tokenId);2699 }27002701 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2702 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2703 }27042705 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2706 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2707 }27082709 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2710 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2711 }27122713 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2714 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2715 }27162717 async repartition(signer: TSigner, amount: bigint) {2718 return await this.collection.repartitionToken(signer, this.tokenId, amount);2719 }27202721 async burn(signer: TSigner, amount=1n) {2722 return await this.collection.burnToken(signer, this.tokenId, amount);2723 }27242725 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2726 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2727 }2728}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 // If ith character is 8 to f then make it uppercase84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255}256257class UniqueEventHelper {258 private static extractIndex(index: any): [number, number] | string {259 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];260 return index.toJSON();261 }262263 private static extractSub(data: any, subTypes: any): {[key: string]: any} {264 let obj: any = {};265 let index = 0;266267 if (data.entries) {268 for(const [key, value] of data.entries()) {269 obj[key] = this.extractData(value, subTypes[index]);270 index++;271 }272 } else obj = data.toJSON();273274 return obj;275 }276 277 private static extractData(data: any, type: any): any {278 if(!type) return data.toHuman();279 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();280 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();281 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);282 return data.toHuman();283 }284285 public static extractEvents(records: ITransactionResult): IEvent[] {286 const parsedEvents: IEvent[] = [];287288 records.result.events.forEach((record) => {289 const {event, phase} = record;290 const types = (event as any).typeDef;291292 const eventData: IEvent = {293 section: event.section.toString(),294 method: event.method.toString(),295 index: this.extractIndex(event.index),296 data: [],297 phase: phase.toJSON(),298 };299300 event.data.forEach((val: any, index: number) => {301 eventData.data.push(this.extractData(val, types[index]));302 });303304 parsedEvents.push(eventData);305 });306307 return parsedEvents;308 }309}310311class ChainHelperBase {312 transactionStatus = UniqueUtil.transactionStatus;313 chainLogType = UniqueUtil.chainLogType;314 util: typeof UniqueUtil;315 eventHelper: typeof UniqueEventHelper;316 logger: ILogger;317 api: ApiPromise | null;318 forcedNetwork: TUniqueNetworks | null;319 network: TUniqueNetworks | null;320 chainLog: IUniqueHelperLog[];321 children: ChainHelperBase[];322323 constructor(logger?: ILogger) {324 this.util = UniqueUtil;325 this.eventHelper = UniqueEventHelper;326 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();327 this.logger = logger;328 this.api = null;329 this.forcedNetwork = null;330 this.network = null;331 this.chainLog = [];332 this.children = [];333 }334335 getApi(): ApiPromise {336 if(this.api === null) throw Error('API not initialized');337 return this.api;338 }339340 clearChainLog(): void {341 this.chainLog = [];342 }343344 forceNetwork(value: TUniqueNetworks): void {345 this.forcedNetwork = value;346 }347348 async connect(wsEndpoint: string, listeners?: IApiListeners) {349 if (this.api !== null) throw Error('Already connected');350 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);351 this.api = api;352 this.network = network;353 }354355 async disconnect() {356 for (const child of this.children) {357 child.clearApi();358 }359360 if (this.api === null) return;361 await this.api.disconnect();362 this.clearApi();363 }364365 clearApi() {366 this.api = null;367 this.network = null;368 }369370 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {371 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;372 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;373 return 'opal';374 }375376 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {377 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});378 await api.isReady;379380 const network = await this.detectNetwork(api);381382 await api.disconnect();383384 return network;385 }386387 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{388 api: ApiPromise;389 network: TUniqueNetworks;390 }> {391 if(typeof network === 'undefined' || network === null) network = 'opal';392 const supportedRPC = {393 opal: {394 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,395 },396 quartz: {397 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,398 },399 unique: {400 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,401 },402 };403 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);404 const rpc = supportedRPC[network];405406 // TODO: investigate how to replace rpc in runtime407 // api._rpcCore.addUserInterfaces(rpc);408409 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});410411 await api.isReadyOrError;412413 if (typeof listeners === 'undefined') listeners = {};414 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {415 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;416 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);417 }418419 return {api, network};420 }421422 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {423 const {events, status} = data;424 if (status.isReady) {425 return this.transactionStatus.NOT_READY;426 }427 if (status.isBroadcast) {428 return this.transactionStatus.NOT_READY;429 }430 if (status.isInBlock || status.isFinalized) {431 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');432 if (errors.length > 0) {433 return this.transactionStatus.FAIL;434 }435 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {436 return this.transactionStatus.SUCCESS;437 }438 }439440 return this.transactionStatus.FAIL;441 }442443 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {444 const sign = (callback: any) => {445 if(options !== null) return transaction.signAndSend(sender, options, callback);446 return transaction.signAndSend(sender, callback);447 };448 // eslint-disable-next-line no-async-promise-executor449 return new Promise(async (resolve, reject) => {450 try {451 const unsub = await sign((result: any) => {452 const status = this.getTransactionStatus(result);453454 if (status === this.transactionStatus.SUCCESS) {455 this.logger.log(`${label} successful`);456 unsub();457 resolve({result, status});458 } else if (status === this.transactionStatus.FAIL) {459 let moduleError = null;460461 if (result.hasOwnProperty('dispatchError')) {462 const dispatchError = result['dispatchError'];463464 if (dispatchError) {465 if (dispatchError.isModule) {466 const modErr = dispatchError.asModule;467 const errorMeta = dispatchError.registry.findMetaError(modErr);468469 moduleError = `${errorMeta.section}.${errorMeta.name}`;470 } else {471 moduleError = dispatchError.toHuman();472 }473 } else {474 this.logger.log(result, this.logger.level.ERROR);475 }476 }477478 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);479 unsub();480 reject({status, moduleError, result});481 }482 });483 } catch (e) {484 this.logger.log(e, this.logger.level.ERROR);485 reject(e);486 }487 });488 }489490 constructApiCall(apiCall: string, params: any[]) {491 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);492 let call = this.getApi() as any;493 for(const part of apiCall.slice(4).split('.')) {494 call = call[part];495 }496 return call(...params);497 }498499 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {500 if(this.api === null) throw Error('API not initialized');501 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);502503 const startTime = (new Date()).getTime();504 let result: ITransactionResult;505 let events: IEvent[] = [];506 try {507 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;508 events = this.eventHelper.extractEvents(result);509 }510 catch(e) {511 if(!(e as object).hasOwnProperty('status')) throw e;512 result = e as ITransactionResult;513 }514515 const endTime = (new Date()).getTime();516517 const log = {518 executedAt: endTime,519 executionTime: endTime - startTime,520 type: this.chainLogType.EXTRINSIC,521 status: result.status,522 call: extrinsic,523 signer: this.getSignerAddress(sender),524 params,525 } as IUniqueHelperLog;526527 if(result.status !== this.transactionStatus.SUCCESS) {528 if (result.moduleError) log.moduleError = result.moduleError;529 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;530 }531 if(events.length > 0) log.events = events;532533 this.chainLog.push(log);534535 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {536 if (result.moduleError) throw Error(`${result.moduleError}`);537 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));538 }539 return result;540 }541542 async callRpc(rpc: string, params?: any[]) {543 if(typeof params === 'undefined') params = [];544 if(this.api === null) throw Error('API not initialized');545 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);546547 const startTime = (new Date()).getTime();548 let result;549 let error = null;550 const log = {551 type: this.chainLogType.RPC,552 call: rpc,553 params,554 } as IUniqueHelperLog;555556 try {557 result = await this.constructApiCall(rpc, params);558 }559 catch(e) {560 error = e;561 }562563 const endTime = (new Date()).getTime();564565 log.executedAt = endTime;566 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';567 log.executionTime = endTime - startTime;568569 this.chainLog.push(log);570571 if(error !== null) throw error;572573 return result;574 }575576 getSignerAddress(signer: IKeyringPair | string): string {577 if(typeof signer === 'string') return signer;578 return signer.address;579 }580581 fetchAllPalletNames(): string[] {582 if(this.api === null) throw Error('API not initialized');583 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());584 }585586 fetchMissingPalletNames(requiredPallets: string[]): string[] {587 const palletNames = this.fetchAllPalletNames();588 return requiredPallets.filter(p => !palletNames.includes(p));589 }590}591592593class HelperGroup {594 helper: UniqueHelper;595596 constructor(uniqueHelper: UniqueHelper) {597 this.helper = uniqueHelper;598 }599}600601602class CollectionGroup extends HelperGroup {603 /**604 * Get number of blocks when sponsored transaction is available.605 *606 * @param collectionId ID of collection607 * @param tokenId ID of token608 * @param addressObj address for which the sponsorship is checked609 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});610 * @returns number of blocks or null if sponsorship hasn't been set611 */612 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {613 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();614 }615616 /**617 * Get the number of created collections.618 *619 * @returns number of created collections620 */621 async getTotalCount(): Promise<number> {622 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();623 }624625 /**626 * Get information about the collection with additional data,627 * including the number of tokens it contains, its administrators,628 * the normalized address of the collection's owner, and decoded name and description.629 *630 * @param collectionId ID of collection631 * @example await getData(2)632 * @returns collection information object633 */634 async getData(collectionId: number): Promise<{635 id: number;636 name: string;637 description: string;638 tokensCount: number;639 admins: CrossAccountId[];640 normalizedOwner: TSubstrateAccount;641 raw: any642 } | null> {643 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);644 const humanCollection = collection.toHuman(), collectionData = {645 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],646 raw: humanCollection,647 } as any, jsonCollection = collection.toJSON();648 if (humanCollection === null) return null;649 collectionData.raw.limits = jsonCollection.limits;650 collectionData.raw.permissions = jsonCollection.permissions;651 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);652 for (const key of ['name', 'description']) {653 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);654 }655656 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))657 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)658 : 0;659 collectionData.admins = await this.getAdmins(collectionId);660661 return collectionData;662 }663664 /**665 * Get the addresses of the collection's administrators, optionally normalized.666 *667 * @param collectionId ID of collection668 * @param normalize whether to normalize the addresses to the default ss58 format669 * @example await getAdmins(1)670 * @returns array of administrators671 */672 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {673 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();674675 return normalize676 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())677 : admins;678 }679680 /**681 * Get the addresses added to the collection allow-list, optionally normalized.682 * @param collectionId ID of collection683 * @param normalize whether to normalize the addresses to the default ss58 format684 * @example await getAllowList(1)685 * @returns array of allow-listed addresses686 */687 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {688 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();689 return normalize690 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())691 : allowListed;692 }693694 /**695 * Get the effective limits of the collection instead of null for default values696 *697 * @param collectionId ID of collection698 * @example await getEffectiveLimits(2)699 * @returns object of collection limits700 */701 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {702 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();703 }704705 /**706 * Burns the collection if the signer has sufficient permissions and collection is empty.707 *708 * @param signer keyring of signer709 * @param collectionId ID of collection710 * @example await helper.collection.burn(aliceKeyring, 3);711 * @returns ```true``` if extrinsic success, otherwise ```false```712 */713 async burn(signer: TSigner, collectionId: number): Promise<boolean> {714 const result = await this.helper.executeExtrinsic(715 signer,716 'api.tx.unique.destroyCollection', [collectionId],717 true,718 );719720 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');721 }722723 /**724 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.725 *726 * @param signer keyring of signer727 * @param collectionId ID of collection728 * @param sponsorAddress Sponsor substrate address729 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")730 * @returns ```true``` if extrinsic success, otherwise ```false```731 */732 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {733 const result = await this.helper.executeExtrinsic(734 signer,735 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],736 true,737 );738739 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');740 }741742 /**743 * Confirms consent to sponsor the collection on behalf of the signer.744 *745 * @param signer keyring of signer746 * @param collectionId ID of collection747 * @example confirmSponsorship(aliceKeyring, 10)748 * @returns ```true``` if extrinsic success, otherwise ```false```749 */750 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {751 const result = await this.helper.executeExtrinsic(752 signer,753 'api.tx.unique.confirmSponsorship', [collectionId],754 true,755 );756757 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');758 }759760 /**761 * Removes the sponsor of a collection, regardless if it consented or not.762 *763 * @param signer keyring of signer764 * @param collectionId ID of collection765 * @example removeSponsor(aliceKeyring, 10)766 * @returns ```true``` if extrinsic success, otherwise ```false```767 */768 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {769 const result = await this.helper.executeExtrinsic(770 signer,771 'api.tx.unique.removeCollectionSponsor', [collectionId],772 true,773 );774775 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');776 }777778 /**779 * Sets the limits of the collection. At least one limit must be specified for a correct call.780 *781 * @param signer keyring of signer782 * @param collectionId ID of collection783 * @param limits collection limits object784 * @example785 * await setLimits(786 * aliceKeyring,787 * 10,788 * {789 * sponsorTransferTimeout: 0,790 * ownerCanDestroy: false791 * }792 * )793 * @returns ```true``` if extrinsic success, otherwise ```false```794 */795 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {796 const result = await this.helper.executeExtrinsic(797 signer,798 'api.tx.unique.setCollectionLimits', [collectionId, limits],799 true,800 );801802 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');803 }804805 /**806 * Changes the owner of the collection to the new Substrate address.807 *808 * @param signer keyring of signer809 * @param collectionId ID of collection810 * @param ownerAddress substrate address of new owner811 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")812 * @returns ```true``` if extrinsic success, otherwise ```false```813 */814 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {815 const result = await this.helper.executeExtrinsic(816 signer,817 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],818 true,819 );820821 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');822 }823824 /**825 * Adds a collection administrator.826 *827 * @param signer keyring of signer828 * @param collectionId ID of collection829 * @param adminAddressObj Administrator address (substrate or ethereum)830 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})831 * @returns ```true``` if extrinsic success, otherwise ```false```832 */833 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {834 const result = await this.helper.executeExtrinsic(835 signer,836 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],837 true,838 );839840 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');841 }842843 /**844 * Removes a collection administrator.845 *846 * @param signer keyring of signer847 * @param collectionId ID of collection848 * @param adminAddressObj Administrator address (substrate or ethereum)849 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})850 * @returns ```true``` if extrinsic success, otherwise ```false```851 */852 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {853 const result = await this.helper.executeExtrinsic(854 signer,855 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],856 true,857 );858859 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');860 }861862 /**863 * Check if user is in allow list.864 * 865 * @param collectionId ID of collection866 * @param user Account to check867 * @example await getAdmins(1)868 * @returns is user in allow list869 */870 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {871 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();872 }873874 /**875 * Adds an address to allow list876 * @param signer keyring of signer877 * @param collectionId ID of collection878 * @param addressObj address to add to the allow list879 * @returns ```true``` if extrinsic success, otherwise ```false```880 */881 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {882 const result = await this.helper.executeExtrinsic(883 signer,884 'api.tx.unique.addToAllowList', [collectionId, addressObj],885 true,886 );887888 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');889 }890891 /**892 * Removes an address from allow list893 *894 * @param signer keyring of signer895 * @param collectionId ID of collection896 * @param addressObj address to remove from the allow list897 * @returns ```true``` if extrinsic success, otherwise ```false```898 */899 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {900 const result = await this.helper.executeExtrinsic(901 signer,902 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],903 true,904 );905906 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');907 }908909 /**910 * Sets onchain permissions for selected collection.911 *912 * @param signer keyring of signer913 * @param collectionId ID of collection914 * @param permissions collection permissions object915 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});916 * @returns ```true``` if extrinsic success, otherwise ```false```917 */918 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {919 const result = await this.helper.executeExtrinsic(920 signer,921 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],922 true,923 );924925 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');926 }927928 /**929 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.930 *931 * @param signer keyring of signer932 * @param collectionId ID of collection933 * @param permissions nesting permissions object934 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});935 * @returns ```true``` if extrinsic success, otherwise ```false```936 */937 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {938 return await this.setPermissions(signer, collectionId, {nesting: permissions});939 }940941 /**942 * Disables nesting for selected collection.943 *944 * @param signer keyring of signer945 * @param collectionId ID of collection946 * @example disableNesting(aliceKeyring, 10);947 * @returns ```true``` if extrinsic success, otherwise ```false```948 */949 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {950 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});951 }952953 /**954 * Sets onchain properties to the collection.955 *956 * @param signer keyring of signer957 * @param collectionId ID of collection958 * @param properties array of property objects959 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);960 * @returns ```true``` if extrinsic success, otherwise ```false```961 */962 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {963 const result = await this.helper.executeExtrinsic(964 signer,965 'api.tx.unique.setCollectionProperties', [collectionId, properties],966 true,967 );968969 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');970 }971972 /**973 * Get collection properties.974 * 975 * @param collectionId ID of collection976 * @param propertyKeys optionally filter the returned properties to only these keys977 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);978 * @returns array of key-value pairs979 */980 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {981 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();982 }983984 /**985 * Deletes onchain properties from the collection.986 *987 * @param signer keyring of signer988 * @param collectionId ID of collection989 * @param propertyKeys array of property keys to delete990 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);991 * @returns ```true``` if extrinsic success, otherwise ```false```992 */993 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {994 const result = await this.helper.executeExtrinsic(995 signer,996 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],997 true,998 );9991000 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1001 }10021003 /**1004 * Changes the owner of the token.1005 *1006 * @param signer keyring of signer1007 * @param collectionId ID of collection1008 * @param tokenId ID of token1009 * @param addressObj address of a new owner1010 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1011 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1012 * @returns true if the token success, otherwise false1013 */1014 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1015 const result = await this.helper.executeExtrinsic(1016 signer,1017 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1018 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1019 );10201021 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1022 }10231024 /**1025 *1026 * Change ownership of a token(s) on behalf of the owner.1027 *1028 * @param signer keyring of signer1029 * @param collectionId ID of collection1030 * @param tokenId ID of token1031 * @param fromAddressObj address on behalf of which the token will be sent1032 * @param toAddressObj new token owner1033 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1034 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1035 * @returns true if the token success, otherwise false1036 */1037 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1041 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1042 );1043 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1044 }10451046 /**1047 *1048 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1049 *1050 * @param signer keyring of signer1051 * @param collectionId ID of collection1052 * @param tokenId ID of token1053 * @param amount amount of tokens to be burned. For NFT must be set to 1n1054 * @example burnToken(aliceKeyring, 10, 5);1055 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1056 */1057 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1058 const burnResult = await this.helper.executeExtrinsic(1059 signer,1060 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1061 true, // `Unable to burn token for ${label}`,1062 );1063 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1064 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1065 return burnedTokens.success;1066 }10671068 /**1069 * Destroys a concrete instance of NFT on behalf of the owner1070 *1071 * @param signer keyring of signer1072 * @param collectionId ID of collection1073 * @param tokenId ID of token1074 * @param fromAddressObj address on behalf of which the token will be burnt1075 * @param amount amount of tokens to be burned. For NFT must be set to 1n1076 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1077 * @returns ```true``` if extrinsic success, otherwise ```false```1078 */1079 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1080 const burnResult = await this.helper.executeExtrinsic(1081 signer,1082 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1083 true, // `Unable to burn token from for ${label}`,1084 );1085 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1086 return burnedTokens.success && burnedTokens.tokens.length > 0;1087 }10881089 /**1090 * Set, change, or remove approved address to transfer the ownership of the NFT.1091 *1092 * @param signer keyring of signer1093 * @param collectionId ID of collection1094 * @param tokenId ID of token1095 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1096 * @param amount amount of token to be approved. For NFT must be set to 1n1097 * @returns ```true``` if extrinsic success, otherwise ```false```1098 */1099 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1100 const approveResult = await this.helper.executeExtrinsic(1101 signer,1102 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1103 true, // `Unable to approve token for ${label}`,1104 );11051106 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1107 }11081109 /**1110 * Get the amount of token pieces approved to transfer or burn. Normally 0.1111 *1112 * @param collectionId ID of collection1113 * @param tokenId ID of token1114 * @param toAccountObj address which is approved to use token pieces1115 * @param fromAccountObj address which may have allowed the use of its owned tokens1116 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1117 * @returns number of approved to transfer pieces1118 */1119 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1120 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1121 }11221123 /**1124 * Get the last created token ID in a collection1125 *1126 * @param collectionId ID of collection1127 * @example getLastTokenId(10);1128 * @returns id of the last created token1129 */1130 async getLastTokenId(collectionId: number): Promise<number> {1131 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1132 }11331134 /**1135 * Check if token exists1136 *1137 * @param collectionId ID of collection1138 * @param tokenId ID of token1139 * @example doesTokenExist(10, 20);1140 * @returns true if the token exists, otherwise false1141 */1142 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1143 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1144 }1145}11461147class NFTnRFT extends CollectionGroup {1148 /**1149 * Get tokens owned by account1150 *1151 * @param collectionId ID of collection1152 * @param addressObj tokens owner1153 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1154 * @returns array of token ids owned by account1155 */1156 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1157 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1158 }11591160 /**1161 * Get token data1162 *1163 * @param collectionId ID of collection1164 * @param tokenId ID of token1165 * @param propertyKeys optionally filter the token properties to only these keys1166 * @param blockHashAt optionally query the data at some block with this hash1167 * @example getToken(10, 5);1168 * @returns human readable token data1169 */1170 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1171 properties: IProperty[];1172 owner: CrossAccountId;1173 normalizedOwner: CrossAccountId;1174 }| null> {1175 let tokenData;1176 if(typeof blockHashAt === 'undefined') {1177 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1178 }1179 else {1180 if(propertyKeys.length == 0) {1181 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1182 if(!collection) return null;1183 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1184 }1185 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1186 }1187 tokenData = tokenData.toHuman();1188 if (tokenData === null || tokenData.owner === null) return null;1189 const owner = {} as any;1190 for (const key of Object.keys(tokenData.owner)) {1191 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1192 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1193 : tokenData.owner[key];1194 }1195 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1196 return tokenData;1197 }11981199 /**1200 * Set permissions to change token properties1201 *1202 * @param signer keyring of signer1203 * @param collectionId ID of collection1204 * @param permissions permissions to change a property by the collection admin or token owner1205 * @example setTokenPropertyPermissions(1206 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1207 * )1208 * @returns true if extrinsic success otherwise false1209 */1210 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1211 const result = await this.helper.executeExtrinsic(1212 signer,1213 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1214 true,1215 );12161217 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1218 }12191220 /**1221 * Get token property permissions.1222 * 1223 * @param collectionId ID of collection1224 * @param propertyKeys optionally filter the returned property permissions to only these keys1225 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1226 * @returns array of key-permission pairs1227 */1228 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1229 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1230 }12311232 /**1233 * Set token properties1234 *1235 * @param signer keyring of signer1236 * @param collectionId ID of collection1237 * @param tokenId ID of token1238 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1239 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1240 * @returns ```true``` if extrinsic success, otherwise ```false```1241 */1242 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1243 const result = await this.helper.executeExtrinsic(1244 signer,1245 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1246 true,1247 );12481249 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1250 }12511252 /**1253 * Get properties, metadata assigned to a token.1254 * 1255 * @param collectionId ID of collection1256 * @param tokenId ID of token1257 * @param propertyKeys optionally filter the returned properties to only these keys1258 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1259 * @returns array of key-value pairs1260 */1261 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1262 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1263 }12641265 /**1266 * Delete the provided properties of a token1267 * @param signer keyring of signer1268 * @param collectionId ID of collection1269 * @param tokenId ID of token1270 * @param propertyKeys property keys to be deleted1271 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1272 * @returns ```true``` if extrinsic success, otherwise ```false```1273 */1274 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1275 const result = await this.helper.executeExtrinsic(1276 signer,1277 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1278 true,1279 );12801281 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1282 }12831284 /**1285 * Mint new collection1286 *1287 * @param signer keyring of signer1288 * @param collectionOptions basic collection options and properties1289 * @param mode NFT or RFT type of a collection1290 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1291 * @returns object of the created collection1292 */1293 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1294 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1295 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1296 for (const key of ['name', 'description', 'tokenPrefix']) {1297 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1298 }1299 const creationResult = await this.helper.executeExtrinsic(1300 signer,1301 'api.tx.unique.createCollectionEx', [collectionOptions],1302 true, // errorLabel,1303 );1304 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1305 }13061307 getCollectionObject(_collectionId: number): any {1308 return null;1309 }13101311 getTokenObject(_collectionId: number, _tokenId: number): any {1312 return null;1313 }1314}131513161317class NFTGroup extends NFTnRFT {1318 /**1319 * Get collection object1320 * @param collectionId ID of collection1321 * @example getCollectionObject(2);1322 * @returns instance of UniqueNFTCollection1323 */1324 getCollectionObject(collectionId: number): UniqueNFTCollection {1325 return new UniqueNFTCollection(collectionId, this.helper);1326 }13271328 /**1329 * Get token object1330 * @param collectionId ID of collection1331 * @param tokenId ID of token1332 * @example getTokenObject(10, 5);1333 * @returns instance of UniqueNFTToken1334 */1335 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1336 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1337 }13381339 /**1340 * Get token's owner1341 * @param collectionId ID of collection1342 * @param tokenId ID of token1343 * @param blockHashAt optionally query the data at the block with this hash1344 * @example getTokenOwner(10, 5);1345 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1346 */1347 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1348 let owner;1349 if (typeof blockHashAt === 'undefined') {1350 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1351 } else {1352 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1353 }1354 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1355 }13561357 /**1358 * Is token approved to transfer1359 * @param collectionId ID of collection1360 * @param tokenId ID of token1361 * @param toAccountObj address to be approved1362 * @returns ```true``` if extrinsic success, otherwise ```false```1363 */1364 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1365 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1366 }13671368 /**1369 * Changes the owner of the token.1370 *1371 * @param signer keyring of signer1372 * @param collectionId ID of collection1373 * @param tokenId ID of token1374 * @param addressObj address of a new owner1375 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1376 * @returns ```true``` if extrinsic success, otherwise ```false```1377 */1378 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1379 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1380 }13811382 /**1383 *1384 * Change ownership of a NFT on behalf of the owner.1385 *1386 * @param signer keyring of signer1387 * @param collectionId ID of collection1388 * @param tokenId ID of token1389 * @param fromAddressObj address on behalf of which the token will be sent1390 * @param toAddressObj new token owner1391 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1392 * @returns ```true``` if extrinsic success, otherwise ```false```1393 */1394 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1395 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1396 }13971398 /**1399 * Recursively find the address that owns the token1400 * @param collectionId ID of collection1401 * @param tokenId ID of token1402 * @param blockHashAt1403 * @example getTokenTopmostOwner(10, 5);1404 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1405 */1406 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1407 let owner;1408 if (typeof blockHashAt === 'undefined') {1409 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1410 } else {1411 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1412 }14131414 if (owner === null) return null;14151416 return owner.toHuman();1417 }14181419 /**1420 * Get tokens nested in the provided token1421 * @param collectionId ID of collection1422 * @param tokenId ID of token1423 * @param blockHashAt optionally query the data at the block with this hash1424 * @example getTokenChildren(10, 5);1425 * @returns tokens whose depth of nesting is <= 51426 */1427 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1428 let children;1429 if(typeof blockHashAt === 'undefined') {1430 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1431 } else {1432 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1433 }14341435 return children.toJSON().map((x: any) => {1436 return {collectionId: x.collection, tokenId: x.token};1437 });1438 }14391440 /**1441 * Nest one token into another1442 * @param signer keyring of signer1443 * @param tokenObj token to be nested1444 * @param rootTokenObj token to be parent1445 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1446 * @returns ```true``` if extrinsic success, otherwise ```false```1447 */1448 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1449 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1450 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1451 if(!result) {1452 throw Error('Unable to nest token!');1453 }1454 return result;1455 }14561457 /**1458 * Remove token from nested state1459 * @param signer keyring of signer1460 * @param tokenObj token to unnest1461 * @param rootTokenObj parent of a token1462 * @param toAddressObj address of a new token owner1463 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1464 * @returns ```true``` if extrinsic success, otherwise ```false```1465 */1466 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1467 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1468 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1469 if(!result) {1470 throw Error('Unable to unnest token!');1471 }1472 return result;1473 }14741475 /**1476 * Mint new collection1477 * @param signer keyring of signer1478 * @param collectionOptions Collection options1479 * @example1480 * mintCollection(aliceKeyring, {1481 * name: 'New',1482 * description: 'New collection',1483 * tokenPrefix: 'NEW',1484 * })1485 * @returns object of the created collection1486 */1487 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1488 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1489 }14901491 /**1492 * Mint new token1493 * @param signer keyring of signer1494 * @param data token data1495 * @returns created token object1496 */1497 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1498 const creationResult = await this.helper.executeExtrinsic(1499 signer,1500 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1501 nft: {1502 properties: data.properties,1503 },1504 }],1505 true,1506 );1507 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1508 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1509 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1510 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1511 }15121513 /**1514 * Mint multiple NFT tokens1515 * @param signer keyring of signer1516 * @param collectionId ID of collection1517 * @param tokens array of tokens with owner and properties1518 * @example1519 * mintMultipleTokens(aliceKeyring, 10, [{1520 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1521 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1522 * },{1523 * owner: {Ethereum: "0x9F0583DbB855d..."},1524 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1525 * }]);1526 * @returns ```true``` if extrinsic success, otherwise ```false```1527 */1528 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1529 const creationResult = await this.helper.executeExtrinsic(1530 signer,1531 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1532 true,1533 );1534 const collection = this.getCollectionObject(collectionId);1535 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1536 }15371538 /**1539 * Mint multiple NFT tokens with one owner1540 * @param signer keyring of signer1541 * @param collectionId ID of collection1542 * @param owner tokens owner1543 * @param tokens array of tokens with owner and properties1544 * @example1545 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1546 * properties: [{1547 * key: "gender",1548 * value: "female",1549 * },{1550 * key: "age",1551 * value: "33",1552 * }],1553 * }]);1554 * @returns array of newly created tokens1555 */1556 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1557 const rawTokens = [];1558 for (const token of tokens) {1559 const raw = {NFT: {properties: token.properties}};1560 rawTokens.push(raw);1561 }1562 const creationResult = await this.helper.executeExtrinsic(1563 signer,1564 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1565 true,1566 );1567 const collection = this.getCollectionObject(collectionId);1568 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1569 }15701571 /**1572 * Set, change, or remove approved address to transfer the ownership of the NFT.1573 *1574 * @param signer keyring of signer1575 * @param collectionId ID of collection1576 * @param tokenId ID of token1577 * @param toAddressObj address to approve1578 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1579 * @returns ```true``` if extrinsic success, otherwise ```false```1580 */1581 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1582 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1583 }1584}158515861587class RFTGroup extends NFTnRFT {1588 /**1589 * Get collection object1590 * @param collectionId ID of collection1591 * @example getCollectionObject(2);1592 * @returns instance of UniqueRFTCollection1593 */1594 getCollectionObject(collectionId: number): UniqueRFTCollection {1595 return new UniqueRFTCollection(collectionId, this.helper);1596 }15971598 /**1599 * Get token object1600 * @param collectionId ID of collection1601 * @param tokenId ID of token1602 * @example getTokenObject(10, 5);1603 * @returns instance of UniqueNFTToken1604 */1605 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1606 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1607 }16081609 /**1610 * Get top 10 token owners with the largest number of pieces1611 * @param collectionId ID of collection1612 * @param tokenId ID of token1613 * @example getTokenTop10Owners(10, 5);1614 * @returns array of top 10 owners1615 */1616 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1617 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1618 }16191620 /**1621 * Get number of pieces owned by address1622 * @param collectionId ID of collection1623 * @param tokenId ID of token1624 * @param addressObj address token owner1625 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1626 * @returns number of pieces ownerd by address1627 */1628 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1629 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1630 }16311632 /**1633 * Transfer pieces of token to another address1634 * @param signer keyring of signer1635 * @param collectionId ID of collection1636 * @param tokenId ID of token1637 * @param addressObj address of a new owner1638 * @param amount number of pieces to be transfered1639 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1640 * @returns ```true``` if extrinsic success, otherwise ```false```1641 */1642 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1643 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1644 }16451646 /**1647 * Change ownership of some pieces of RFT on behalf of the owner.1648 * @param signer keyring of signer1649 * @param collectionId ID of collection1650 * @param tokenId ID of token1651 * @param fromAddressObj address on behalf of which the token will be sent1652 * @param toAddressObj new token owner1653 * @param amount number of pieces to be transfered1654 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1655 * @returns ```true``` if extrinsic success, otherwise ```false```1656 */1657 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1658 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1659 }16601661 /**1662 * Mint new collection1663 * @param signer keyring of signer1664 * @param collectionOptions Collection options1665 * @example1666 * mintCollection(aliceKeyring, {1667 * name: 'New',1668 * description: 'New collection',1669 * tokenPrefix: 'NEW',1670 * })1671 * @returns object of the created collection1672 */1673 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1674 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1675 }16761677 /**1678 * Mint new token1679 * @param signer keyring of signer1680 * @param data token data1681 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1682 * @returns created token object1683 */1684 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1685 const creationResult = await this.helper.executeExtrinsic(1686 signer,1687 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1688 refungible: {1689 pieces: data.pieces,1690 properties: data.properties,1691 },1692 }],1693 true,1694 );1695 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1696 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1697 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1698 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1699 }17001701 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1702 throw Error('Not implemented');1703 const creationResult = await this.helper.executeExtrinsic(1704 signer,1705 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1706 true, // `Unable to mint RFT tokens for ${label}`,1707 );1708 const collection = this.getCollectionObject(collectionId);1709 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1710 }17111712 /**1713 * Mint multiple RFT tokens with one owner1714 * @param signer keyring of signer1715 * @param collectionId ID of collection1716 * @param owner tokens owner1717 * @param tokens array of tokens with properties and pieces1718 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1719 * @returns array of newly created RFT tokens1720 */1721 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1722 const rawTokens = [];1723 for (const token of tokens) {1724 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1725 rawTokens.push(raw);1726 }1727 const creationResult = await this.helper.executeExtrinsic(1728 signer,1729 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1730 true,1731 );1732 const collection = this.getCollectionObject(collectionId);1733 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1734 }17351736 /**1737 * Destroys a concrete instance of RFT.1738 * @param signer keyring of signer1739 * @param collectionId ID of collection1740 * @param tokenId ID of token1741 * @param amount number of pieces to be burnt1742 * @example burnToken(aliceKeyring, 10, 5);1743 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1744 */1745 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1746 return await super.burnToken(signer, collectionId, tokenId, amount);1747 }17481749 /**1750 * Destroys a concrete instance of RFT on behalf of the owner.1751 * @param signer keyring of signer1752 * @param collectionId ID of collection1753 * @param tokenId ID of token1754 * @param fromAddressObj address on behalf of which the token will be burnt1755 * @param amount number of pieces to be burnt1756 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1757 * @returns ```true``` if extrinsic success, otherwise ```false```1758 */1759 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1760 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1761 }17621763 /**1764 * Set, change, or remove approved address to transfer the ownership of the RFT.1765 *1766 * @param signer keyring of signer1767 * @param collectionId ID of collection1768 * @param tokenId ID of token1769 * @param toAddressObj address to approve1770 * @param amount number of pieces to be approved1771 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1772 * @returns true if the token success, otherwise false1773 */1774 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1775 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1776 }17771778 /**1779 * Get total number of pieces1780 * @param collectionId ID of collection1781 * @param tokenId ID of token1782 * @example getTokenTotalPieces(10, 5);1783 * @returns number of pieces1784 */1785 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1786 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1787 }17881789 /**1790 * Change number of token pieces. Signer must be the owner of all token pieces.1791 * @param signer keyring of signer1792 * @param collectionId ID of collection1793 * @param tokenId ID of token1794 * @param amount new number of pieces1795 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1796 * @returns true if the repartion was success, otherwise false1797 */1798 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1799 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1800 const repartitionResult = await this.helper.executeExtrinsic(1801 signer,1802 'api.tx.unique.repartition', [collectionId, tokenId, amount],1803 true,1804 );1805 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1806 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1807 }1808}180918101811class FTGroup extends CollectionGroup {1812 /**1813 * Get collection object1814 * @param collectionId ID of collection1815 * @example getCollectionObject(2);1816 * @returns instance of UniqueFTCollection1817 */1818 getCollectionObject(collectionId: number): UniqueFTCollection {1819 return new UniqueFTCollection(collectionId, this.helper);1820 }18211822 /**1823 * Mint new fungible collection1824 * @param signer keyring of signer1825 * @param collectionOptions Collection options1826 * @param decimalPoints number of token decimals1827 * @example1828 * mintCollection(aliceKeyring, {1829 * name: 'New',1830 * description: 'New collection',1831 * tokenPrefix: 'NEW',1832 * }, 18)1833 * @returns newly created fungible collection1834 */1835 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1836 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1837 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1838 collectionOptions.mode = {fungible: decimalPoints};1839 for (const key of ['name', 'description', 'tokenPrefix']) {1840 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1841 }1842 const creationResult = await this.helper.executeExtrinsic(1843 signer,1844 'api.tx.unique.createCollectionEx', [collectionOptions],1845 true,1846 );1847 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1848 }18491850 /**1851 * Mint tokens1852 * @param signer keyring of signer1853 * @param collectionId ID of collection1854 * @param owner address owner of new tokens1855 * @param amount amount of tokens to be meanted1856 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1857 * @returns ```true``` if extrinsic success, otherwise ```false```1858 */1859 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1860 const creationResult = await this.helper.executeExtrinsic(1861 signer,1862 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1863 fungible: {1864 value: amount,1865 },1866 }],1867 true, // `Unable to mint fungible tokens for ${label}`,1868 );1869 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1870 }18711872 /**1873 * Mint multiple Fungible tokens with one owner1874 * @param signer keyring of signer1875 * @param collectionId ID of collection1876 * @param owner tokens owner1877 * @param tokens array of tokens with properties and pieces1878 * @returns ```true``` if extrinsic success, otherwise ```false```1879 */1880 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1881 const rawTokens = [];1882 for (const token of tokens) {1883 const raw = {Fungible: {Value: token.value}};1884 rawTokens.push(raw);1885 }1886 const creationResult = await this.helper.executeExtrinsic(1887 signer,1888 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1889 true,1890 );1891 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1892 }18931894 /**1895 * Get the top 10 owners with the largest balance for the Fungible collection1896 * @param collectionId ID of collection1897 * @example getTop10Owners(10);1898 * @returns array of ```ICrossAccountId```1899 */1900 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1901 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1902 }19031904 /**1905 * Get account balance1906 * @param collectionId ID of collection1907 * @param addressObj address of owner1908 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1909 * @returns amount of fungible tokens owned by address1910 */1911 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1912 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1913 }19141915 /**1916 * Transfer tokens to address1917 * @param signer keyring of signer1918 * @param collectionId ID of collection1919 * @param toAddressObj address recipient1920 * @param amount amount of tokens to be sent1921 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1922 * @returns ```true``` if extrinsic success, otherwise ```false```1923 */1924 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1925 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1926 }19271928 /**1929 * Transfer some tokens on behalf of the owner.1930 * @param signer keyring of signer1931 * @param collectionId ID of collection1932 * @param fromAddressObj address on behalf of which tokens will be sent1933 * @param toAddressObj address where token to be sent1934 * @param amount number of tokens to be sent1935 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1936 * @returns ```true``` if extrinsic success, otherwise ```false```1937 */1938 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1939 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1940 }19411942 /**1943 * Destroy some amount of tokens1944 * @param signer keyring of signer1945 * @param collectionId ID of collection1946 * @param amount amount of tokens to be destroyed1947 * @example burnTokens(aliceKeyring, 10, 1000n);1948 * @returns ```true``` if extrinsic success, otherwise ```false```1949 */1950 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1951 return await super.burnToken(signer, collectionId, 0, amount);1952 }19531954 /**1955 * Burn some tokens on behalf of the owner.1956 * @param signer keyring of signer1957 * @param collectionId ID of collection1958 * @param fromAddressObj address on behalf of which tokens will be burnt1959 * @param amount amount of tokens to be burnt1960 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1961 * @returns ```true``` if extrinsic success, otherwise ```false```1962 */1963 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1964 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1965 }19661967 /**1968 * Get total collection supply1969 * @param collectionId1970 * @returns1971 */1972 async getTotalPieces(collectionId: number): Promise<bigint> {1973 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1974 }19751976 /**1977 * Set, change, or remove approved address to transfer tokens.1978 *1979 * @param signer keyring of signer1980 * @param collectionId ID of collection1981 * @param toAddressObj address to be approved1982 * @param amount amount of tokens to be approved1983 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1984 * @returns ```true``` if extrinsic success, otherwise ```false```1985 */1986 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1987 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1988 }19891990 /**1991 * Get amount of fungible tokens approved to transfer1992 * @param collectionId ID of collection1993 * @param fromAddressObj owner of tokens1994 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1995 * @returns number of tokens approved for the transfer1996 */1997 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1998 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1999 }2000}200120022003class ChainGroup extends HelperGroup {2004 /**2005 * Get system properties of a chain2006 * @example getChainProperties();2007 * @returns ss58Format, token decimals, and token symbol2008 */2009 getChainProperties(): IChainProperties {2010 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2011 return {2012 ss58Format: properties.ss58Format.toJSON(),2013 tokenDecimals: properties.tokenDecimals.toJSON(),2014 tokenSymbol: properties.tokenSymbol.toJSON(),2015 };2016 }20172018 /**2019 * Get chain header2020 * @example getLatestBlockNumber();2021 * @returns the number of the last block2022 */2023 async getLatestBlockNumber(): Promise<number> {2024 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2025 }20262027 /**2028 * Get block hash by block number2029 * @param blockNumber number of block2030 * @example getBlockHashByNumber(12345);2031 * @returns hash of a block2032 */2033 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2034 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2035 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2036 return blockHash;2037 }20382039 // TODO add docs2040 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2041 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2042 if (!blockHash) return null;2043 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2044 }20452046 /**2047 * Get account nonce2048 * @param address substrate address2049 * @example getNonce("5GrwvaEF5zXb26Fz...");2050 * @returns number, account's nonce2051 */2052 async getNonce(address: TSubstrateAccount): Promise<number> {2053 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2054 }2055}205620572058class BalanceGroup extends HelperGroup {2059 getCollectionCreationPrice(): bigint {2060 return 2n * this.helper.balance.getOneTokenNominal();2061 }2062 /**2063 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2064 * @example getOneTokenNominal()2065 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2066 */2067 getOneTokenNominal(): bigint {2068 const chainProperties = this.helper.chain.getChainProperties();2069 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2070 }20712072 /**2073 * Get substrate address balance2074 * @param address substrate address2075 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2076 * @returns amount of tokens on address2077 */2078 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2079 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2080 }20812082 /**2083 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2084 * @param address substrate address2085 * @returns2086 */2087 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2088 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2089 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2090 }20912092 /**2093 * Get ethereum address balance2094 * @param address ethereum address2095 * @example getEthereum("0x9F0583DbB855d...")2096 * @returns amount of tokens on address2097 */2098 async getEthereum(address: TEthereumAccount): Promise<bigint> {2099 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2100 }21012102 /**2103 * Transfer tokens to substrate address2104 * @param signer keyring of signer2105 * @param address substrate address of a recipient2106 * @param amount amount of tokens to be transfered2107 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2108 * @returns ```true``` if extrinsic success, otherwise ```false```2109 */2110 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2111 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);21122113 let transfer = {from: null, to: null, amount: 0n} as any;2114 result.result.events.forEach(({event: {data, method, section}}) => {2115 if ((section === 'balances') && (method === 'Transfer')) {2116 transfer = {2117 from: this.helper.address.normalizeSubstrate(data[0]),2118 to: this.helper.address.normalizeSubstrate(data[1]),2119 amount: BigInt(data[2]),2120 };2121 }2122 });2123 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2124 && this.helper.address.normalizeSubstrate(address) === transfer.to 2125 && BigInt(amount) === transfer.amount;2126 return isSuccess;2127 }2128}212921302131class AddressGroup extends HelperGroup {2132 /**2133 * Normalizes the address to the specified ss58 format, by default ```42```.2134 * @param address substrate address2135 * @param ss58Format format for address conversion, by default ```42```2136 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2137 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2138 */2139 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2140 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2141 }21422143 /**2144 * Get address in the connected chain format2145 * @param address substrate address2146 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2147 * @returns address in chain format2148 */2149 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2150 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2151 }21522153 /**2154 * Get substrate mirror of an ethereum address2155 * @param ethAddress ethereum address2156 * @param toChainFormat false for normalized account2157 * @example ethToSubstrate('0x9F0583DbB855d...')2158 * @returns substrate mirror of a provided ethereum address2159 */2160 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2161 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2162 }21632164 /**2165 * Get ethereum mirror of a substrate address2166 * @param subAddress substrate account2167 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2168 * @returns ethereum mirror of a provided substrate address2169 */2170 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2171 return CrossAccountId.translateSubToEth(subAddress);2172 }2173}21742175class StakingGroup extends HelperGroup {2176 /**2177 * Stake tokens for App Promotion2178 * @param signer keyring of signer2179 * @param amountToStake amount of tokens to stake2180 * @param label extra label for log2181 * @returns2182 */2183 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2184 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2185 const _stakeResult = await this.helper.executeExtrinsic(2186 signer, 'api.tx.appPromotion.stake',2187 [amountToStake], true,2188 );2189 // TODO extract info from stakeResult2190 return true;2191 }21922193 /**2194 * Unstake tokens for App Promotion2195 * @param signer keyring of signer2196 * @param amountToUnstake amount of tokens to unstake2197 * @param label extra label for log2198 * @returns block number where balances will be unlocked2199 */2200 async unstake(signer: TSigner, label?: string): Promise<number> {2201 if(typeof label === 'undefined') label = `${signer.address}`;2202 const _unstakeResult = await this.helper.executeExtrinsic(2203 signer, 'api.tx.appPromotion.unstake',2204 [], true,2205 );2206 // TODO extract block number fron events2207 return 1;2208 }22092210 /**2211 * Get total staked amount for address2212 * @param address substrate or ethereum address2213 * @returns total staked amount2214 */2215 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2216 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2217 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2218 }22192220 /**2221 * Get total staked per block2222 * @param address substrate or ethereum address2223 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2224 */2225 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2226 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2227 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2228 return { 2229 block: block.toBigInt(),2230 amount: amount.toBigInt(),2231 };2232 });2233 }22342235 /**2236 * Get total pending unstake amount for address2237 * @param address substrate or ethereum address2238 * @returns total pending unstake amount2239 */2240 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2241 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2242 }22432244 /**2245 * Get pending unstake amount per block for address2246 * @param address substrate or ethereum address2247 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2248 */2249 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2250 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2251 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2252 return {2253 block: block.toBigInt(),2254 amount: amount.toBigInt(),2255 };2256 });2257 return result;2258 }2259}22602261class SchedulerGroup extends HelperGroup {2262 constructor(helper: UniqueHelper) {2263 super(helper);2264 }22652266 async cancelScheduled(signer: TSigner, scheduledId: string) {2267 return this.helper.executeExtrinsic(2268 signer,2269 'api.tx.scheduler.cancelNamed',2270 [scheduledId],2271 true,2272 );2273 }22742275 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2276 return this.helper.executeExtrinsic(2277 signer,2278 'api.tx.scheduler.changeNamedPriority',2279 [scheduledId, priority],2280 true,2281 );2282 }22832284 scheduleAt<T extends UniqueHelper>(2285 scheduledId: string,2286 executionBlockNumber: number,2287 options: ISchedulerOptions = {},2288 ) {2289 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2290 }22912292 scheduleAfter<T extends UniqueHelper>(2293 scheduledId: string,2294 blocksBeforeExecution: number,2295 options: ISchedulerOptions = {},2296 ) {2297 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2298 }22992300 schedule<T extends UniqueHelper>(2301 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2302 scheduledId: string,2303 blocksNum: number,2304 options: ISchedulerOptions = {},2305 ) {2306 // eslint-disable-next-line @typescript-eslint/naming-convention2307 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2308 return this.helper.clone(ScheduledHelperType, {2309 scheduleFn,2310 scheduledId,2311 blocksNum,2312 options,2313 }) as T;2314 }2315}23162317export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;23182319export class UniqueHelper extends ChainHelperBase {2320 helperBase: any;23212322 chain: ChainGroup;2323 balance: BalanceGroup;2324 address: AddressGroup;2325 collection: CollectionGroup;2326 nft: NFTGroup;2327 rft: RFTGroup;2328 ft: FTGroup;2329 staking: StakingGroup;2330 scheduler: SchedulerGroup;23312332 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2333 super(logger);23342335 this.helperBase = options.helperBase ?? UniqueHelper;23362337 this.chain = new ChainGroup(this);2338 this.balance = new BalanceGroup(this);2339 this.address = new AddressGroup(this);2340 this.collection = new CollectionGroup(this);2341 this.nft = new NFTGroup(this);2342 this.rft = new RFTGroup(this);2343 this.ft = new FTGroup(this);2344 this.staking = new StakingGroup(this);2345 this.scheduler = new SchedulerGroup(this);2346 }23472348 clone(helperCls: UniqueHelperConstructor, options: {[key: string]: any} = {}) {2349 Object.setPrototypeOf(helperCls.prototype, this);2350 const newHelper = new helperCls(this.logger, options);23512352 newHelper.api = this.api;2353 newHelper.network = this.network;2354 newHelper.forceNetwork = this.forceNetwork;23552356 this.children.push(newHelper);23572358 return newHelper;2359 }23602361 getSudo<T extends UniqueHelper>() {2362 // eslint-disable-next-line @typescript-eslint/naming-convention2363 const SudoHelperType = SudoUniqueHelper(this.helperBase);2364 return this.clone(SudoHelperType) as T;2365 }2366}23672368// eslint-disable-next-line @typescript-eslint/naming-convention2369function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2370 return class extends Base {2371 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2372 scheduledId: string;2373 blocksNum: number;2374 options: ISchedulerOptions;23752376 constructor(...args: any[]) {2377 const logger = args[0] as ILogger;2378 const options = args[1] as {2379 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2380 scheduledId: string,2381 blocksNum: number,2382 options: ISchedulerOptions2383 };23842385 super(logger);23862387 this.scheduleFn = options.scheduleFn;2388 this.scheduledId = options.scheduledId;2389 this.blocksNum = options.blocksNum;2390 this.options = options.options;2391 }23922393 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2394 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2395 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;23962397 return super.executeExtrinsic(2398 sender,2399 extrinsic,2400 [2401 this.scheduledId,2402 this.blocksNum,2403 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2404 this.options.priority ?? null,2405 {Value: scheduledTx},2406 ],2407 expectSuccess,2408 );2409 }2410 };2411}24122413// eslint-disable-next-line @typescript-eslint/naming-convention2414function SudoUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2415 return class extends Base {2416 constructor(...args: any[]) {2417 super(...args);2418 }24192420 executeExtrinsic (2421 sender: IKeyringPair,2422 extrinsic: string,2423 params: any[],2424 expectSuccess?: boolean,2425 ): Promise<ITransactionResult> {2426 const call = this.constructApiCall(extrinsic, params);24272428 return super.executeExtrinsic(2429 sender,2430 'api.tx.sudo.sudo',2431 [call],2432 expectSuccess,2433 );2434 }2435 };2436}24372438export class UniqueBaseCollection {2439 helper: UniqueHelper;2440 collectionId: number;24412442 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2443 this.collectionId = collectionId;2444 this.helper = uniqueHelper;2445 }24462447 async getData() {2448 return await this.helper.collection.getData(this.collectionId);2449 }24502451 async getLastTokenId() {2452 return await this.helper.collection.getLastTokenId(this.collectionId);2453 }24542455 async doesTokenExist(tokenId: number) {2456 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2457 }24582459 async getAdmins() {2460 return await this.helper.collection.getAdmins(this.collectionId);2461 }24622463 async getAllowList() {2464 return await this.helper.collection.getAllowList(this.collectionId);2465 }24662467 async getEffectiveLimits() {2468 return await this.helper.collection.getEffectiveLimits(this.collectionId);2469 }24702471 async getProperties(propertyKeys?: string[] | null) {2472 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2473 }24742475 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2476 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2477 }24782479 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2480 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2481 }24822483 async confirmSponsorship(signer: TSigner) {2484 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2485 }24862487 async removeSponsor(signer: TSigner) {2488 return await this.helper.collection.removeSponsor(signer, this.collectionId);2489 }24902491 async setLimits(signer: TSigner, limits: ICollectionLimits) {2492 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2493 }24942495 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2496 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2497 }24982499 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2500 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2501 }25022503 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2504 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2505 }25062507 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2508 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2509 }25102511 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2512 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2513 }25142515 async setProperties(signer: TSigner, properties: IProperty[]) {2516 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2517 }25182519 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2520 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2521 }25222523 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2524 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2525 }25262527 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2528 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2529 }25302531 async disableNesting(signer: TSigner) {2532 return await this.helper.collection.disableNesting(signer, this.collectionId);2533 }25342535 async burn(signer: TSigner) {2536 return await this.helper.collection.burn(signer, this.collectionId);2537 }25382539 scheduleAt<T extends UniqueHelper>(2540 scheduledId: string,2541 executionBlockNumber: number,2542 options: ISchedulerOptions = {},2543 ) {2544 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2545 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2546 }25472548 scheduleAfter<T extends UniqueHelper>(2549 scheduledId: string,2550 blocksBeforeExecution: number,2551 options: ISchedulerOptions = {},2552 ) {2553 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2554 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2555 }25562557 getSudo<T extends UniqueHelper>() {2558 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2559 }2560}256125622563export class UniqueNFTCollection extends UniqueBaseCollection {2564 getTokenObject(tokenId: number) {2565 return new UniqueNFToken(tokenId, this);2566 }25672568 async getTokensByAddress(addressObj: ICrossAccountId) {2569 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2570 }25712572 async getToken(tokenId: number, blockHashAt?: string) {2573 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2574 }25752576 async getTokenOwner(tokenId: number, blockHashAt?: string) {2577 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2578 }25792580 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2581 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2582 }25832584 async getTokenChildren(tokenId: number, blockHashAt?: string) {2585 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2586 }25872588 async getPropertyPermissions(propertyKeys: string[] | null = null) {2589 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2590 }25912592 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2593 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2594 }25952596 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2597 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2598 }25992600 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2601 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2602 }26032604 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2605 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2606 }26072608 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2609 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2610 }26112612 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2613 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2614 }26152616 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2617 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2618 }26192620 async burnToken(signer: TSigner, tokenId: number) {2621 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2622 }26232624 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2625 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2626 }26272628 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2629 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2630 }26312632 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2633 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2634 }26352636 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2637 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2638 }26392640 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2641 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2642 }26432644 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2645 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2646 }26472648 scheduleAt<T extends UniqueHelper>(2649 scheduledId: string,2650 executionBlockNumber: number,2651 options: ISchedulerOptions = {},2652 ) {2653 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2654 return new UniqueNFTCollection(this.collectionId, scheduledHelper);2655 }26562657 scheduleAfter<T extends UniqueHelper>(2658 scheduledId: string,2659 blocksBeforeExecution: number,2660 options: ISchedulerOptions = {},2661 ) {2662 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2663 return new UniqueNFTCollection(this.collectionId, scheduledHelper);2664 }26652666 getSudo<T extends UniqueHelper>() {2667 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());2668 }2669}267026712672export class UniqueRFTCollection extends UniqueBaseCollection {2673 getTokenObject(tokenId: number) {2674 return new UniqueRFToken(tokenId, this);2675 }26762677 async getToken(tokenId: number, blockHashAt?: string) {2678 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2679 }26802681 async getTokensByAddress(addressObj: ICrossAccountId) {2682 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2683 }26842685 async getTop10TokenOwners(tokenId: number) {2686 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2687 }26882689 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2690 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2691 }26922693 async getTokenTotalPieces(tokenId: number) {2694 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2695 }26962697 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2698 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2699 }27002701 async getPropertyPermissions(propertyKeys: string[] | null = null) {2702 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2703 }27042705 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2706 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2707 }27082709 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2710 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2711 }27122713 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2714 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2715 }27162717 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2718 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2719 }27202721 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2722 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2723 }27242725 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2726 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2727 }27282729 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2730 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2731 }27322733 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2734 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2735 }27362737 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2738 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2739 }27402741 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2742 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2743 }27442745 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2746 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2747 }27482749 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2750 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2751 }27522753 scheduleAt<T extends UniqueHelper>(2754 scheduledId: string,2755 executionBlockNumber: number,2756 options: ISchedulerOptions = {},2757 ) {2758 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2759 return new UniqueRFTCollection(this.collectionId, scheduledHelper);2760 }27612762 scheduleAfter<T extends UniqueHelper>(2763 scheduledId: string,2764 blocksBeforeExecution: number,2765 options: ISchedulerOptions = {},2766 ) {2767 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2768 return new UniqueRFTCollection(this.collectionId, scheduledHelper);2769 }27702771 getSudo<T extends UniqueHelper>() {2772 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());2773 }2774}277527762777export class UniqueFTCollection extends UniqueBaseCollection {2778 async getBalance(addressObj: ICrossAccountId) {2779 return await this.helper.ft.getBalance(this.collectionId, addressObj);2780 }27812782 async getTotalPieces() {2783 return await this.helper.ft.getTotalPieces(this.collectionId);2784 }27852786 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2787 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2788 }27892790 async getTop10Owners() {2791 return await this.helper.ft.getTop10Owners(this.collectionId);2792 }27932794 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2795 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2796 }27972798 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2799 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2800 }28012802 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2803 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2804 }28052806 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2807 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2808 }28092810 async burnTokens(signer: TSigner, amount=1n) {2811 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2812 }28132814 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2815 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2816 }28172818 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2819 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2820 }28212822 scheduleAt<T extends UniqueHelper>(2823 scheduledId: string,2824 executionBlockNumber: number,2825 options: ISchedulerOptions = {},2826 ) {2827 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2828 return new UniqueFTCollection(this.collectionId, scheduledHelper);2829 }28302831 scheduleAfter<T extends UniqueHelper>(2832 scheduledId: string,2833 blocksBeforeExecution: number,2834 options: ISchedulerOptions = {},2835 ) {2836 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2837 return new UniqueFTCollection(this.collectionId, scheduledHelper);2838 }28392840 getSudo<T extends UniqueHelper>() {2841 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());2842 }2843}284428452846export class UniqueBaseToken {2847 collection: UniqueNFTCollection | UniqueRFTCollection;2848 collectionId: number;2849 tokenId: number;28502851 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2852 this.collection = collection;2853 this.collectionId = collection.collectionId;2854 this.tokenId = tokenId;2855 }28562857 async getNextSponsored(addressObj: ICrossAccountId) {2858 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2859 }28602861 async getProperties(propertyKeys?: string[] | null) {2862 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2863 }28642865 async setProperties(signer: TSigner, properties: IProperty[]) {2866 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2867 }28682869 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2870 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2871 }28722873 async doesExist() {2874 return await this.collection.doesTokenExist(this.tokenId);2875 }28762877 nestingAccount() {2878 return this.collection.helper.util.getTokenAccount(this);2879 }28802881 scheduleAt<T extends UniqueHelper>(2882 scheduledId: string,2883 executionBlockNumber: number,2884 options: ISchedulerOptions = {},2885 ) {2886 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);2887 return new UniqueBaseToken(this.tokenId, scheduledCollection);2888 }28892890 scheduleAfter<T extends UniqueHelper>(2891 scheduledId: string,2892 blocksBeforeExecution: number,2893 options: ISchedulerOptions = {},2894 ) {2895 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2896 return new UniqueBaseToken(this.tokenId, scheduledCollection);2897 }28982899 getSudo<T extends UniqueHelper>() {2900 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());2901 }2902}290329042905export class UniqueNFToken extends UniqueBaseToken {2906 collection: UniqueNFTCollection;29072908 constructor(tokenId: number, collection: UniqueNFTCollection) {2909 super(tokenId, collection);2910 this.collection = collection;2911 }29122913 async getData(blockHashAt?: string) {2914 return await this.collection.getToken(this.tokenId, blockHashAt);2915 }29162917 async getOwner(blockHashAt?: string) {2918 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2919 }29202921 async getTopmostOwner(blockHashAt?: string) {2922 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2923 }29242925 async getChildren(blockHashAt?: string) {2926 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2927 }29282929 async nest(signer: TSigner, toTokenObj: IToken) {2930 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2931 }29322933 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2934 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2935 }29362937 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2938 return await this.collection.transferToken(signer, this.tokenId, addressObj);2939 }29402941 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2942 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2943 }29442945 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2946 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2947 }29482949 async isApproved(toAddressObj: ICrossAccountId) {2950 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2951 }29522953 async burn(signer: TSigner) {2954 return await this.collection.burnToken(signer, this.tokenId);2955 }29562957 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2958 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2959 }29602961 scheduleAt<T extends UniqueHelper>(2962 scheduledId: string,2963 executionBlockNumber: number,2964 options: ISchedulerOptions = {},2965 ) {2966 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);2967 return new UniqueNFToken(this.tokenId, scheduledCollection);2968 }29692970 scheduleAfter<T extends UniqueHelper>(2971 scheduledId: string,2972 blocksBeforeExecution: number,2973 options: ISchedulerOptions = {},2974 ) {2975 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2976 return new UniqueNFToken(this.tokenId, scheduledCollection);2977 }29782979 getSudo<T extends UniqueHelper>() {2980 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());2981 }2982}29832984export class UniqueRFToken extends UniqueBaseToken {2985 collection: UniqueRFTCollection;29862987 constructor(tokenId: number, collection: UniqueRFTCollection) {2988 super(tokenId, collection);2989 this.collection = collection;2990 }29912992 async getData(blockHashAt?: string) {2993 return await this.collection.getToken(this.tokenId, blockHashAt);2994 }29952996 async getTop10Owners() {2997 return await this.collection.getTop10TokenOwners(this.tokenId);2998 }29993000 async getBalance(addressObj: ICrossAccountId) {3001 return await this.collection.getTokenBalance(this.tokenId, addressObj);3002 }30033004 async getTotalPieces() {3005 return await this.collection.getTokenTotalPieces(this.tokenId);3006 }30073008 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3009 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3010 }30113012 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3013 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3014 }30153016 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3017 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3018 }30193020 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3021 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3022 }30233024 async repartition(signer: TSigner, amount: bigint) {3025 return await this.collection.repartitionToken(signer, this.tokenId, amount);3026 }30273028 async burn(signer: TSigner, amount=1n) {3029 return await this.collection.burnToken(signer, this.tokenId, amount);3030 }30313032 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3033 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3034 }30353036 scheduleAt<T extends UniqueHelper>(3037 scheduledId: string,3038 executionBlockNumber: number,3039 options: ISchedulerOptions = {},3040 ) {3041 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3042 return new UniqueRFToken(this.tokenId, scheduledCollection);3043 }30443045 scheduleAfter<T extends UniqueHelper>(3046 scheduledId: string,3047 blocksBeforeExecution: number,3048 options: ISchedulerOptions = {},3049 ) {3050 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3051 return new UniqueRFToken(this.tokenId, scheduledCollection);3052 }30533054 getSudo<T extends UniqueHelper>() {3055 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3056 }3057}tests/src/util/util.tsdiffbeforeafterboth--- a/tests/src/util/util.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-export function strToUTF16(str: string): any {
- const buf: number[] = [];
- for (let i=0, strLen=str.length; i < strLen; i++) {
- buf.push(str.charCodeAt(i));
- }
- return buf;
-}
-
-export function utf16ToStr(buf: number[]): string {
- let str = '';
- for (let i=0, strLen=buf.length; i < strLen; i++) {
- if (buf[i] != 0) str += String.fromCharCode(buf[i]);
- else break;
- }
- return str;
-}
-
-export function hexToStr(buf: string): string {
- let str = '';
- let hexStart = buf.indexOf('0x');
- if (hexStart < 0) hexStart = 0;
- else hexStart = 2;
- for (let i=hexStart, strLen=buf.length; i < strLen; i+=2) {
- const ch = buf[i] + buf[i+1];
- const num = parseInt(ch, 16);
- if (num != 0) str += String.fromCharCode(num);
- else break;
- }
- return str;
-}
tests/src/xcm/xcmOpal.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmOpal.test.ts
+++ b/tests/src/xcm/xcmOpal.test.ts
@@ -21,9 +21,8 @@
import {ApiOptions} from '@polkadot/api/types';
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {executeTransaction} from './../substrate/substrate-api';
-import {bigIntToDecimals, describe_xcm, getGenericResult, paraSiblingSovereignAccount} from './../util/helpers';
+import {bigIntToDecimals, describe_xcm, getGenericResult, paraSiblingSovereignAccount, normalizeAccountId} from './../deprecated-helpers/helpers';
import waitNewBlocks from './../substrate/wait-new-blocks';
-import {normalizeAccountId} from './../util/helpers';
import getBalance from './../substrate/get-balance';
tests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmQuartz.test.ts
+++ b/tests/src/xcm/xcmQuartz.test.ts
@@ -21,7 +21,7 @@
import {ApiOptions} from '@polkadot/api/types';
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
-import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm, bigIntToDecimals} from '../util/helpers';
+import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm, bigIntToDecimals} from '../deprecated-helpers/helpers';
import {MultiLocation} from '@polkadot/types/interfaces';
import {blake2AsHex} from '@polkadot/util-crypto';
import waitNewBlocks from '../substrate/wait-new-blocks';
tests/src/xcm/xcmUnique.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmUnique.test.ts
+++ b/tests/src/xcm/xcmUnique.test.ts
@@ -21,7 +21,7 @@
import {ApiOptions} from '@polkadot/api/types';
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
-import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm, bigIntToDecimals} from '../util/helpers';
+import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm, bigIntToDecimals} from '../deprecated-helpers/helpers';
import {MultiLocation} from '@polkadot/types/interfaces';
import {blake2AsHex} from '@polkadot/util-crypto';
import waitNewBlocks from '../substrate/wait-new-blocks';
tests/src/xcmTransfer.test.tsdiffbeforeafterboth--- a/tests/src/xcmTransfer.test.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-
-import {WsProvider} from '@polkadot/api';
-import {ApiOptions} from '@polkadot/api/types';
-import {IKeyringPair} from '@polkadot/types/types';
-import usingApi, {submitTransactionAsync} from './substrate/substrate-api';
-import {getGenericResult} from './util/helpers';
-import waitNewBlocks from './substrate/wait-new-blocks';
-import getBalance from './substrate/get-balance';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-const UNIQUE_CHAIN = 1000;
-const KARURA_CHAIN = 2000;
-const KARURA_PORT = '9946';
-const TRANSFER_AMOUNT = 2000000000000000000000000n;
-
-// todo:playgrounds refit when XCM drops
-describe.skip('Integration test: Exchanging QTZ with Karura', () => {
- let alice: IKeyringPair;
-
- before(async () => {
- await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- });
-
- const karuraApiOptions: ApiOptions = {
- provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT),
- };
-
- await usingApi(async (api) => {
- const destination = {
- V0: {
- X2: [
- 'Parent',
- {
- Parachain: UNIQUE_CHAIN,
- },
- ],
- },
- };
-
- const metadata =
- {
- name: 'QTZ',
- symbol: 'QTZ',
- decimals: 18,
- minimalBalance: 1,
- };
-
- const tx = api.tx.assetRegistry.registerForeignAsset(destination, metadata);
- const sudoTx = api.tx.sudo.sudo(tx as any);
- const events = await submitTransactionAsync(alice, sudoTx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
- }, karuraApiOptions);
- });
-
- it('Should connect and send QTZ to Karura', async () => {
- let balanceOnKaruraBefore: bigint;
-
- await usingApi(async (api) => {
- const {free} = (await api.query.tokens.accounts(alice.addressRaw, {ForeignAssetId: 0})).toJSON() as any;
- balanceOnKaruraBefore = free;
- }, {provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT)});
-
- await usingApi(async (api) => {
- const destination = {
- V0: {
- X2: [
- 'Parent',
- {
- Parachain: KARURA_CHAIN,
- },
- ],
- },
- };
-
- const beneficiary = {
- V0: {
- X1: {
- AccountId32: {
- network: 'Any',
- id: alice.addressRaw,
- },
- },
- },
- };
-
- const assets = {
- V1: [
- {
- id: {
- Concrete: {
- parents: 0,
- interior: 'Here',
- },
- },
- fun: {
- Fungible: TRANSFER_AMOUNT,
- },
- },
- ],
- };
-
- const feeAssetItem = 0;
-
- const weightLimit = {
- Limited: 5000000000,
- };
-
- const tx = api.tx.polkadotXcm.limitedReserveTransferAssets(destination, beneficiary, assets, feeAssetItem, weightLimit);
- const events = await submitTransactionAsync(alice, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
- });
-
- await usingApi(async (api) => {
- // todo do something about instant sealing, where there might not be any new blocks
- await waitNewBlocks(api, 3);
- const {free} = (await api.query.tokens.accounts(alice.addressRaw, {ForeignAssetId: 0})).toJSON() as any;
- expect(free > balanceOnKaruraBefore).to.be.true;
- }, {provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT)});
- });
-
- it('Should connect to Karura and send QTZ back', async () => {
- let balanceBefore: bigint;
-
- await usingApi(async (api) => {
- [balanceBefore] = await getBalance(api, [alice.address]);
- });
-
- await usingApi(async (api) => {
- const destination = {
- V1: {
- parents: 1,
- interior: {
- X2: [
- {Parachain: UNIQUE_CHAIN},
- {AccountId32: {
- network: 'Any',
- id: alice.addressRaw,
- }},
- ],
- },
- },
- };
-
- const id = {
- ForeignAssetId: 0,
- };
-
- const amount = TRANSFER_AMOUNT;
- const destWeight = 50000000;
-
- const tx = api.tx.xTokens.transfer(id, amount, destination, destWeight);
- const events = await submitTransactionAsync(alice, tx);
- const result = getGenericResult(events);
- expect(result.success).to.be.true;
- }, {provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT)});
-
- await usingApi(async (api) => {
- // todo do something about instant sealing, where there might not be any new blocks
- await waitNewBlocks(api, 3);
- const [balanceAfter] = await getBalance(api, [alice.address]);
- expect(balanceAfter > balanceBefore).to.be.true;
- });
- });
-});
tests/tsconfig.jsondiffbeforeafterboth--- a/tests/tsconfig.json
+++ b/tests/tsconfig.json
@@ -21,6 +21,9 @@
"./src/**/*",
"./src/interfaces/*.ts"
],
+ "exclude": [
+ "./src/.outdated"
+ ],
"lib": [
"es2017"
],