git.delta.rocks / unique-network / refs/commits / 01020524b715

difftreelog

Merge branch 'develop' into feature/app-staking

Max Andreev2022-09-06parents: #75d727e #fc6e541.patch.diff
in: master

24 files changed

modified.docker/Dockerfile-parachain-node-onlydiffbeforeafterboth
27RUN mkdir /unique_parachain27RUN mkdir /unique_parachain
28WORKDIR /unique_parachain28WORKDIR /unique_parachain
2929
30
30# ===== BUILD current version ======31# ===== BUILD current version ======
31FROM rust-builder as builder-unique-current32FROM rust-builder as builder-unique-current
3233
4546
46ARG PROFILE=release47ARG PROFILE=release
47ARG FEATURE=48ARG FEATURE=
48ARG BRANCH=
49ARG REPO_URL=
5049
51COPY . /unique_parachain50COPY . /unique_parachain
52WORKDIR /unique_parachain51WORKDIR /unique_parachain
modified.github/workflows/codestyle.ymldiffbeforeafterboth
11 - ready_for_review11 - ready_for_review
1212
13concurrency: 13concurrency:
14 group: ${{ github.workflow }}-${{ github.ref }}14 group: ${{ github.workflow }}-${{ github.head_ref }}
15 cancel-in-progress: true15 cancel-in-progress: true
1616
17jobs:17jobs:
modified.github/workflows/dev-build-tests.ymldiffbeforeafterboth
20 REPO_URL: ${{ github.server_url }}/${{ github.repository }}20 REPO_URL: ${{ github.server_url }}/${{ github.repository }}
2121
22concurrency: 22concurrency:
23 group: ${{ github.workflow }}-${{ github.ref }}23 group: ${{ github.workflow }}-${{ github.head_ref }}
24 cancel-in-progress: true24 cancel-in-progress: true
2525
26# A workflow run is made up of one or more jobs that can run sequentially or in parallel26# A workflow run is made up of one or more jobs that can run sequentially or in parallel
modified.github/workflows/forkless-update-data.ymldiffbeforeafterboth
20 REPO_URL: ${{ github.server_url }}/${{ github.repository }}20 REPO_URL: ${{ github.server_url }}/${{ github.repository }}
2121
22concurrency:22concurrency:
23 group: ${{ github.workflow }}-${{ github.ref }}23 group: ${{ github.workflow }}-${{ github.head_ref }}
24 cancel-in-progress: true24 cancel-in-progress: true
2525
26# A workflow run is made up of one or more jobs that can run sequentially or in parallel26# A workflow run is made up of one or more jobs that can run sequentially or in parallel
modified.github/workflows/forkless-update-nodata.ymldiffbeforeafterboth
20 REPO_URL: ${{ github.server_url }}/${{ github.repository }}20 REPO_URL: ${{ github.server_url }}/${{ github.repository }}
2121
22concurrency:22concurrency:
23 group: ${{ github.workflow }}-${{ github.ref }}23 group: ${{ github.workflow }}-${{ github.head_ref }}
24 cancel-in-progress: true24 cancel-in-progress: true
2525
26# A workflow run is made up of one or more jobs that can run sequentially or in parallel26# A workflow run is made up of one or more jobs that can run sequentially or in parallel
modified.github/workflows/nodes-only-update.ymldiffbeforeafterboth
20 REPO_URL: ${{ github.server_url }}/${{ github.repository }}20 REPO_URL: ${{ github.server_url }}/${{ github.repository }}
2121
22concurrency:22concurrency:
23 group: ${{ github.workflow }}-${{ github.ref }}23 group: ${{ github.workflow }}-${{ github.head_ref }}
24 cancel-in-progress: true24 cancel-in-progress: true
2525
26# A workflow run is made up of one or more jobs that can run sequentially or in parallel26# A workflow run is made up of one or more jobs that can run sequentially or in parallel
142 node-version: 16142 node-version: 16
143143
144 - name: Build the stack144 - name: Build the stack
145 run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" up -d --build --force-recreate --timeout 300145 run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" up -d --build --remove-orphans --force-recreate --timeout 300
146146
147 # 🚀 POLKADOT LAUNCH COMPLETE 🚀147 # 🚀 POLKADOT LAUNCH COMPLETE 🚀
148 - name: Check if docker logs consist messages related to testing of Node Parachain Upgrade.148 - name: Check if docker logs consist messages related to testing of Node Parachain Upgrade.
191 shell: bash191 shell: bash
192192
193 - name: Run tests before Node Parachain upgrade193 - name: Run tests before Node Parachain upgrade
194 working-directory: tests
194 run: |195 run: |
195 cd tests196 yarn install
196 yarn install197 yarn add mochawesome
197 yarn add mochawesome198 echo "Ready to start tests"
198 echo "Ready to start tests"199 NOW=$(date +%s) && yarn test --reporter mochawesome --reporter-options reportFilename=test-${NOW}
199 NOW=$(date +%s) && yarn test --reporter mochawesome --reporter-options reportFilename=test-${NOW}
200 env:200 env:
201 RPC_URL: http://127.0.0.1:9933/201 RPC_URL: http://127.0.0.1:9933/
202202
211 fail-on-error: 'false'211 fail-on-error: 'false'
212212
213 - name: Send SIGUSR1 to polkadotlaunch process213 - name: Send SIGUSR1 to polkadotlaunch process
214 if: success()214 if: success() || failure()
215 run: |215 run: |
216 #Get PID of polkadot-launch216 #Get PID of polkadot-launch
217 PID=$(docker exec node-parachain pidof 'polkadot-launch')217 PID=$(docker exec node-parachain pidof 'polkadot-launch')
266 shell: bash266 shell: bash
267267
268 - name: Run tests after Node Parachain upgrade268 - name: Run tests after Node Parachain upgrade
269 working-directory: tests
269 run: |270 run: |
270 cd tests271 yarn install
271 yarn install272 yarn add mochawesome
272 yarn add mochawesome273 echo "Ready to start tests"
273 echo "Ready to start tests"274 NOW=$(date +%s) && yarn test --reporter mochawesome --reporter-options reportFilename=test-${NOW}
274 NOW=$(date +%s) && yarn test --reporter mochawesome --reporter-options reportFilename=test-${NOW}
275 env:275 env:
276 RPC_URL: http://127.0.0.1:9933/276 RPC_URL: http://127.0.0.1:9933/
277277
288288
289 - name: Stop running containers289 - name: Stop running containers
290 if: always() # run this step always290 if: always() # run this step always
291 run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" down291 run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" down --volumes
292292
293 #docker-compose rm -f
294 - name: Remove Docker build artefacts293 - name: Remove builder cache
295 if: always() # run this step always294 if: always() # run this step always
296 run: docker-compose -f ".docker/docker-compose-forkless.yml" -f ".docker/docker-compose.node.${{ matrix.network }}.yml" rm -f295 run: |
296 docker builder prune -f
297 docker system prune -f
298
299 - name: Clean Workspace
300 if: always()
301 uses: AutoModality/action-clean@v1.1.0
297302
modified.github/workflows/tests_codestyle.ymldiffbeforeafterboth
11 - ready_for_review11 - ready_for_review
1212
13concurrency: 13concurrency:
14 group: ${{ github.workflow }}-${{ github.ref }}14 group: ${{ github.workflow }}-${{ github.head_ref }}
15 cancel-in-progress: true15 cancel-in-progress: true
1616
17jobs:17jobs:
modified.github/workflows/try-runtime.ymldiffbeforeafterboth
20 REPO_URL: ${{ github.server_url }}/${{ github.repository }}20 REPO_URL: ${{ github.server_url }}/${{ github.repository }}
2121
22concurrency: 22concurrency:
23 group: ${{ github.workflow }}-${{ github.ref }}23 group: ${{ github.workflow }}-${{ github.head_ref }}
24 cancel-in-progress: true24 cancel-in-progress: true
2525
26# A workflow run is made up of one or more jobs that can run sequentially or in parallel26# A workflow run is made up of one or more jobs that can run sequentially or in parallel
modified.github/workflows/unit-test.ymldiffbeforeafterboth
17 workflow_dispatch:17 workflow_dispatch:
1818
19concurrency: 19concurrency:
20 group: ${{ github.workflow }}-${{ github.ref }}20 group: ${{ github.workflow }}-${{ github.head_ref }}
21 cancel-in-progress: true21 cancel-in-progress: true
2222
23# A workflow run is made up of one or more jobs that can run sequentially or in parallel23# A workflow run is made up of one or more jobs that can run sequentially or in parallel
modifiedtests/package.jsondiffbeforeafterboth
30 "testEth": "mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.test.ts'",30 "testEth": "mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.test.ts'",
31 "testEthMarketplace": "mocha --timeout 9999999 -r ts-node/register './**/eth/marketplace/**/*.test.ts'",31 "testEthMarketplace": "mocha --timeout 9999999 -r ts-node/register './**/eth/marketplace/**/*.test.ts'",
32 "testEthNesting": "mocha --timeout 9999999 -r ts-node/register './**/eth/nesting/**/*.test.ts'",32 "testEthNesting": "mocha --timeout 9999999 -r ts-node/register './**/eth/nesting/**/*.test.ts'",
33 "testEthPayable": "mocha --timeout 9999999 -r ts-node/register './**/eth/payable.test.ts'",
33 "load": "mocha --timeout 9999999 -r ts-node/register './**/*.load.ts'",34 "load": "mocha --timeout 9999999 -r ts-node/register './**/*.load.ts'",
34 "loadTransfer": "ts-node src/transfer.nload.ts",35 "loadTransfer": "ts-node src/transfer.nload.ts",
35 "testCollision": "mocha --timeout 9999999 -r ts-node/register ./src/collision-tests/*.test.ts",36 "testCollision": "mocha --timeout 9999999 -r ts-node/register ./src/collision-tests/*.test.ts",
79 "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",80 "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
80 "testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",81 "testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",
81 "testLimits": "mocha --timeout 9999999 -r ts-node/register ./**/limits.test.ts",82 "testLimits": "mocha --timeout 9999999 -r ts-node/register ./**/limits.test.ts",
83 "testEthCreateNFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createNFTCollection.test.ts",
82 "testEthCreateCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createCollection.test.ts",84 "testEthCreateRFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createRFTCollection.test.ts",
83 "testRFT": "mocha --timeout 9999999 -r ts-node/register ./**/refungible.test.ts",85 "testRFT": "mocha --timeout 9999999 -r ts-node/register ./**/refungible.test.ts",
84 "testFT": "mocha --timeout 9999999 -r ts-node/register ./**/fungible.test.ts",86 "testFT": "mocha --timeout 9999999 -r ts-node/register ./**/fungible.test.ts",
85 "testRPC": "mocha --timeout 9999999 -r ts-node/register ./**/rpc.test.ts",87 "testRPC": "mocha --timeout 9999999 -r ts-node/register ./**/rpc.test.ts",
modifiedtests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth
24 getCollectionAddressFromResult, 24 getCollectionAddressFromResult,
25 itWeb3,25 itWeb3,
26 recordEthFee,26 recordEthFee,
27 subToEth,
28} from './util/helpers';27} from './util/helpers';
2928
30describe('Add collection admins', () => {29describe('Add collection admins', () => {
37 .send();36 .send();
38 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);37 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
3938
40 const newAdmin = await createEthAccount(web3);39 const newAdmin = createEthAccount(web3);
41 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);40 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
42 await collectionEvm.methods.addCollectionAdmin(newAdmin).send();41 await collectionEvm.methods.addCollectionAdmin(newAdmin).send();
43 const adminList = await api.rpc.unique.adminlist(collectionId);42 const adminList = await api.rpc.unique.adminlist(collectionId);
92 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);91 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
93 await collectionEvm.methods.addCollectionAdmin(admin).send();92 await collectionEvm.methods.addCollectionAdmin(admin).send();
94 93
95 const user = await createEthAccount(web3);94 const user = createEthAccount(web3);
96 await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: admin}))95 await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: admin}))
97 .to.be.rejectedWith('NoPermission');96 .to.be.rejectedWith('NoPermission');
9897
114 const notAdmin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);113 const notAdmin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
115 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);114 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
116 115
117 const user = await createEthAccount(web3);116 const user = createEthAccount(web3);
118 await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: notAdmin}))117 await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: notAdmin}))
119 .to.be.rejectedWith('NoPermission');118 .to.be.rejectedWith('NoPermission');
120119
175 .send();174 .send();
176 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);175 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
177176
178 const newAdmin = await createEthAccount(web3);177 const newAdmin = createEthAccount(web3);
179 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);178 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
180 await collectionEvm.methods.addCollectionAdmin(newAdmin).send();179 await collectionEvm.methods.addCollectionAdmin(newAdmin).send();
181 {180 {
226225
227 const admin0 = await createEthAccountWithBalance(api, web3, privateKeyWrapper);226 const admin0 = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
228 await collectionEvm.methods.addCollectionAdmin(admin0).send();227 await collectionEvm.methods.addCollectionAdmin(admin0).send();
229 const admin1 = await createEthAccount(web3);228 const admin1 = createEthAccount(web3);
230 await collectionEvm.methods.addCollectionAdmin(admin1).send();229 await collectionEvm.methods.addCollectionAdmin(admin1).send();
231230
232 await expect(collectionEvm.methods.removeCollectionAdmin(admin1).call({from: admin0}))231 await expect(collectionEvm.methods.removeCollectionAdmin(admin1).call({from: admin0}))
253252
254 const admin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);253 const admin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
255 await collectionEvm.methods.addCollectionAdmin(admin).send();254 await collectionEvm.methods.addCollectionAdmin(admin).send();
256 const notAdmin = await createEthAccount(web3);255 const notAdmin = createEthAccount(web3);
257256
258 await expect(collectionEvm.methods.removeCollectionAdmin(admin).call({from: notAdmin}))257 await expect(collectionEvm.methods.removeCollectionAdmin(admin).call({from: notAdmin}))
259 .to.be.rejectedWith('NoPermission');258 .to.be.rejectedWith('NoPermission');
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
1import {addToAllowListExpectSuccess, bigIntToSub, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess} from '../util/helpers';1import {addToAllowListExpectSuccess, bigIntToSub, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess} from '../util/helpers';
2import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub, subToEth} from './util/helpers';2import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub} from './util/helpers';
3import nonFungibleAbi from './nonFungibleAbi.json';3import nonFungibleAbi from './nonFungibleAbi.json';
4import {expect} from 'chai';4import {expect} from 'chai';
5import {evmToAddress} from '@polkadot/util-crypto';5import {evmToAddress} from '@polkadot/util-crypto';
modifiedtests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth
181 });181 });
182 182
183 itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {183 itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
184 const owner = await createEthAccount(web3);184 const owner = createEthAccount(web3);
185 const helper = evmCollectionHelpers(web3, owner);185 const helper = evmCollectionHelpers(web3, owner);
186 const collectionName = 'A';186 const collectionName = 'A';
187 const description = 'A';187 const description = 'A';
194194
195 itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {195 itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {
196 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);196 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
197 const notOwner = await createEthAccount(web3);197 const notOwner = createEthAccount(web3);
198 const collectionHelpers = evmCollectionHelpers(web3, owner);198 const collectionHelpers = evmCollectionHelpers(web3, owner);
199 const result = await collectionHelpers.methods.createNonfungibleCollection('A', 'A', 'A').send();199 const result = await collectionHelpers.methods.createNonfungibleCollection('A', 'A', 'A').send();
200 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);200 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
modifiedtests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth
189 });189 });
190 190
191 itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {191 itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
192 const owner = await createEthAccount(web3);192 const owner = createEthAccount(web3);
193 const helper = evmCollectionHelpers(web3, owner);193 const helper = evmCollectionHelpers(web3, owner);
194 const collectionName = 'A';194 const collectionName = 'A';
195 const description = 'A';195 const description = 'A';
202202
203 itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {203 itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {
204 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);204 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
205 const notOwner = await createEthAccount(web3);205 const notOwner = createEthAccount(web3);
206 const collectionHelpers = evmCollectionHelpers(web3, owner);206 const collectionHelpers = evmCollectionHelpers(web3, owner);
207 const result = await collectionHelpers.methods.createRefungibleCollection('A', 'A', 'A').send();207 const result = await collectionHelpers.methods.createRefungibleCollection('A', 'A', 'A').send();
208 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);208 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
modifiedtests/src/eth/nesting/nest.test.tsdiffbeforeafterboth
1import {ApiPromise} from '@polkadot/api';1import {IKeyringPair} from '@polkadot/types/types';
2import {Contract} from 'web3-eth-contract';2import {Contract} from 'web3-eth-contract';
3import {expect} from 'chai';3
4import Web3 from 'web3';
5import {createEthAccountWithBalance, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, tokenIdToAddress} from '../../eth/util/helpers';4import {itEth, EthUniqueHelper, usingEthPlaygrounds, expect} from '../util/playgrounds';
6import nonFungibleAbi from '../nonFungibleAbi.json';
75
8const createNestingCollection = async (6const createNestingCollection = async (
9 api: ApiPromise,7 helper: EthUniqueHelper,
10 web3: Web3,
11 owner: string,8 owner: string,
12): Promise<{ collectionId: number, collectionAddress: string, contract: Contract }> => {9): Promise<{ collectionId: number, collectionAddress: string, contract: Contract }> => {
13 const collectionHelper = evmCollectionHelpers(web3, owner);
14
15 const result = await collectionHelper.methods10 const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
16 .createNonfungibleCollection('A', 'B', 'C')
17 .send();
18 const {collectionIdAddress: collectionAddress, collectionId} = await getCollectionAddressFromResult(api, result);
1911
20 const contract = new web3.eth.Contract(nonFungibleAbi as any, collectionAddress, {from: owner, ...GAS_ARGS});12 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
21 await contract.methods.setCollectionNesting(true).send({from: owner});13 await contract.methods.setCollectionNesting(true).send({from: owner});
2214
23 return {collectionId, collectionAddress, contract};15 return {collectionId, collectionAddress, contract};
24};16};
2517
26describe('Integration Test: EVM Nesting', () => {
27 itWeb3('NFT: allows an Owner to nest/unnest their token', async ({api, web3, privateKeyWrapper}) => {
28 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
29 const {collectionId, contract} = await createNestingCollection(api, web3, owner);
30
31 // Create a token to be nested
32 const targetNFTTokenId = await contract.methods.nextTokenId().call();
33 await contract.methods.mint(
34 owner,
35 targetNFTTokenId,
36 ).send({from: owner});
37
38 const targetNftTokenAddress = tokenIdToAddress(collectionId, targetNFTTokenId);
39
40 // Create a nested token
41 const firstTokenId = await contract.methods.nextTokenId().call();
42 await contract.methods.mint(
43 targetNftTokenAddress,
44 firstTokenId,
45 ).send({from: owner});
46
47 expect(await contract.methods.ownerOf(firstTokenId).call()).to.be.equal(targetNftTokenAddress);
48
49 // Create a token to be nested and nest
50 const secondTokenId = await contract.methods.nextTokenId().call();
51 await contract.methods.mint(
52 owner,
53 secondTokenId,
54 ).send({from: owner});
55
56 await contract.methods.transfer(targetNftTokenAddress, secondTokenId).send({from: owner});
57
58 expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(targetNftTokenAddress);
59
60 // Unnest token back
61 await contract.methods.transferFrom(targetNftTokenAddress, owner, secondTokenId).send({from: owner});
62 expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
63 });
64
65 itWeb3('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({api, web3, privateKeyWrapper}) => {
66 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
67
68 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(api, web3, owner);
69 const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(api, web3, owner);
70 await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
71
72 // Create a token to nest into
73 const targetNftTokenId = await contractA.methods.nextTokenId().call();
74 await contractA.methods.mint(
75 owner,
76 targetNftTokenId,
77 ).send({from: owner});
78 const nftTokenAddressA1 = tokenIdToAddress(collectionIdA, targetNftTokenId);
79
80 // Create a token for nesting in the same collection as the target
81 const nftTokenIdA = await contractA.methods.nextTokenId().call();
82 await contractA.methods.mint(
83 owner,
84 nftTokenIdA,
85 ).send({from: owner});
86
87 // Create a token for nesting in a different collection
88 const nftTokenIdB = await contractB.methods.nextTokenId().call();
89 await contractB.methods.mint(
90 owner,
91 nftTokenIdB,
92 ).send({from: owner});
93
94 // Nest
95 await contractA.methods.transfer(nftTokenAddressA1, nftTokenIdA).send({from: owner});
96 expect(await contractA.methods.ownerOf(nftTokenIdA).call()).to.be.equal(nftTokenAddressA1);
97
98 await contractB.methods.transfer(nftTokenAddressA1, nftTokenIdB).send({from: owner});
99 expect(await contractB.methods.ownerOf(nftTokenIdB).call()).to.be.equal(nftTokenAddressA1);
100 });
101});
10218
103describe('Negative Test: EVM Nesting', async() => {19describe('EVM nesting tests group', () => {
20 let donor: IKeyringPair;
21
22 before(async function() {
23 await usingEthPlaygrounds(async (helper, privateKey) => {
24 donor = privateKey('//Alice');
25 });
26 });
27
28 describe('Integration Test: EVM Nesting', () => {
29 itEth('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {
30 const owner = await helper.eth.createAccountWithBalance(donor);
31 const {collectionId, contract} = await createNestingCollection(helper, owner);
32
33 // Create a token to be nested
34 const targetNFTTokenId = await contract.methods.nextTokenId().call();
35 await contract.methods.mint(
36 owner,
37 targetNFTTokenId,
38 ).send({from: owner});
39
40 const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNFTTokenId);
41
42 // Create a nested token
43 const firstTokenId = await contract.methods.nextTokenId().call();
44 await contract.methods.mint(
45 targetNftTokenAddress,
46 firstTokenId,
47 ).send({from: owner});
48
49 expect(await contract.methods.ownerOf(firstTokenId).call()).to.be.equal(targetNftTokenAddress);
50
51 // Create a token to be nested and nest
52 const secondTokenId = await contract.methods.nextTokenId().call();
53 await contract.methods.mint(
54 owner,
55 secondTokenId,
56 ).send({from: owner});
57
58 await contract.methods.transfer(targetNftTokenAddress, secondTokenId).send({from: owner});
59
60 expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(targetNftTokenAddress);
61
62 // Unnest token back
63 await contract.methods.transferFrom(targetNftTokenAddress, owner, secondTokenId).send({from: owner});
64 expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
65 });
66
67 itEth('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
68 const owner = await helper.eth.createAccountWithBalance(donor);
69
70 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
71 const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
72 await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
73
74 // Create a token to nest into
75 const targetNftTokenId = await contractA.methods.nextTokenId().call();
76 await contractA.methods.mint(
77 owner,
78 targetNftTokenId,
79 ).send({from: owner});
80 const nftTokenAddressA1 = helper.ethAddress.fromTokenId(collectionIdA, targetNftTokenId);
81
82 // Create a token for nesting in the same collection as the target
83 const nftTokenIdA = await contractA.methods.nextTokenId().call();
84 await contractA.methods.mint(
85 owner,
86 nftTokenIdA,
87 ).send({from: owner});
88
89 // Create a token for nesting in a different collection
90 const nftTokenIdB = await contractB.methods.nextTokenId().call();
91 await contractB.methods.mint(
92 owner,
93 nftTokenIdB,
94 ).send({from: owner});
95
96 // Nest
97 await contractA.methods.transfer(nftTokenAddressA1, nftTokenIdA).send({from: owner});
98 expect(await contractA.methods.ownerOf(nftTokenIdA).call()).to.be.equal(nftTokenAddressA1);
99
100 await contractB.methods.transfer(nftTokenAddressA1, nftTokenIdB).send({from: owner});
101 expect(await contractB.methods.ownerOf(nftTokenIdB).call()).to.be.equal(nftTokenAddressA1);
102 });
103 });
104
105 describe('Negative Test: EVM Nesting', async() => {
104 itWeb3('NFT: disallows to nest token if nesting is disabled', async ({api, web3, privateKeyWrapper}) => {106 itEth('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {
105 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);107 const owner = await helper.eth.createAccountWithBalance(donor);
106108
107 const {collectionId, contract} = await createNestingCollection(api, web3, owner);109 const {collectionId, contract} = await createNestingCollection(helper, owner);
108 await contract.methods.setCollectionNesting(false).send({from: owner});110 await contract.methods.setCollectionNesting(false).send({from: owner});
109111
110 // Create a token to nest into112 // Create a token to nest into
114 targetNftTokenId,116 targetNftTokenId,
115 ).send({from: owner});117 ).send({from: owner});
116118
117 const targetNftTokenAddress = tokenIdToAddress(collectionId, targetNftTokenId);119 const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNftTokenId);
118120
119 // Create a token to nest121 // Create a token to nest
120 const nftTokenId = await contract.methods.nextTokenId().call();122 const nftTokenId = await contract.methods.nextTokenId().call();
129 .call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');131 .call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
130 });132 });
131133
132 itWeb3('NFT: disallows a non-Owner to nest someone else\'s token', async ({api, web3, privateKeyWrapper}) => {134 itEth('NFT: disallows a non-Owner to nest someone else\'s token', async ({helper}) => {
133 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);135 const owner = await helper.eth.createAccountWithBalance(donor);
134 const malignant = await createEthAccountWithBalance(api, web3, privateKeyWrapper);136 const malignant = await helper.eth.createAccountWithBalance(donor);
135137
136 const {collectionId, contract} = await createNestingCollection(api, web3, owner);138 const {collectionId, contract} = await createNestingCollection(helper, owner);
137139
138 // Mint a token140 // Mint a token
139 const targetTokenId = await contract.methods.nextTokenId().call();141 const targetTokenId = await contract.methods.nextTokenId().call();
140 await contract.methods.mint(142 await contract.methods.mint(
141 owner,143 owner,
142 targetTokenId,144 targetTokenId,
143 ).send({from: owner});145 ).send({from: owner});
144 const targetTokenAddress = tokenIdToAddress(collectionId, targetTokenId);146 const targetTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetTokenId);
145147
146 // Mint a token belonging to a different account148 // Mint a token belonging to a different account
147 const tokenId = await contract.methods.nextTokenId().call();149 const tokenId = await contract.methods.nextTokenId().call();
156 .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');158 .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
157 });159 });
158160
159 itWeb3('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({api, web3, privateKeyWrapper}) => {161 itEth('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({helper}) => {
160 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);162 const owner = await helper.eth.createAccountWithBalance(donor);
161 const malignant = await createEthAccountWithBalance(api, web3, privateKeyWrapper);163 const malignant = await helper.eth.createAccountWithBalance(donor);
162164
163 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(api, web3, owner);165 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
164 const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(api, web3, owner);166 const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
165167
166 await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});168 await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
167169
171 owner,173 owner,
172 nftTokenIdA,174 nftTokenIdA,
173 ).send({from: owner});175 ).send({from: owner});
174 const nftTokenAddressA = tokenIdToAddress(collectionIdA, nftTokenIdA);176 const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
175177
176 // Create a token in another collection belonging to someone else178 // Create a token in another collection belonging to someone else
177 const nftTokenIdB = await contractB.methods.nextTokenId().call();179 const nftTokenIdB = await contractB.methods.nextTokenId().call();
186 .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');188 .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
187 });189 });
188190
189 itWeb3('NFT: disallows to nest token in an unlisted collection', async ({api, web3, privateKeyWrapper}) => {191 itEth('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {
190 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);192 const owner = await helper.eth.createAccountWithBalance(donor);
191193
192 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(api, web3, owner);194 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
193 const {contract: contractB} = await createNestingCollection(api, web3, owner);195 const {contract: contractB} = await createNestingCollection(helper, owner);
194196
195 await contractA.methods.setCollectionNesting(true, [collectionAddressA]).send({from: owner});197 await contractA.methods.setCollectionNesting(true, [collectionAddressA]).send({from: owner});
196198
200 owner,202 owner,
201 nftTokenIdA,203 nftTokenIdA,
202 ).send({from: owner});204 ).send({from: owner});
203 const nftTokenAddressA = tokenIdToAddress(collectionIdA, nftTokenIdA);205 const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
204206
205 // Create a token in another collection207 // Create a token in another collection
206 const nftTokenIdB = await contractB.methods.nextTokenId().call();208 const nftTokenIdB = await contractB.methods.nextTokenId().call();
214 .transfer(nftTokenAddressA, nftTokenIdB)216 .transfer(nftTokenAddressA, nftTokenIdB)
215 .call()).to.be.rejectedWith('SourceCollectionIsNotAllowedToNest');217 .call()).to.be.rejectedWith('SourceCollectionIsNotAllowedToNest');
216 });218 });
217});219 });
220});
218221
modifiedtests/src/eth/payable.test.tsdiffbeforeafterboth
14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License
15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
1616
17import {expect} from 'chai';
18import {submitTransactionAsync} from '../substrate/substrate-api';17import {IKeyringPair} from '@polkadot/types/types';
18
19import {createEthAccountWithBalance, deployCollector, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';19import {itEth, expect, usingEthPlaygrounds} from './util/playgrounds';
20import {evmToAddress} from '@polkadot/util-crypto';
21import {getGenericResult, UNIQUE} from '../util/helpers';
22import {getBalanceSingle, transferBalanceExpectSuccess} from '../substrate/get-balance';
2320
24describe('EVM payable contracts', () => {21describe('EVM payable contracts', () => {
22 let donor: IKeyringPair;
23
24 before(async function() {
25 await usingEthPlaygrounds(async (helper, privateKey) => {
26 donor = privateKey('//Alice');
27 });
28 });
29
25 itWeb3('Evm contract can receive wei from eth account', async ({api, web3, privateKeyWrapper}) => {30 itEth('Evm contract can receive wei from eth account', async ({helper}) => {
26 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);31 const deployer = await helper.eth.createAccountWithBalance(donor);
27 const contract = await deployCollector(web3, deployer);32 const contract = await helper.eth.deployCollectorContract(deployer);
33
34 const web3 = helper.getWeb3();
2835
29 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: '10000', ...GAS_ARGS});36 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: '10000', gas: helper.eth.DEFAULT_GAS});
3037
31 expect(await contract.methods.getCollected().call()).to.be.equal('10000');38 expect(await contract.methods.getCollected().call()).to.be.equal('10000');
32 });39 });
3340
34 itWeb3('Evm contract can receive wei from substrate account', async ({api, web3, privateKeyWrapper}) => {41 itEth('Evm contract can receive wei from substrate account', async ({helper}) => {
35 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);42 const deployer = await helper.eth.createAccountWithBalance(donor);
36 const contract = await deployCollector(web3, deployer);43 const contract = await helper.eth.deployCollectorContract(deployer);
37 const alice = privateKeyWrapper('//Alice');44 const [alice] = await helper.arrange.createAccounts([10n], donor);
45
46 const weiCount = '10000';
3847
39 // Transaction fee/value will be payed from subToEth(sender) evm balance,48 // Transaction fee/value will be payed from subToEth(sender) evm balance,
40 // which is backed by evmToAddress(subToEth(sender)) substrate balance49 // which is backed by evmToAddress(subToEth(sender)) substrate balance
41 await transferBalanceToEth(api, alice, subToEth(alice.address));50 await helper.eth.transferBalanceFromSubstrate(alice, helper.address.substrateToEth(alice.address), 5n);
4251
43 {52
44 const tx = api.tx.evm.call(53 await helper.eth.callEVM(alice, contract.options.address, contract.methods.giveMoney().encodeABI(), weiCount);
45 subToEth(alice.address),
46 contract.options.address,
47 contract.methods.giveMoney().encodeABI(),
52 null,
53 [],
54 );
55 const events = await submitTransactionAsync(alice, tx);
56 const result = getGenericResult(events);
57 expect(result.success).to.be.true;
58 }
5954
60 expect(await contract.methods.getCollected().call()).to.be.equal('10000');55 expect(await contract.methods.getCollected().call()).to.be.equal(weiCount);
61 });56 });
6257
63 // We can't handle sending balance to backing storage of evm balance, because evmToAddress operation is irreversible58 // We can't handle sending balance to backing storage of evm balance, because evmToAddress operation is irreversible
64 itWeb3('Wei sent directly to backing storage of evm contract balance is unaccounted', async({api, web3, privateKeyWrapper}) => {59 itEth('Wei sent directly to backing storage of evm contract balance is unaccounted', async({helper}) => {
65 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);60 const deployer = await helper.eth.createAccountWithBalance(donor);
66 const contract = await deployCollector(web3, deployer);61 const contract = await helper.eth.deployCollectorContract(deployer);
67 const alice = privateKeyWrapper('//Alice');62 const [alice] = await helper.arrange.createAccounts([10n], donor);
63
64 const weiCount = 10_000n;
6865
69 await transferBalanceExpectSuccess(api, alice, evmToAddress(contract.options.address), '10000');66 await helper.eth.transferBalanceFromSubstrate(alice, contract.options.address, weiCount, false);
7067
71 expect(await contract.methods.getUnaccounted().call()).to.be.equal('10000');68 expect(await contract.methods.getUnaccounted().call()).to.be.equal(weiCount.toString());
72 });69 });
7370
74 itWeb3('Balance can be retrieved from evm contract', async({api, web3, privateKeyWrapper}) => {71 itEth('Balance can be retrieved from evm contract', async({helper, privateKey}) => {
75 const FEE_BALANCE = 1000n * UNIQUE;72 const FEE_BALANCE = 10n * helper.balance.getOneTokenNominal();
76 const CONTRACT_BALANCE = 1n * UNIQUE;73 const CONTRACT_BALANCE = 1n * helper.balance.getOneTokenNominal();
7774
78 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);75 const deployer = await helper.eth.createAccountWithBalance(donor);
79 const contract = await deployCollector(web3, deployer);76 const contract = await helper.eth.deployCollectorContract(deployer);
80 const alice = privateKeyWrapper('//Alice');77 const [alice] = await helper.arrange.createAccounts([20n], donor);
78
79 const web3 = helper.getWeb3();
8180
82 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), ...GAS_ARGS});81 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), gas: helper.eth.DEFAULT_GAS});
8382
84 const receiver = privateKeyWrapper(`//Receiver${Date.now()}`);83 const receiver = privateKey(`//Receiver${Date.now()}`);
8584
86 // First receive balance on eth balance of bob85 // First receive balance on eth balance of bob
87 {86 {
88 const ethReceiver = subToEth(receiver.address);87 const ethReceiver = helper.address.substrateToEth(receiver.address);
89 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal('0');88 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal('0');
90 await contract.methods.withdraw(ethReceiver).send({from: deployer});89 await contract.methods.withdraw(ethReceiver).send({from: deployer});
91 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal(CONTRACT_BALANCE.toString());90 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal(CONTRACT_BALANCE.toString());
92 }91 }
9392
94 // Some balance is required to pay fee for evm.withdraw call93 // Some balance is required to pay fee for evm.withdraw call
95 await transferBalanceExpectSuccess(api, alice, receiver.address, FEE_BALANCE.toString());94 await helper.balance.transferToSubstrate(alice, receiver.address, FEE_BALANCE);
95 // await transferBalanceExpectSuccess(api, alice, receiver.address, FEE_BALANCE.toString());
9696
97 // Withdraw balance from eth to substrate97 // Withdraw balance from eth to substrate
98 {98 {
99 const initialReceiverBalance = await getBalanceSingle(api, receiver.address);99 const initialReceiverBalance = await helper.balance.getSubstrate(receiver.address);
100 const tx = api.tx.evm.withdraw(100 await helper.executeExtrinsic(receiver, 'api.tx.evm.withdraw', [helper.address.substrateToEth(receiver.address), CONTRACT_BALANCE.toString()], true);
101 subToEth(receiver.address),
102 CONTRACT_BALANCE.toString(),
103 );
104 const events = await submitTransactionAsync(receiver, tx);
105 const result = getGenericResult(events);
106 expect(result.success).to.be.true;
107 const finalReceiverBalance = await getBalanceSingle(api, receiver.address);101 const finalReceiverBalance = await helper.balance.getSubstrate(receiver.address);
108102
109 expect(finalReceiverBalance > initialReceiverBalance).to.be.true;103 expect(finalReceiverBalance > initialReceiverBalance).to.be.true;
110 }104 }
modifiedtests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth
15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
1616
17import {approve, createCollection, createRefungibleToken, transfer, transferFrom, UNIQUE, requirePallets, Pallets} from '../util/helpers';17import {approve, createCollection, createRefungibleToken, transfer, transferFrom, UNIQUE, requirePallets, Pallets} from '../util/helpers';
18import {collectionIdFromAddress, collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';18import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createRefungibleCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';
1919
20import chai from 'chai';20import chai from 'chai';
21import chaiAsPromised from 'chai-as-promised';21import chaiAsPromised from 'chai-as-promised';
addedtests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth

no changes

addedtests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth

no changes

addedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth

no changes

modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
25import privateKey from './privateKey';25import privateKey from './privateKey';
26import promisifySubstrate from './promisify-substrate';26import promisifySubstrate from './promisify-substrate';
27
28import {SilentConsole} from '../util/playgrounds/unique.dev';
2729
2830
2931
76 const api: ApiPromise = new ApiPromise(settings);78 const api: ApiPromise = new ApiPromise(settings);
77 let result: T = null as unknown as T;79 let result: T = null as unknown as T;
78
79 // TODO: Remove, this is temporary: Filter unneeded API output
80 // (Jaco promised it will be removed in the next version)
81 const consoleErr = console.error;
82 const consoleLog = console.log;
83 const consoleWarn = console.warn;
8480
85 const outFn = (printer: any) => (...args: any[]) => {81 const silentConsole = new SilentConsole();
86 for (const arg of args) {
87 if (typeof arg !== 'string')
88 continue;
89 if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))
90 return;
91 }
92 printer(...args);
93 };
94
95 console.error = outFn(consoleErr.bind(console));82 silentConsole.enable();
96 console.log = outFn(consoleLog.bind(console));
97 console.warn = outFn(consoleWarn.bind(console));
9883
99 try {84 try {
100 await promisifySubstrate(api, async () => {85 await promisifySubstrate(api, async () => {
107 })();92 })();
108 } finally {93 } finally {
109 await api.disconnect();94 await api.disconnect();
110 console.error = consoleErr;95 silentConsole.disable();
111 console.log = consoleLog;
112 console.warn = consoleWarn;
113 }96 }
114 return result as T;97 return result as T;
115}98}
modifiedtests/src/util/playgrounds/index.tsdiffbeforeafterboth
4import {IKeyringPair} from '@polkadot/types/types';4import {IKeyringPair} from '@polkadot/types/types';
5import config from '../../config';5import config from '../../config';
6import '../../interfaces/augment-api-events';6import '../../interfaces/augment-api-events';
7import {DevUniqueHelper} from './unique.dev';7import {DevUniqueHelper, SilentLogger, SilentConsole} from './unique.dev';
8
9
10class SilentLogger {
11 log(msg: any, level: any): void { }
12 level = {
13 ERROR: 'ERROR' as const,
14 WARNING: 'WARNING' as const,
15 INFO: 'INFO' as const,
16 };
17}
18
19
208
219
22export const usingPlaygrounds = async <T = void> (code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<T>) => {10export const usingPlaygrounds = async (code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
23 // TODO: Remove, this is temporary: Filter unneeded API output
24 // (Jaco promised it will be removed in the next version)
25 const consoleErr = console.error;
26 const consoleLog = console.log;
27 const consoleWarn = console.warn;
28 let result: T = null as unknown as T;
29
30 const outFn = (printer: any) => (...args: any[]) => {11 const silentConsole = new SilentConsole();
31 for (const arg of args) {
32 if (typeof arg !== 'string')
33 continue;
34 if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))
35 return;
36 }
37 printer(...args);
38 };
39
40 console.error = outFn(consoleErr.bind(console));12 silentConsole.enable();
41 console.log = outFn(consoleLog.bind(console));13
42 console.warn = outFn(consoleWarn.bind(console));
43 const helper = new DevUniqueHelper(new SilentLogger());14 const helper = new DevUniqueHelper(new SilentLogger());
4415
45 try {16 try {
46 await helper.connect(config.substrateUrl);17 await helper.connect(config.substrateUrl);
47 const ss58Format = helper.chain.getChainProperties().ss58Format;18 const ss58Format = helper.chain.getChainProperties().ss58Format;
48 const privateKey = (seed: string) => helper.util.fromSeed(seed, ss58Format);19 const privateKey = (seed: string) => helper.util.fromSeed(seed, ss58Format);
49 result = await code(helper, privateKey);20 await code(helper, privateKey);
50 }21 }
51 finally {22 finally {
52 await helper.disconnect();23 await helper.disconnect();
53 console.error = consoleErr;24 silentConsole.disable();
54 console.log = consoleLog;
55 console.warn = consoleWarn;
56 }25 }
57 return result as T;
58};26};
27
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
8import {IKeyringPair} from '@polkadot/types/types';8import {IKeyringPair} from '@polkadot/types/types';
9
10
11export class SilentLogger {
12 log(_msg: any, _level: any): void { }
13 level = {
14 ERROR: 'ERROR' as const,
15 WARNING: 'WARNING' as const,
16 INFO: 'INFO' as const,
17 };
18}
19
20
21export class SilentConsole {
22 // TODO: Remove, this is temporary: Filter unneeded API output
23 // (Jaco promised it will be removed in the next version)
24 consoleErr: any;
25 consoleLog: any;
26 consoleWarn: any;
27
28 constructor() {
29 this.consoleErr = console.error;
30 this.consoleLog = console.log;
31 this.consoleWarn = console.warn;
32 }
33
34 enable() {
35 const outFn = (printer: any) => (...args: any[]) => {
36 for (const arg of args) {
37 if (typeof arg !== 'string')
38 continue;
39 if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis: UniqueApi/2, RmrkApi/1') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
40 return;
41 }
42 printer(...args);
43 };
44
45 console.error = outFn(this.consoleErr.bind(console));
46 console.log = outFn(this.consoleLog.bind(console));
47 console.warn = outFn(this.consoleWarn.bind(console));
48 }
49
50 disable() {
51 console.error = this.consoleErr;
52 console.log = this.consoleLog;
53 console.warn = this.consoleWarn;
54 }
55}
956
1057
11export class DevUniqueHelper extends UniqueHelper {58export class DevUniqueHelper extends UniqueHelper {
19 this.arrange = new ArrangeGroup(this);66 this.arrange = new ArrangeGroup(this);
20 }67 }
2168
22 async connect(wsEndpoint: string, listeners?: any): Promise<void> {69 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
23 const wsProvider = new WsProvider(wsEndpoint);70 const wsProvider = new WsProvider(wsEndpoint);
24 this.api = new ApiPromise({71 this.api = new ApiPromise({
25 provider: wsProvider,72 provider: wsProvider,
85 }132 }
86 }133 }
87134
88 await Promise.all(transactions).catch(e => {});135 await Promise.all(transactions).catch(_e => {});
89 136
90 //#region TODO remove this region, when nonce problem will be solved137 //#region TODO remove this region, when nonce problem will be solved
91 const checkBalances = async () => {138 const checkBalances = async () => {
186 * @returns 233 * @returns
187 */234 */
188 async waitNewBlocks(blocksCount = 1): Promise<void> {235 async waitNewBlocks(blocksCount = 1): Promise<void> {
236 // eslint-disable-next-line no-async-promise-executor
189 const promise = new Promise<void>(async (resolve) => {237 const promise = new Promise<void>(async (resolve) => {
190 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {238 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {
191 if (blocksCount > 0) {239 if (blocksCount > 0) {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
91 return encodeAddress(decodeAddress(address), ss58Format);91 return encodeAddress(decodeAddress(address), ss58Format);
92 }92 }
9393
94 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {94 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {
95 if (creationResult.status !== this.transactionStatus.SUCCESS) {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {
96 throw Error(`Unable to create collection for ${label}`);96 throw Error('Unable to create collection!');
97 }97 }
9898
99 let collectionId = null;99 let collectionId = null;
104 });104 });
105105
106 if (collectionId === null) {106 if (collectionId === null) {
107 throw Error(`No CollectionCreated event for ${label}`);107 throw Error('No CollectionCreated event was found!');
108 }108 }
109109
110 return collectionId;110 return collectionId;
111 }111 }
112112
113 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {113 static extractTokensFromCreationResult(creationResult: ITransactionResult) {
114 if (creationResult.status !== this.transactionStatus.SUCCESS) {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {
115 throw Error(`Unable to create tokens for ${label}`);115 throw Error('Unable to create tokens!');
116 }116 }
117 let success = false;117 let success = false;
118 const tokens = [] as any;118 const tokens = [] as any;
130 return {success, tokens};130 return {success, tokens};
131 }131 }
132132
133 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {133 static extractTokensFromBurnResult(burnResult: ITransactionResult) {
134 if (burnResult.status !== this.transactionStatus.SUCCESS) {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {
135 throw Error(`Unable to burn tokens for ${label}`);135 throw Error('Unable to burn tokens!');
136 }136 }
137 let success = false;137 let success = false;
138 const tokens = [] as any;138 const tokens = [] as any;
150 return {success, tokens};150 return {success, tokens};
151 }151 }
152152
153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {
154 let eventId = null;154 let eventId = null;
155 events.forEach(({event: {data, method, section}}) => {155 events.forEach(({event: {data, method, section}}) => {
156 if ((section === expectedSection) && (method === expectedMethod)) {156 if ((section === expectedSection) && (method === expectedMethod)) {
159 });159 });
160160
161 if (eventId === null) {161 if (eventId === null) {
162 throw Error(`No ${expectedMethod} event for ${label}`);162 throw Error(`No ${expectedMethod} event was found!`);
163 }163 }
164 return eventId === collectionId;164 return eventId === collectionId;
165 }165 }
317 if(options !== null) return transaction.signAndSend(sender, options, callback);317 if(options !== null) return transaction.signAndSend(sender, options, callback);
318 return transaction.signAndSend(sender, callback);318 return transaction.signAndSend(sender, callback);
319 };319 };
320 // eslint-disable-next-line no-async-promise-executor
320 return new Promise(async (resolve, reject) => {321 return new Promise(async (resolve, reject) => {
321 try {322 try {
322 const unsub = await sign((result: any) => {323 const unsub = await sign((result: any) => {
364 return call(...params);365 return call(...params);
365 }366 }
366367
367 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {368 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false/*, failureMessage='expected success'*/) {
368 if(this.api === null) throw Error('API not initialized');369 if(this.api === null) throw Error('API not initialized');
369 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);370 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);
370371
388 type: this.chainLogType.EXTRINSIC,389 type: this.chainLogType.EXTRINSIC,
389 status: result.status,390 status: result.status,
390 call: extrinsic,391 call: extrinsic,
392 signer: this.getSignerAddress(sender),
391 params,393 params,
392 } as IUniqueHelperLog;394 } as IUniqueHelperLog;
393395
396398
397 this.chainLog.push(log);399 this.chainLog.push(log);
398400
399 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);401 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);
400 return result;402 return result;
401 }403 }
402404
556 * 558 *
557 * @param signer keyring of signer559 * @param signer keyring of signer
558 * @param collectionId ID of collection560 * @param collectionId ID of collection
559 * @param label extra label for log
560 * @example await helper.collection.burn(aliceKeyring, 3);561 * @example await helper.collection.burn(aliceKeyring, 3);
561 * @returns ```true``` if extrinsic success, otherwise ```false```562 * @returns ```true``` if extrinsic success, otherwise ```false```
562 */563 */
563 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {564 async burn(signer: TSigner, collectionId: number): Promise<boolean> {
564 if(typeof label === 'undefined') label = `collection #${collectionId}`;
565 const result = await this.helper.executeExtrinsic(565 const result = await this.helper.executeExtrinsic(
566 signer,566 signer,
567 'api.tx.unique.destroyCollection', [collectionId],567 'api.tx.unique.destroyCollection', [collectionId],
568 true, `Unable to burn collection for ${label}`,568 true,
569 );569 );
570570
571 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);571 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');
572 }572 }
573573
574 /**574 /**
577 * @param signer keyring of signer577 * @param signer keyring of signer
578 * @param collectionId ID of collection578 * @param collectionId ID of collection
579 * @param sponsorAddress Sponsor substrate address579 * @param sponsorAddress Sponsor substrate address
580 * @param label extra label for log
581 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")580 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")
582 * @returns ```true``` if extrinsic success, otherwise ```false```581 * @returns ```true``` if extrinsic success, otherwise ```false```
583 */582 */
584 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {583 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {
585 if(typeof label === 'undefined') label = `collection #${collectionId}`;
586 const result = await this.helper.executeExtrinsic(584 const result = await this.helper.executeExtrinsic(
587 signer,585 signer,
588 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],586 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],
589 true, `Unable to set collection sponsor for ${label}`,587 true,
590 );588 );
591589
592 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);590 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');
593 }591 }
594592
595 /**593 /**
596 * Confirms consent to sponsor the collection on behalf of the signer.594 * Confirms consent to sponsor the collection on behalf of the signer.
597 * 595 *
598 * @param signer keyring of signer596 * @param signer keyring of signer
599 * @param collectionId ID of collection597 * @param collectionId ID of collection
600 * @param label extra label for log
601 * @example confirmSponsorship(aliceKeyring, 10)598 * @example confirmSponsorship(aliceKeyring, 10)
602 * @returns ```true``` if extrinsic success, otherwise ```false```599 * @returns ```true``` if extrinsic success, otherwise ```false```
603 */600 */
604 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {601 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {
605 if(typeof label === 'undefined') label = `collection #${collectionId}`;
606 const result = await this.helper.executeExtrinsic(602 const result = await this.helper.executeExtrinsic(
607 signer,603 signer,
608 'api.tx.unique.confirmSponsorship', [collectionId],604 'api.tx.unique.confirmSponsorship', [collectionId],
609 true, `Unable to confirm collection sponsorship for ${label}`,605 true,
610 );606 );
611607
612 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);608 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');
613 }609 }
614610
615 /**611 /**
618 * @param signer keyring of signer614 * @param signer keyring of signer
619 * @param collectionId ID of collection615 * @param collectionId ID of collection
620 * @param limits collection limits object616 * @param limits collection limits object
621 * @param label extra label for log
622 * @example617 * @example
623 * await setLimits(618 * await setLimits(
624 * aliceKeyring,619 * aliceKeyring,
630 * )625 * )
631 * @returns ```true``` if extrinsic success, otherwise ```false```626 * @returns ```true``` if extrinsic success, otherwise ```false```
632 */627 */
633 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {628 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {
634 if(typeof label === 'undefined') label = `collection #${collectionId}`;
635 const result = await this.helper.executeExtrinsic(629 const result = await this.helper.executeExtrinsic(
636 signer,630 signer,
637 'api.tx.unique.setCollectionLimits', [collectionId, limits],631 'api.tx.unique.setCollectionLimits', [collectionId, limits],
638 true, `Unable to set collection limits for ${label}`,632 true,
639 );633 );
640634
641 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);635 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');
642 }636 }
643637
644 /**638 /**
647 * @param signer keyring of signer641 * @param signer keyring of signer
648 * @param collectionId ID of collection642 * @param collectionId ID of collection
649 * @param ownerAddress substrate address of new owner643 * @param ownerAddress substrate address of new owner
650 * @param label extra label for log
651 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")644 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")
652 * @returns ```true``` if extrinsic success, otherwise ```false```645 * @returns ```true``` if extrinsic success, otherwise ```false```
653 */646 */
654 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {647 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {
655 if(typeof label === 'undefined') label = `collection #${collectionId}`;
656 const result = await this.helper.executeExtrinsic(648 const result = await this.helper.executeExtrinsic(
657 signer,649 signer,
658 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],650 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],
659 true, `Unable to change collection owner for ${label}`,651 true,
660 );652 );
661653
662 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);654 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');
663 }655 }
664656
665 /**657 /**
668 * @param signer keyring of signer660 * @param signer keyring of signer
669 * @param collectionId ID of collection661 * @param collectionId ID of collection
670 * @param adminAddressObj Administrator address (substrate or ethereum)662 * @param adminAddressObj Administrator address (substrate or ethereum)
671 * @param label extra label for log
672 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})663 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})
673 * @returns ```true``` if extrinsic success, otherwise ```false```664 * @returns ```true``` if extrinsic success, otherwise ```false```
674 */665 */
675 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {666 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {
676 if(typeof label === 'undefined') label = `collection #${collectionId}`;
677 const result = await this.helper.executeExtrinsic(667 const result = await this.helper.executeExtrinsic(
678 signer,668 signer,
679 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],669 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],
680 true, `Unable to add collection admin for ${label}`,670 true,
681 );671 );
682672
683 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);673 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');
684 }674 }
685675
686 /**676 /**
677 * Removes a collection administrator.
678 *
679 * @param signer keyring of signer
680 * @param collectionId ID of collection
681 * @param adminAddressObj Administrator address (substrate or ethereum)
682 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})
683 * @returns ```true``` if extrinsic success, otherwise ```false```
684 */
685 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {
686 const result = await this.helper.executeExtrinsic(
687 signer,
688 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],
689 true,
690 );
691
692 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');
693 }
694
695 /**
687 * Adds an address to allow list 696 * Adds an address to allow list
688 * @param signer keyring of signer697 * @param signer keyring of signer
689 * @param collectionId ID of collection698 * @param collectionId ID of collection
690 * @param addressObj address to add to the allow list699 * @param addressObj address to add to the allow list
691 * @param label extra label for log
692 * @returns ```true``` if extrinsic success, otherwise ```false```700 * @returns ```true``` if extrinsic success, otherwise ```false```
693 */701 */
694 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId, label?: string): Promise<boolean> {702 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {
695 if(typeof label === 'undefined') label = `collection #${collectionId}`;
696 const result = await this.helper.executeExtrinsic(703 const result = await this.helper.executeExtrinsic(
697 signer,704 signer,
698 'api.tx.unique.addToAllowList', [collectionId, addressObj],705 'api.tx.unique.addToAllowList', [collectionId, addressObj],
699 true, `Unable to add address to allow list for ${label}`,706 true,
700 );707 );
701708
702 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');709 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');
703 }710 }
704711
705 /**712 /**
706 * Removes a collection administrator.713 * Removes an address from allow list
707 * 714 *
708 * @param signer keyring of signer715 * @param signer keyring of signer
709 * @param collectionId ID of collection716 * @param collectionId ID of collection
710 * @param adminAddressObj Administrator address (substrate or ethereum)717 * @param addressObj address to remove from the allow list
711 * @param label extra label for log
712 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})
713 * @returns ```true``` if extrinsic success, otherwise ```false```718 * @returns ```true``` if extrinsic success, otherwise ```false```
714 */719 */
715 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {720 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {
716 if(typeof label === 'undefined') label = `collection #${collectionId}`;
717 const result = await this.helper.executeExtrinsic(721 const result = await this.helper.executeExtrinsic(
718 signer,722 signer,
719 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],723 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],
720 true, `Unable to remove collection admin for ${label}`,724 true,
721 );725 );
722726
723 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);727 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');
724 }728 }
725729
726 /**730 /**
729 * @param signer keyring of signer733 * @param signer keyring of signer
730 * @param collectionId ID of collection734 * @param collectionId ID of collection
731 * @param permissions collection permissions object735 * @param permissions collection permissions object
732 * @param label extra label for log
733 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});736 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});
734 * @returns ```true``` if extrinsic success, otherwise ```false```737 * @returns ```true``` if extrinsic success, otherwise ```false```
735 */738 */
736 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {739 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {
737 if(typeof label === 'undefined') label = `collection #${collectionId}`;
738 const result = await this.helper.executeExtrinsic(740 const result = await this.helper.executeExtrinsic(
739 signer,741 signer,
740 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],742 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],
741 true, `Unable to set collection permissions for ${label}`,743 true,
742 );744 );
743745
744 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);746 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');
745 }747 }
746748
747 /**749 /**
750 * @param signer keyring of signer752 * @param signer keyring of signer
751 * @param collectionId ID of collection753 * @param collectionId ID of collection
752 * @param permissions nesting permissions object754 * @param permissions nesting permissions object
753 * @param label extra label for log
754 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});755 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});
755 * @returns ```true``` if extrinsic success, otherwise ```false```756 * @returns ```true``` if extrinsic success, otherwise ```false```
756 */757 */
757 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {758 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {
758 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);759 return await this.setPermissions(signer, collectionId, {nesting: permissions});
759 }760 }
760761
761 /**762 /**
762 * Disables nesting for selected collection.763 * Disables nesting for selected collection.
763 * 764 *
764 * @param signer keyring of signer765 * @param signer keyring of signer
765 * @param collectionId ID of collection766 * @param collectionId ID of collection
766 * @param label extra label for log
767 * @example disableNesting(aliceKeyring, 10);767 * @example disableNesting(aliceKeyring, 10);
768 * @returns ```true``` if extrinsic success, otherwise ```false```768 * @returns ```true``` if extrinsic success, otherwise ```false```
769 */769 */
770 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {770 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {
771 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);771 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});
772 }772 }
773773
774 /**774 /**
777 * @param signer keyring of signer777 * @param signer keyring of signer
778 * @param collectionId ID of collection778 * @param collectionId ID of collection
779 * @param properties array of property objects779 * @param properties array of property objects
780 * @param label extra label for log
781 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);780 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);
782 * @returns ```true``` if extrinsic success, otherwise ```false```781 * @returns ```true``` if extrinsic success, otherwise ```false```
783 */782 */
784 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {783 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {
785 if(typeof label === 'undefined') label = `collection #${collectionId}`;
786 const result = await this.helper.executeExtrinsic(784 const result = await this.helper.executeExtrinsic(
787 signer,785 signer,
788 'api.tx.unique.setCollectionProperties', [collectionId, properties],786 'api.tx.unique.setCollectionProperties', [collectionId, properties],
789 true, `Unable to set collection properties for ${label}`,787 true,
790 );788 );
791789
792 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);790 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');
793 }791 }
794792
795 /**793 /**
798 * @param signer keyring of signer796 * @param signer keyring of signer
799 * @param collectionId ID of collection797 * @param collectionId ID of collection
800 * @param propertyKeys array of property keys to delete798 * @param propertyKeys array of property keys to delete
801 * @param label
802 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);799 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);
803 * @returns ```true``` if extrinsic success, otherwise ```false```800 * @returns ```true``` if extrinsic success, otherwise ```false```
804 */801 */
805 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {802 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {
806 if(typeof label === 'undefined') label = `collection #${collectionId}`;
807 const result = await this.helper.executeExtrinsic(803 const result = await this.helper.executeExtrinsic(
808 signer,804 signer,
809 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],805 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],
810 true, `Unable to delete collection properties for ${label}`,806 true,
811 );807 );
812808
813 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);809 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');
814 }810 }
815811
816 /**812 /**
828 const result = await this.helper.executeExtrinsic(824 const result = await this.helper.executeExtrinsic(
829 signer,825 signer,
830 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],826 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],
831 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,827 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,
832 );828 );
833829
834 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);830 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);
851 const result = await this.helper.executeExtrinsic(847 const result = await this.helper.executeExtrinsic(
852 signer,848 signer,
853 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],849 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],
854 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,850 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,
855 );851 );
856 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);852 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);
857 }853 }
863 * @param signer keyring of signer859 * @param signer keyring of signer
864 * @param collectionId ID of collection860 * @param collectionId ID of collection
865 * @param tokenId ID of token861 * @param tokenId ID of token
866 * @param label
867 * @param amount amount of tokens to be burned. For NFT must be set to 1n862 * @param amount amount of tokens to be burned. For NFT must be set to 1n
868 * @example burnToken(aliceKeyring, 10, 5);863 * @example burnToken(aliceKeyring, 10, 5);
869 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```864 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```
870 */865 */
871 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{866 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{
872 success: boolean,867 success: boolean,
873 token: number | null868 token: number | null
874 }> {869 }> {
875 if(typeof label === 'undefined') label = `collection #${collectionId}`;
876 const burnResult = await this.helper.executeExtrinsic(870 const burnResult = await this.helper.executeExtrinsic(
877 signer,871 signer,
878 'api.tx.unique.burnItem', [collectionId, tokenId, amount],872 'api.tx.unique.burnItem', [collectionId, tokenId, amount],
879 true, `Unable to burn token for ${label}`,873 true, // `Unable to burn token for ${label}`,
880 );874 );
881 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);875 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);
882 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');876 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');
883 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};877 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};
884 }878 }
890 * @param collectionId ID of collection884 * @param collectionId ID of collection
891 * @param fromAddressObj address on behalf of which the token will be burnt885 * @param fromAddressObj address on behalf of which the token will be burnt
892 * @param tokenId ID of token886 * @param tokenId ID of token
893 * @param label
894 * @param amount amount of tokens to be burned. For NFT must be set to 1n887 * @param amount amount of tokens to be burned. For NFT must be set to 1n
895 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})888 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})
896 * @returns ```true``` if extrinsic success, otherwise ```false```889 * @returns ```true``` if extrinsic success, otherwise ```false```
897 */890 */
898 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {891 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {
899 if(typeof label === 'undefined') label = `collection #${collectionId}`;
900 const burnResult = await this.helper.executeExtrinsic(892 const burnResult = await this.helper.executeExtrinsic(
901 signer,893 signer,
902 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],894 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],
903 true, `Unable to burn token from for ${label}`,895 true, // `Unable to burn token from for ${label}`,
904 );896 );
905 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);897 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);
906 return burnedTokens.success && burnedTokens.tokens.length > 0;898 return burnedTokens.success && burnedTokens.tokens.length > 0;
907 }899 }
908900
912 * @param signer keyring of signer904 * @param signer keyring of signer
913 * @param collectionId ID of collection905 * @param collectionId ID of collection
914 * @param tokenId ID of token906 * @param tokenId ID of token
915 * @param toAddressObj 907 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens
916 * @param label
917 * @param amount amount of token to be approved. For NFT must be set to 1n908 * @param amount amount of token to be approved. For NFT must be set to 1n
918 * @returns ```true``` if extrinsic success, otherwise ```false```909 * @returns ```true``` if extrinsic success, otherwise ```false```
919 */910 */
920 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {911 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {
921 if(typeof label === 'undefined') label = `collection #${collectionId}`;
922 const approveResult = await this.helper.executeExtrinsic(912 const approveResult = await this.helper.executeExtrinsic(
923 signer, 913 signer,
924 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],914 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],
925 true, `Unable to approve token for ${label}`,915 true, // `Unable to approve token for ${label}`,
926 );916 );
927917
928 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);918 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');
929 }919 }
930920
931 /**921 /**
932 * Get the amount of token pieces approved to transfer922 * Get the amount of token pieces approved to transfer or burn. Normally 0.
923 *
933 * @param collectionId ID of collection924 * @param collectionId ID of collection
934 * @param tokenId ID of token925 * @param tokenId ID of token
935 * @param toAccountObj 926 * @param toAccountObj address which is approved to use token pieces
936 * @param fromAccountObj927 * @param fromAccountObj address which may have allowed the use of its owned tokens
937 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})928 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})
938 * @returns number of approved to transfer pieces929 * @returns number of approved to transfer pieces
939 */930 */
942 }933 }
943934
944 /**935 /**
945 * Get the last created token id936 * Get the last created token ID in a collection
937 *
946 * @param collectionId ID of collection938 * @param collectionId ID of collection
947 * @example getLastTokenId(10);939 * @example getLastTokenId(10);
948 * @returns id of the last created token940 * @returns id of the last created token
953945
954 /**946 /**
955 * Check if token exists947 * Check if token exists
948 *
956 * @param collectionId ID of collection949 * @param collectionId ID of collection
957 * @param tokenId ID of token950 * @param tokenId ID of token
958 * @example isTokenExists(10, 20);951 * @example isTokenExists(10, 20);
978971
979 /**972 /**
980 * Get token data973 * Get token data
974 *
981 * @param collectionId ID of collection975 * @param collectionId ID of collection
982 * @param tokenId ID of token976 * @param tokenId ID of token
983 * @param blockHashAt 977 * @param propertyKeys optionally filter the token properties to only these keys
984 * @param propertyKeys978 * @param blockHashAt optionally query the data at some block with this hash
985 * @example getToken(10, 5);979 * @example getToken(10, 5);
986 * @returns human readable token data 980 * @returns human readable token data
987 */981 */
988 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{982 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{
989 properties: IProperty[];983 properties: IProperty[];
990 owner: ICrossAccountId;984 owner: ICrossAccountId;
991 normalizedOwner: ICrossAccountId;985 normalizedOwner: ICrossAccountId;
995 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);989 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);
996 }990 }
997 else {991 else {
998 if(typeof propertyKeys === 'undefined') {992 if(propertyKeys.length == 0) {
999 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();993 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();
1000 if(!collection) return null;994 if(!collection) return null;
1001 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);995 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);
10141008
1015 /**1009 /**
1016 * Set permissions to change token properties1010 * Set permissions to change token properties
1011 *
1017 * @param signer keyring of signer1012 * @param signer keyring of signer
1018 * @param collectionId ID of collection1013 * @param collectionId ID of collection
1019 * @param permissions permissions to change a property by the collection owner or admin1014 * @param permissions permissions to change a property by the collection owner or admin
1020 * @param label
1021 * @example setTokenPropertyPermissions(1015 * @example setTokenPropertyPermissions(
1022 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1016 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]
1023 * )1017 * )
1024 * @returns true if extrinsic success otherwise false1018 * @returns true if extrinsic success otherwise false
1025 */1019 */
1026 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {1020 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {
1027 if(typeof label === 'undefined') label = `collection #${collectionId}`;
1028 const result = await this.helper.executeExtrinsic(1021 const result = await this.helper.executeExtrinsic(
1029 signer,1022 signer,
1030 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1023 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],
1031 true, `Unable to set token property permissions for ${label}`,1024 true,
1032 );1025 );
10331026
1034 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1027 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');
1035 }1028 }
10361029
1037 /**1030 /**
1038 * Set token properties1031 * Set token properties
1032 *
1039 * @param signer keyring of signer1033 * @param signer keyring of signer
1040 * @param collectionId ID of collection1034 * @param collectionId ID of collection
1041 * @param tokenId ID of token1035 * @param tokenId ID of token
1042 * @param properties 1036 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection
1043 * @param label
1044 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1037 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])
1045 * @returns ```true``` if extrinsic success, otherwise ```false```1038 * @returns ```true``` if extrinsic success, otherwise ```false```
1046 */1039 */
1047 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1040 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {
1048 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;
1049 const result = await this.helper.executeExtrinsic(1041 const result = await this.helper.executeExtrinsic(
1050 signer,1042 signer,
1051 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1043 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],
1052 true, `Unable to set token properties for ${label}`,1044 true,
1053 );1045 );
10541046
1055 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1047 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');
1056 }1048 }
10571049
1058 /**1050 /**
1061 * @param collectionId ID of collection1053 * @param collectionId ID of collection
1062 * @param tokenId ID of token1054 * @param tokenId ID of token
1063 * @param propertyKeys property keys to be deleted 1055 * @param propertyKeys property keys to be deleted
1064 * @param label
1065 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1056 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])
1066 * @returns ```true``` if extrinsic success, otherwise ```false```1057 * @returns ```true``` if extrinsic success, otherwise ```false```
1067 */1058 */
1068 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1059 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {
1069 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;
1070 const result = await this.helper.executeExtrinsic(1060 const result = await this.helper.executeExtrinsic(
1071 signer,1061 signer,
1072 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1062 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],
1073 true, `Unable to delete token properties for ${label}`,1063 true,
1074 );1064 );
10751065
1076 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1066 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');
1077 }1067 }
10781068
1079 /**1069 /**
1080 * Mint new collection1070 * Mint new collection
1071 *
1081 * @param signer keyring of signer1072 * @param signer keyring of signer
1082 * @param collectionOptions basic collection options and properties 1073 * @param collectionOptions basic collection options and properties
1083 * @param mode NFT or RFT type of a collection1074 * @param mode NFT or RFT type of a collection
1084 * @param errorLabel
1085 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1075 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")
1086 * @returns object of the created collection1076 * @returns object of the created collection
1087 */1077 */
1088 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1078 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {
1089 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1079 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object
1090 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1080 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};
1091 for (const key of ['name', 'description', 'tokenPrefix']) {1081 for (const key of ['name', 'description', 'tokenPrefix']) {
1094 const creationResult = await this.helper.executeExtrinsic(1084 const creationResult = await this.helper.executeExtrinsic(
1095 signer,1085 signer,
1096 'api.tx.unique.createCollectionEx', [collectionOptions],1086 'api.tx.unique.createCollectionEx', [collectionOptions],
1097 true, errorLabel,1087 true, // errorLabel,
1098 );1088 );
1099 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1089 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));
1100 }1090 }
11011091
1102 getCollectionObject(collectionId: number): any {1092 getCollectionObject(_collectionId: number): any {
1103 return null;1093 return null;
1104 }1094 }
11051095
1106 getTokenObject(collectionId: number, tokenId: number): any {1096 getTokenObject(_collectionId: number, _tokenId: number): any {
1107 return null;1097 return null;
1108 }1098 }
1109}1099}
1135 * Get token's owner1125 * Get token's owner
1136 * @param collectionId ID of collection1126 * @param collectionId ID of collection
1137 * @param tokenId ID of token1127 * @param tokenId ID of token
1138 * @param blockHashAt 1128 * @param blockHashAt optionally query the data at the block with this hash
1139 * @example getTokenOwner(10, 5);1129 * @example getTokenOwner(10, 5);
1140 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1130 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}
1141 */1131 */
1217 * Get tokens nested in the provided token1207 * Get tokens nested in the provided token
1218 * @param collectionId ID of collection1208 * @param collectionId ID of collection
1219 * @param tokenId ID of token1209 * @param tokenId ID of token
1220 * @param blockHashAt 1210 * @param blockHashAt optionally query the data at the block with this hash
1221 * @example getTokenChildren(10, 5);1211 * @example getTokenChildren(10, 5);
1222 * @returns tokens whose depth of nesting is <= 5 1212 * @returns tokens whose depth of nesting is <= 5
1223 */1213 */
1239 * @param signer keyring of signer1229 * @param signer keyring of signer
1240 * @param tokenObj token to be nested1230 * @param tokenObj token to be nested
1241 * @param rootTokenObj token to be parent1231 * @param rootTokenObj token to be parent
1242 * @param label
1243 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1232 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});
1244 * @returns ```true``` if extrinsic success, otherwise ```false```1233 * @returns ```true``` if extrinsic success, otherwise ```false```
1245 */1234 */
1246 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1235 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {
1247 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1236 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};
1248 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1237 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);
1249 if(!result) {1238 if(!result) {
1250 throw Error(`Unable to nest token for ${label}`);1239 throw Error('Unable to nest token!');
1251 }1240 }
1252 return result;1241 return result;
1253 }1242 }
1258 * @param tokenObj token to unnest1247 * @param tokenObj token to unnest
1259 * @param rootTokenObj parent of a token1248 * @param rootTokenObj parent of a token
1260 * @param toAddressObj address of a new token owner 1249 * @param toAddressObj address of a new token owner
1261 * @param label
1262 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1250 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});
1263 * @returns ```true``` if extrinsic success, otherwise ```false```1251 * @returns ```true``` if extrinsic success, otherwise ```false```
1264 */1252 */
1265 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1253 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {
1266 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1254 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};
1267 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1255 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);
1268 if(!result) {1256 if(!result) {
1269 throw Error(`Unable to unnest token for ${label}`);1257 throw Error('Unable to unnest token!');
1270 }1258 }
1271 return result;1259 return result;
1272 }1260 }
1275 * Mint new collection1263 * Mint new collection
1276 * @param signer keyring of signer1264 * @param signer keyring of signer
1277 * @param collectionOptions Collection options1265 * @param collectionOptions Collection options
1278 * @param label
1279 * @example 1266 * @example
1280 * mintCollection(aliceKeyring, {1267 * mintCollection(aliceKeyring, {
1281 * name: 'New',1268 * name: 'New',
1284 * })1271 * })
1285 * @returns object of the created collection1272 * @returns object of the created collection
1286 */1273 */
1287 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1274 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {
1288 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1275 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;
1289 }1276 }
12901277
1291 /**1278 /**
1292 * Mint new token1279 * Mint new token
1293 * @param signer keyring of signer1280 * @param signer keyring of signer
1294 * @param data token data1281 * @param data token data
1295 * @param label
1296 * @returns created token object1282 * @returns created token object
1297 */1283 */
1298 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1284 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {
1299 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;
1300 const creationResult = await this.helper.executeExtrinsic(1285 const creationResult = await this.helper.executeExtrinsic(
1301 signer,1286 signer,
1302 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1287 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {
1303 nft: {1288 nft: {
1304 properties: data.properties,1289 properties: data.properties,
1305 },1290 },
1306 }],1291 }],
1307 true, `Unable to mint NFT token for ${label}`,1292 true,
1308 );1293 );
1309 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1294 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);
1310 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1295 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');
1311 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1296 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');
1312 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1297 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);
1317 * @param signer keyring of signer1302 * @param signer keyring of signer
1318 * @param collectionId ID of collection1303 * @param collectionId ID of collection
1319 * @param tokens array of tokens with owner and properties1304 * @param tokens array of tokens with owner and properties
1320 * @param label
1321 * @example 1305 * @example
1322 * mintMultipleTokens(aliceKeyring, 10, [{1306 * mintMultipleTokens(aliceKeyring, 10, [{
1323 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1307 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},
1328 * }]);1312 * }]);
1329 * @returns ```true``` if extrinsic success, otherwise ```false```1313 * @returns ```true``` if extrinsic success, otherwise ```false```
1330 */1314 */
1331 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1315 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {
1332 if(typeof label === 'undefined') label = `collection #${collectionId}`;
1333 const creationResult = await this.helper.executeExtrinsic(1316 const creationResult = await this.helper.executeExtrinsic(
1334 signer,1317 signer,
1335 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1318 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],
1336 true, `Unable to mint NFT tokens for ${label}`,1319 true,
1337 );1320 );
1338 const collection = this.getCollectionObject(collectionId);1321 const collection = this.getCollectionObject(collectionId);
1339 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1322 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));
1340 }1323 }
13411324
1342 /**1325 /**
1345 * @param collectionId ID of collection1328 * @param collectionId ID of collection
1346 * @param owner tokens owner1329 * @param owner tokens owner
1347 * @param tokens array of tokens with owner and properties1330 * @param tokens array of tokens with owner and properties
1348 * @param label
1349 * @example1331 * @example
1350 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1332 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{
1351 * properties: [{1333 * properties: [{
1358 * }]);1340 * }]);
1359 * @returns array of newly created tokens1341 * @returns array of newly created tokens
1360 */1342 */
1361 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1343 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {
1362 if(typeof label === 'undefined') label = `collection #${collectionId}`;
1363 const rawTokens = [];1344 const rawTokens = [];
1364 for (const token of tokens) {1345 for (const token of tokens) {
1365 const raw = {NFT: {properties: token.properties}};1346 const raw = {NFT: {properties: token.properties}};
1368 const creationResult = await this.helper.executeExtrinsic(1349 const creationResult = await this.helper.executeExtrinsic(
1369 signer,1350 signer,
1370 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1351 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],
1371 true, `Unable to mint NFT tokens for ${label}`,1352 true,
1372 );1353 );
1373 const collection = this.getCollectionObject(collectionId);1354 const collection = this.getCollectionObject(collectionId);
1374 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1355 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));
1375 }1356 }
13761357
1377 /**1358 /**
1378 * Destroys a concrete instance of NFT.1359 * Destroys a concrete instance of NFT.
1379 * @param signer keyring of signer1360 * @param signer keyring of signer
1380 * @param collectionId ID of collection1361 * @param collectionId ID of collection
1381 * @param tokenId ID of token1362 * @param tokenId ID of token
1382 * @param label
1383 * @example burnToken(aliceKeyring, 10, 5);1363 * @example burnToken(aliceKeyring, 10, 5);
1384 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1364 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```
1385 */1365 */
1386 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1366 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number): Promise<{ success: boolean; token: number | null; }> {
1387 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1367 return await super.burnToken(signer, collectionId, tokenId, 1n);
1388 }1368 }
13891369
1390 /**1370 /**
1394 * @param collectionId ID of collection1374 * @param collectionId ID of collection
1395 * @param tokenId ID of token1375 * @param tokenId ID of token
1396 * @param toAddressObj address to approve1376 * @param toAddressObj address to approve
1397 * @param label
1398 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1377 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})
1399 * @returns ```true``` if extrinsic success, otherwise ```false```1378 * @returns ```true``` if extrinsic success, otherwise ```false```
1400 */1379 */
1401 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1380 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {
1402 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1381 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);
1403 }1382 }
1404}1383}
14051384
1459 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1438 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)
1460 * @returns ```true``` if extrinsic success, otherwise ```false```1439 * @returns ```true``` if extrinsic success, otherwise ```false```
1461 */1440 */
1462 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1441 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {
1463 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1442 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);
1464 }1443 }
14651444
1474 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1453 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)
1475 * @returns ```true``` if extrinsic success, otherwise ```false```1454 * @returns ```true``` if extrinsic success, otherwise ```false```
1476 */1455 */
1477 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1456 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {
1478 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1457 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);
1479 }1458 }
14801459
1481 /**1460 /**
1482 * Mint new collection1461 * Mint new collection
1483 * @param signer keyring of signer1462 * @param signer keyring of signer
1484 * @param collectionOptions Collection options1463 * @param collectionOptions Collection options
1485 * @param label
1486 * @example1464 * @example
1487 * mintCollection(aliceKeyring, {1465 * mintCollection(aliceKeyring, {
1488 * name: 'New',1466 * name: 'New',
1491 * })1469 * })
1492 * @returns object of the created collection1470 * @returns object of the created collection
1493 */1471 */
1494 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1472 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {
1495 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1473 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;
1496 }1474 }
14971475
1498 /**1476 /**
1499 * Mint new token1477 * Mint new token
1500 * @param signer keyring of signer1478 * @param signer keyring of signer
1501 * @param data token data1479 * @param data token data
1502 * @param label
1503 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1480 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});
1504 * @returns created token object1481 * @returns created token object
1505 */1482 */
1506 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1483 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {
1507 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;
1508 const creationResult = await this.helper.executeExtrinsic(1484 const creationResult = await this.helper.executeExtrinsic(
1509 signer,1485 signer,
1510 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1486 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {
1513 properties: data.properties,1489 properties: data.properties,
1514 },1490 },
1515 }],1491 }],
1516 true, `Unable to mint RFT token for ${label}`,1492 true,
1517 );1493 );
1518 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1494 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);
1519 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1495 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');
1520 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1496 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');
1521 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1497 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);
1522 }1498 }
15231499
1524 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1500 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {
1525 throw Error('Not implemented');1501 throw Error('Not implemented');
1526 if(typeof label === 'undefined') label = `collection #${collectionId}`;
1527 const creationResult = await this.helper.executeExtrinsic(1502 const creationResult = await this.helper.executeExtrinsic(
1528 signer,1503 signer,
1529 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1504 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],
1530 true, `Unable to mint RFT tokens for ${label}`,1505 true, // `Unable to mint RFT tokens for ${label}`,
1531 );1506 );
1532 const collection = this.getCollectionObject(collectionId);1507 const collection = this.getCollectionObject(collectionId);
1533 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1508 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));
1534 }1509 }
15351510
1536 /**1511 /**
1539 * @param collectionId ID of collection1514 * @param collectionId ID of collection
1540 * @param owner tokens owner1515 * @param owner tokens owner
1541 * @param tokens array of tokens with properties and pieces1516 * @param tokens array of tokens with properties and pieces
1542 * @param label
1543 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1517 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);
1544 * @returns array of newly created RFT tokens1518 * @returns array of newly created RFT tokens
1545 */1519 */
1546 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1520 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {
1547 if(typeof label === 'undefined') label = `collection #${collectionId}`;
1548 const rawTokens = [];1521 const rawTokens = [];
1549 for (const token of tokens) {1522 for (const token of tokens) {
1550 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1523 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};
1553 const creationResult = await this.helper.executeExtrinsic(1526 const creationResult = await this.helper.executeExtrinsic(
1554 signer,1527 signer,
1555 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1528 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],
1556 true, `Unable to mint RFT tokens for ${label}`,1529 true,
1557 );1530 );
1558 const collection = this.getCollectionObject(collectionId);1531 const collection = this.getCollectionObject(collectionId);
1559 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1532 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));
1560 }1533 }
15611534
1562 /**1535 /**
1563 * Destroys a concrete instance of RFT.1536 * Destroys a concrete instance of RFT.
1564 * @param signer keyring of signer1537 * @param signer keyring of signer
1565 * @param collectionId ID of collection1538 * @param collectionId ID of collection
1566 * @param tokenId ID of token1539 * @param tokenId ID of token
1567 * @param label
1568 * @param amount number of pieces to be burnt1540 * @param amount number of pieces to be burnt
1569 * @example burnToken(aliceKeyring, 10, 5);1541 * @example burnToken(aliceKeyring, 10, 5);
1570 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1542 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```
1571 */1543 */
1572 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1544 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {
1573 return await super.burnToken(signer, collectionId, tokenId, label, amount);1545 return await super.burnToken(signer, collectionId, tokenId, amount);
1574 }1546 }
15751547
1576 /**1548 /**
1580 * @param collectionId ID of collection1552 * @param collectionId ID of collection
1581 * @param tokenId ID of token1553 * @param tokenId ID of token
1582 * @param toAddressObj address to approve1554 * @param toAddressObj address to approve
1583 * @param label
1584 * @param amount number of pieces to be approved1555 * @param amount number of pieces to be approved
1585 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1556 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);
1586 * @returns true if the token success, otherwise false1557 * @returns true if the token success, otherwise false
1587 */1558 */
1588 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1559 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {
1589 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1560 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);
1590 }1561 }
15911562
1592 /**1563 /**
1606 * @param collectionId ID of collection1577 * @param collectionId ID of collection
1607 * @param tokenId ID of token1578 * @param tokenId ID of token
1608 * @param amount new number of pieces1579 * @param amount new number of pieces
1609 * @param label
1610 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1580 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);
1611 * @returns true if the repartion was success, otherwise false1581 * @returns true if the repartion was success, otherwise false
1612 */1582 */
1613 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1583 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {
1614 if(typeof label === 'undefined') label = `collection #${collectionId}`;
1615 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1584 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);
1616 const repartitionResult = await this.helper.executeExtrinsic(1585 const repartitionResult = await this.helper.executeExtrinsic(
1617 signer,1586 signer,
1618 'api.tx.unique.repartition', [collectionId, tokenId, amount],1587 'api.tx.unique.repartition', [collectionId, tokenId, amount],
1619 true, `Unable to repartition RFT token for ${label}`,1588 true,
1620 );1589 );
1621 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1590 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');
1622 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1591 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');
1623 }1592 }
1624}1593}
16251594
1640 * @param signer keyring of signer1609 * @param signer keyring of signer
1641 * @param collectionOptions Collection options1610 * @param collectionOptions Collection options
1642 * @param decimalPoints number of token decimals 1611 * @param decimalPoints number of token decimals
1643 * @param errorLabel
1644 * @example1612 * @example
1645 * mintCollection(aliceKeyring, {1613 * mintCollection(aliceKeyring, {
1646 * name: 'New',1614 * name: 'New',
1649 * }, 18)1617 * }, 18)
1650 * @returns newly created fungible collection1618 * @returns newly created fungible collection
1651 */1619 */
1652 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1620 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {
1653 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1621 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object
1654 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1622 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');
1655 collectionOptions.mode = {fungible: decimalPoints};1623 collectionOptions.mode = {fungible: decimalPoints};
1659 const creationResult = await this.helper.executeExtrinsic(1627 const creationResult = await this.helper.executeExtrinsic(
1660 signer,1628 signer,
1661 'api.tx.unique.createCollectionEx', [collectionOptions],1629 'api.tx.unique.createCollectionEx', [collectionOptions],
1662 true, errorLabel,1630 true,
1663 );1631 );
1664 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1632 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));
1665 }1633 }
16661634
1667 /**1635 /**
1670 * @param collectionId ID of collection1638 * @param collectionId ID of collection
1671 * @param owner address owner of new tokens1639 * @param owner address owner of new tokens
1672 * @param amount amount of tokens to be meanted1640 * @param amount amount of tokens to be meanted
1673 * @param label
1674 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1641 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);
1675 * @returns ```true``` if extrinsic success, otherwise ```false``` 1642 * @returns ```true``` if extrinsic success, otherwise ```false```
1676 */1643 */
1677 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1644 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint): Promise<boolean> {
1678 if(typeof label === 'undefined') label = `collection #${collectionId}`;
1679 const creationResult = await this.helper.executeExtrinsic(1645 const creationResult = await this.helper.executeExtrinsic(
1680 signer,1646 signer,
1681 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1647 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {
1682 fungible: {1648 fungible: {
1683 value: amount,1649 value: amount,
1684 },1650 },
1685 }],1651 }],
1686 true, `Unable to mint fungible tokens for ${label}`,1652 true, // `Unable to mint fungible tokens for ${label}`,
1687 );1653 );
1688 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1654 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');
1689 }1655 }
16901656
1691 /**1657 /**
1694 * @param collectionId ID of collection1660 * @param collectionId ID of collection
1695 * @param owner tokens owner1661 * @param owner tokens owner
1696 * @param tokens array of tokens with properties and pieces1662 * @param tokens array of tokens with properties and pieces
1697 * @param label
1698 * @returns ```true``` if extrinsic success, otherwise ```false``` 1663 * @returns ```true``` if extrinsic success, otherwise ```false```
1699 */1664 */
1700 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1665 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[]): Promise<boolean> {
1701 if(typeof label === 'undefined') label = `collection #${collectionId}`;
1702 const rawTokens = [];1666 const rawTokens = [];
1703 for (const token of tokens) {1667 for (const token of tokens) {
1704 const raw = {Fungible: {Value: token.value}};1668 const raw = {Fungible: {Value: token.value}};
1707 const creationResult = await this.helper.executeExtrinsic(1671 const creationResult = await this.helper.executeExtrinsic(
1708 signer,1672 signer,
1709 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1673 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],
1710 true, `Unable to mint RFT tokens for ${label}`,1674 true,
1711 );1675 );
1712 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1676 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');
1713 }1677 }
17141678
1715 /**1679 /**
1737 * Transfer tokens to address1701 * Transfer tokens to address
1738 * @param signer keyring of signer1702 * @param signer keyring of signer
1739 * @param collectionId ID of collection1703 * @param collectionId ID of collection
1740 * @param toAddressObj address recepient1704 * @param toAddressObj address recipient
1741 * @param amount amount of tokens to be sent1705 * @param amount amount of tokens to be sent
1742 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1706 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);
1743 * @returns ```true``` if extrinsic success, otherwise ```false``` 1707 * @returns ```true``` if extrinsic success, otherwise ```false```
1744 */1708 */
1745 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1709 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {
1746 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1710 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);
1747 }1711 }
17481712
1756 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1720 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);
1757 * @returns ```true``` if extrinsic success, otherwise ```false``` 1721 * @returns ```true``` if extrinsic success, otherwise ```false```
1758 */1722 */
1759 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1723 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {
1760 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1724 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);
1761 }1725 }
17621726
1765 * @param signer keyring of signer1729 * @param signer keyring of signer
1766 * @param collectionId ID of collection1730 * @param collectionId ID of collection
1767 * @param amount amount of tokens to be destroyed1731 * @param amount amount of tokens to be destroyed
1768 * @param label
1769 * @example burnTokens(aliceKeyring, 10, 1000n);1732 * @example burnTokens(aliceKeyring, 10, 1000n);
1770 * @returns ```true``` if extrinsic success, otherwise ```false``` 1733 * @returns ```true``` if extrinsic success, otherwise ```false```
1771 */1734 */
1772 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1735 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {
1773 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1736 return (await super.burnToken(signer, collectionId, 0, amount)).success;
1774 }1737 }
17751738
1776 /**1739 /**
1779 * @param collectionId ID of collection1742 * @param collectionId ID of collection
1780 * @param fromAddressObj address on behalf of which tokens will be burnt1743 * @param fromAddressObj address on behalf of which tokens will be burnt
1781 * @param amount amount of tokens to be burnt1744 * @param amount amount of tokens to be burnt
1782 * @param label
1783 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1745 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);
1784 * @returns ```true``` if extrinsic success, otherwise ```false``` 1746 * @returns ```true``` if extrinsic success, otherwise ```false```
1785 */1747 */
1786 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1748 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {
1787 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1749 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);
1788 }1750 }
17891751
1790 /**1752 /**
1803 * @param collectionId ID of collection1765 * @param collectionId ID of collection
1804 * @param toAddressObj address to be approved1766 * @param toAddressObj address to be approved
1805 * @param amount amount of tokens to be approved1767 * @param amount amount of tokens to be approved
1806 * @param label
1807 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1768 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)
1808 * @returns ```true``` if extrinsic success, otherwise ```false``` 1769 * @returns ```true``` if extrinsic success, otherwise ```false```
1809 */1770 */
1810 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1771 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {
1811 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1772 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);
1812 }1773 }
18131774
1814 /**1775 /**
1923 /**1884 /**
1924 * Transfer tokens to substrate address1885 * Transfer tokens to substrate address
1925 * @param signer keyring of signer1886 * @param signer keyring of signer
1926 * @param address substrate address of a recepient1887 * @param address substrate address of a recipient
1927 * @param amount amount of tokens to be transfered1888 * @param amount amount of tokens to be transfered
1928 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1889 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);
1929 * @returns ```true``` if extrinsic success, otherwise ```false```1890 * @returns ```true``` if extrinsic success, otherwise ```false```
1930 */1891 */
1931 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1892 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {
1932 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}`);1893 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}`*/);
19331894
1934 let transfer = {from: null, to: null, amount: 0n} as any;1895 let transfer = {from: null, to: null, amount: 0n} as any;
1935 result.result.events.forEach(({event: {data, method, section}}) => {1896 result.result.events.forEach(({event: {data, method, section}}) => {
2007 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {1968 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {
2008 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;1969 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;
2009 const stakeResult = await this.helper.executeExtrinsic(1970 const stakeResult = await this.helper.executeExtrinsic(
2010 signer,1971 signer, 'api.tx.appPromotion.stake',
2011 'api.tx.appPromotion.stake', [amountToStake],
2012 true, `stake failed for ${label}`,1972 [amountToStake], true,
2013 );1973 );
2014 // TODO extract info from stakeResult1974 // TODO extract info from stakeResult
2015 return true;1975 return true;
2025 async unstake(signer: TSigner, label?: string): Promise<boolean> {1985 async unstake(signer: TSigner, label?: string): Promise<boolean> {
2026 if(typeof label === 'undefined') label = `${signer.address}`;1986 if(typeof label === 'undefined') label = `${signer.address}`;
2027 const unstakeResult = await this.helper.executeExtrinsic(1987 const unstakeResult = await this.helper.executeExtrinsic(
2028 signer,1988 signer, 'api.tx.appPromotion.unstake',
2029 'api.tx.appPromotion.unstake', [],
2030 true, `unstake failed for ${label}`,1989 [], true,
2031 );1990 );
2032 // TODO extract info from unstakeResult1991 // TODO extract info from unstakeResult
2033 return true;1992 return true;
21102069
2111 async getEffectiveLimits() {2070 async getEffectiveLimits() {
2112 return await this.helper.collection.getEffectiveLimits(this.collectionId);2071 return await this.helper.collection.getEffectiveLimits(this.collectionId);
2072 }
2073
2074 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {
2075 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);
2076 }
2077
2078 async confirmSponsorship(signer: TSigner) {
2079 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);
2113 }2080 }
21142081
2115 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2082 async setLimits(signer: TSigner, limits: ICollectionLimits) {
2116 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2083 return await this.helper.collection.setLimits(signer, this.collectionId, limits);
2117 }2084 }
21182085
2119 async confirmSponsorship(signer: TSigner, label?: string) {2086 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {
2120 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2087 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);
2121 }2088 }
21222089
2123 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2090 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {
2124 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2091 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);
2125 }2092 }
21262093
2127 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2094 async enableAllowList(signer: TSigner, value = true/*: 'Normal' | 'AllowList' = 'AllowList'*/) {
2128 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2095 return await this.setPermissions(signer, value ? {access: 'AllowList', mintMode: true} : {access: 'Normal'});
2129 }2096 }
21302097
2131 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2098 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {
2132 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2099 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);
2133 }2100 }
21342101
2135 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId, label?: string) {2102 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {
2136 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj, label);2103 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);
2137 }2104 }
21382105
2139 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2106 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {
2140 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2107 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);
2141 }2108 }
21422109
2143 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2110 async setProperties(signer: TSigner, properties: IProperty[]) {
2144 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2111 return await this.helper.collection.setProperties(signer, this.collectionId, properties);
2145 }2112 }
21462113
2147 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2114 async deleteProperties(signer: TSigner, propertyKeys: string[]) {
2148 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2115 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);
2149 }2116 }
21502117
2151 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2118 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {
2152 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2119 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);
2153 }2120 }
21542121
2155 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2122 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {
2156 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2123 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);
2157 }2124 }
21582125
2159 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2126 async enableNesting(signer: TSigner, permissions: INestingPermissions) {
2160 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2127 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);
2161 }2128 }
21622129
2163 async disableNesting(signer: TSigner, label?: string) {2130 async disableNesting(signer: TSigner) {
2164 return await this.helper.collection.disableNesting(signer, this.collectionId, label);2131 return await this.helper.collection.disableNesting(signer, this.collectionId);
2165 }2132 }
21662133
2167 async burn(signer: TSigner, label?: string) {2134 async burn(signer: TSigner) {
2168 return await this.helper.collection.burn(signer, this.collectionId, label);2135 return await this.helper.collection.burn(signer, this.collectionId);
2169 }2136 }
2170}2137}
21712138
2180 }2147 }
21812148
2182 async getToken(tokenId: number, blockHashAt?: string) {2149 async getToken(tokenId: number, blockHashAt?: string) {
2183 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2150 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);
2184 }2151 }
21852152
2186 async getTokenOwner(tokenId: number, blockHashAt?: string) {2153 async getTokenOwner(tokenId: number, blockHashAt?: string) {
2203 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2170 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);
2204 }2171 }
22052172
2206 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2173 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {
2207 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2174 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);
2208 }2175 }
22092176
2210 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2177 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {
2211 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2178 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);
2212 }2179 }
22132180
2214 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2181 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[]) {
2215 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2182 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});
2216 }2183 }
22172184
2218 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2185 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {
2219 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2186 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);
2220 }2187 }
22212188
2222 async burnToken(signer: TSigner, tokenId: number, label?: string) {2189 async burnToken(signer: TSigner, tokenId: number) {
2223 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2190 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);
2224 }2191 }
22252192
2226 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2193 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {
2227 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2194 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);
2228 }2195 }
22292196
2230 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2197 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {
2231 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2198 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);
2232 }2199 }
22332200
2234 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2201 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {
2235 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2202 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);
2236 }2203 }
22372204
2238 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2205 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {
2239 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2206 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);
2240 }2207 }
22412208
2242 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2209 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {
2243 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2210 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);
2244 }2211 }
2245}2212}
22462213
2266 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2233 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);
2267 }2234 }
22682235
2269 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2236 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {
2270 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2237 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);
2271 }2238 }
22722239
2273 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2240 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {
2274 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2241 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);
2275 }2242 }
22762243
2277 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2244 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {
2278 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2245 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);
2279 }2246 }
22802247
2281 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2248 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {
2282 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2249 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);
2283 }2250 }
22842251
2285 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2252 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {
2286 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2253 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);
2287 }2254 }
22882255
2289 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2256 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[]) {
2290 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2257 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});
2291 }2258 }
22922259
2293 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2260 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]) {
2294 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2261 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);
2295 }2262 }
22962263
2297 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2264 async burnToken(signer: TSigner, tokenId: number, amount=1n) {
2298 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2265 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);
2299 }2266 }
23002267
2301 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2268 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {
2302 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2269 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);
2303 }2270 }
23042271
2305 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2272 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {
2306 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2273 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);
2307 }2274 }
23082275
2309 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2276 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {
2310 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2277 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);
2311 }2278 }
2312}2279}
23132280
23142281
2315class UniqueFTCollection extends UniqueCollectionBase {2282class UniqueFTCollection extends UniqueCollectionBase {
2316 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2283 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint) {
2317 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2284 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount);
2318 }2285 }
23192286
2320 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2287 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[]) {
2321 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2288 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens);
2322 }2289 }
23232290
2324 async getBalance(addressObj: ICrossAccountId) {2291 async getBalance(addressObj: ICrossAccountId) {
2329 return await this.helper.ft.getTop10Owners(this.collectionId);2296 return await this.helper.ft.getTop10Owners(this.collectionId);
2330 }2297 }
23312298
2332 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2299 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {
2333 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2300 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);
2334 }2301 }
23352302
2336 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2303 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {
2337 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2304 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);
2338 }2305 }
23392306
2340 async burnTokens(signer: TSigner, amount: bigint, label?: string) {2307 async burnTokens(signer: TSigner, amount=1n) {
2341 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2308 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);
2342 }2309 }
23432310
2344 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2311 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {
2345 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2312 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);
2346 }2313 }
23472314
2348 async getTotalPieces() {2315 async getTotalPieces() {
2349 return await this.helper.ft.getTotalPieces(this.collectionId);2316 return await this.helper.ft.getTotalPieces(this.collectionId);
2350 }2317 }
23512318
2352 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2319 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {
2353 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2320 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);
2354 }2321 }
23552322
2356 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2323 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {
2374 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2341 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);
2375 }2342 }
23762343
2377 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2344 async setProperties(signer: TSigner, properties: IProperty[]) {
2378 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2345 return await this.collection.setTokenProperties(signer, this.tokenId, properties);
2379 }2346 }
23802347
2381 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2348 async deleteProperties(signer: TSigner, propertyKeys: string[]) {
2382 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2349 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);
2383 }2350 }
2384}2351}
23852352
2408 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2375 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);
2409 }2376 }
24102377
2411 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2378 async nest(signer: TSigner, toTokenObj: IToken) {
2412 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2379 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);
2413 }2380 }
24142381
2415 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2382 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {
2416 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2383 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);
2417 }2384 }
24182385
2419 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2386 async transfer(signer: TSigner, addressObj: ICrossAccountId) {
2424 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2391 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);
2425 }2392 }
24262393
2427 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2394 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {
2428 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2395 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);
2429 }2396 }
24302397
2431 async isApproved(toAddressObj: ICrossAccountId) {2398 async isApproved(toAddressObj: ICrossAccountId) {
2432 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2399 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);
2433 }2400 }
24342401
2435 async burn(signer: TSigner, label?: string) {2402 async burn(signer: TSigner) {
2436 return await this.collection.burnToken(signer, this.tokenId, label);2403 return await this.collection.burnToken(signer, this.tokenId);
2437 }2404 }
2438}2405}
24392406
2457 return await this.collection.getTokenTotalPieces(this.tokenId);2424 return await this.collection.getTokenTotalPieces(this.tokenId);
2458 }2425 }
24592426
2460 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2427 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {
2461 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2428 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);
2462 }2429 }
24632430
2464 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2431 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {
2465 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2432 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);
2466 }2433 }
24672434
2468 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2435 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {
2469 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2436 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);
2470 }2437 }
24712438
2472 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2439 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {
2473 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2440 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);
2474 }2441 }
24752442
2476 async repartition(signer: TSigner, amount: bigint, label?: string) {2443 async repartition(signer: TSigner, amount: bigint) {
2477 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2444 return await this.collection.repartitionToken(signer, this.tokenId, amount);
2478 }2445 }
24792446
2480 async burn(signer: TSigner, amount=100n, label?: string) {2447 async burn(signer: TSigner, amount=1n) {
2481 return await this.collection.burnToken(signer, this.tokenId, amount, label);2448 return await this.collection.burnToken(signer, this.tokenId, amount);
2482 }2449 }
2483}2450}