difftreelog
Add tests for properties
in: master
6 files changed
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -50,6 +50,7 @@
"testContracts": "mocha --timeout 9999999 -r ts-node/register ./**/contracts.test.ts",
"testCreateItem": "mocha --timeout 9999999 -r ts-node/register ./**/createItem.test.ts",
"testCreateMultipleItems": "mocha --timeout 9999999 -r ts-node/register ./**/createMultipleItems.test.ts",
+ "testCreateMultipleItemsEx": "mocha --timeout 9999999 -r ts-node/register ./**/createMultipleItemsEx.test.ts",
"testApprove": "mocha --timeout 9999999 -r ts-node/register ./**/approve.test.ts",
"testTransferFrom": "mocha --timeout 9999999 -r ts-node/register ./**/transferFrom.test.ts",
"testCreateCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -17,7 +17,7 @@
import {expect} from 'chai';
import privateKey from './substrate/privateKey';
import usingApi, {executeTransaction, submitTransactionAsync} from './substrate/substrate-api';
-import {createCollectionExpectFailure, createCollectionExpectSuccess, getCreateCollectionResult, getDetailedCollectionInfo} from './util/helpers';
+import {createCollectionWithPropsExpectFailure, createCollectionExpectFailure, createCollectionExpectSuccess, getCreateCollectionResult, getDetailedCollectionInfo, createCollectionWithPropsExpectSuccess} from './util/helpers';
describe('integration test: ext. createCollection():', () => {
it('Create new NFT collection', async () => {
@@ -38,6 +38,25 @@
it('Create new ReFungible collection', async () => {
await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
});
+
+ it('create new collection with properties #1', async () => {
+ await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
+ properties: [{key: 'key1', value: 'val1'}],
+ propPerm: [{key: 'key1', tokenOwner: true, mutable: false, collectionAdmin: true}]});
+ });
+
+ it('create new collection with properties #2', async () => {
+ await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
+ properties: [{key: 'key1', value: 'val1'}],
+ propPerm: [{key: 'key1', tokenOwner: false, mutable: true, collectionAdmin: false}]});
+ });
+
+ it('create new collection with properties #3', async () => {
+ await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'},
+ properties: [{key: 'key1', value: 'val1'}],
+ propPerm: [{key: 'key1', tokenOwner: true, mutable: false, collectionAdmin: false}]});
+ });
+
it('Create new collection with extra fields', async () => {
await usingApi(async api => {
const alice = privateKey('//Alice');
@@ -96,4 +115,24 @@
await expect(executeTransaction(api, alice, tx)).to.be.rejectedWith(/^common.CollectionTokenLimitExceeded$/);
});
});
+
+ it('(!negative test!) create collection with incorrect property limit (64 elements)', async () => {
+ const props = [];
+
+ for (let i = 0; i < 65; i++) {
+ props.push({key: `key${i}`, value: `value${i}`});
+ }
+
+ await createCollectionWithPropsExpectFailure({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}, properties: props});
+ });
+
+ it('(!negative test!) create collection with incorrect property limit (40 kb)', async () => {
+ const props = [];
+
+ for (let i = 0; i < 32; i++) {
+ props.push({key: `key${i}`.repeat(80), value: `value${i}`.repeat(80)});
+ }
+
+ await createCollectionWithPropsExpectFailure({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}, properties: props});
+ });
});
tests/src/createItem.test.tsdiffbeforeafterboth--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {default as usingApi} from './substrate/substrate-api';
+import {default as usingApi, executeTransaction} from './substrate/substrate-api';
import chai from 'chai';
import {Keyring} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
@@ -22,6 +22,7 @@
createCollectionExpectSuccess,
createItemExpectSuccess,
addCollectionAdminExpectSuccess,
+ createCollectionWithPropsExpectSuccess,
} from './util/helpers';
const expect = chai.expect;
@@ -70,6 +71,33 @@
await addCollectionAdminExpectSuccess(alice, newCollectionID, bob.address);
await createItemExpectSuccess(bob, newCollectionID, createMode);
});
+
+ it('Set property Admin', async () => {
+ const createMode = 'NFT';
+ const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode},
+ properties: [{key: 'key1', value: 'val1'}],
+ propPerm: [{key: 'key1', mutable: true, collectionAdmin: true, tokenOwner: false}]});
+
+ await createItemExpectSuccess(alice, newCollectionID, createMode);
+ });
+
+ it('Set property AdminConst', async () => {
+ const createMode = 'NFT';
+ const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode},
+ properties: [{key: 'key1', value: 'val1'}],
+ propPerm: [{key: 'key1', mutable: false, collectionAdmin: true, tokenOwner: false}]});
+
+ await createItemExpectSuccess(alice, newCollectionID, createMode);
+ });
+
+ it('Set property itemOwnerOrAdmin', async () => {
+ const createMode = 'NFT';
+ const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode},
+ properties: [{key: 'key1', value: 'val1'}],
+ propPerm: [{key: 'key1', mutable: true, collectionAdmin: true, tokenOwner: true}]});
+
+ await createItemExpectSuccess(alice, newCollectionID, createMode);
+ });
});
describe('Negative integration test: ext. createItem():', () => {
@@ -96,4 +124,76 @@
const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});
await expect(createItemExpectSuccess(bob, newCollectionID, createMode)).to.be.rejected;
});
+
+ it('No editing rights', async () => {
+ await usingApi(async api => {
+ const createMode = 'NFT';
+ const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode},
+ propPerm: [{key: 'key1', mutable: false, collectionAdmin: false, tokenOwner: false}]});
+
+ const token = await createItemExpectSuccess(alice, newCollectionID, 'NFT');
+ await addCollectionAdminExpectSuccess(alice, newCollectionID, bob.address);
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setTokenProperties(newCollectionID, token, [{key: 'key1', value: 'v2'}]),
+ )).to.be.rejected;
+ });
+ });
+
+ it('User doesnt have editing rights', async () => {
+ await usingApi(async api => {
+ const createMode = 'NFT';
+ const newCollectionID = await createCollectionWithPropsExpectSuccess({propPerm: [{key: 'key1', mutable: true, collectionAdmin: false, tokenOwner: false}]});
+ const token = await createItemExpectSuccess(alice, newCollectionID, 'NFT');
+
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(newCollectionID, token, [{key: 'key1', value: 'v2'}]),
+ )).to.be.rejected;
+ });
+ });
+
+ it('Adding property without access rights', async () => {
+ await usingApi(async api => {
+ const createMode = 'NFT';
+ const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});
+
+ const token = await createItemExpectSuccess(alice, newCollectionID, 'NFT');
+ await addCollectionAdminExpectSuccess(alice, newCollectionID, bob.address);
+
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(newCollectionID, token, [{key: 'key1', value: 'v2'}]),
+ )).to.be.rejected;
+ });
+ });
+
+ it('Adding more than 64 prps', async () => {
+ await usingApi(async api => {
+ const createMode = 'NFT';
+
+ const prps = [];
+
+ for (let i = 0; i < 65; i++) {
+ prps.push({key: `key${i}`, value: `value${i}`});
+ }
+
+ const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});
+
+ await expect(executeTransaction(api, alice, api.tx.unique.setCollectionProperties(newCollectionID, prps))).to.be.rejectedWith(/common\.PropertyLimitReached/);
+ });
+ });
+
+ it('Trying to add bigger property than allowed', async () => {
+ await usingApi(async api => {
+ const createMode = 'NFT';
+ const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});
+
+ await expect(executeTransaction(api, alice, api.tx.unique.setCollectionProperties(newCollectionID, [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]))).to.be.rejectedWith(/common\.NoSpaceForProperty/);
+ });
+ });
});
tests/src/createMultipleItems.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -19,7 +19,7 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
-import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
+import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync, executeTransaction} from './substrate/substrate-api';
import {
createCollectionExpectSuccess,
destroyCollectionExpectSuccess,
@@ -33,6 +33,8 @@
getVariableMetadata,
getConstMetadata,
getCreatedCollectionCount,
+ createCollectionWithPropsExpectSuccess,
+ getCreateItemsResult,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -45,7 +47,9 @@
const itemsListIndexBefore = await getLastTokenId(api, collectionId);
expect(itemsListIndexBefore).to.be.equal(0);
const alice = privateKey('//Alice');
- const args = [{NFT: ['0x31', '0x31']}, {NFT: ['0x32', '0x32']}, {NFT: ['0x33', '0x33']}];
+ const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
+ {Nft: {const_data: '0x32', variable_data: '0x32'}},
+ {Nft: {const_data: '0x33', variable_data: '0x33'}}];
const createMultipleItemsTx = api.tx.unique
.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
await submitTransactionAsync(alice, createMultipleItemsTx);
@@ -135,6 +139,114 @@
expect(result.success).to.be.true;
});
});
+
+ it('Create 0x31, 0x32, 0x33 items in active NFT with property Admin', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemsListIndexBefore = await getLastTokenId(api, collectionId);
+ expect(itemsListIndexBefore).to.be.equal(0);
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
+ {Nft: {const_data: '0x32', variable_data: '0x32'}},
+ {Nft: {const_data: '0x33', variable_data: '0x33'}}];
+ const createMultipleItemsTx = api.tx.unique
+ .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+ await submitTransactionAsync(alice, createMultipleItemsTx);
+ const itemsListIndexAfter = await getLastTokenId(api, collectionId);
+ expect(itemsListIndexAfter).to.be.equal(3);
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setPropertyPermissions(collectionId, [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: false}}]),
+ )).to.not.be.rejected;
+
+ expect(await getTokenOwner(api, collectionId, 1)).to.be.deep.equal(normalizeAccountId(alice.address));
+ expect(await getTokenOwner(api, collectionId, 2)).to.be.deep.equal(normalizeAccountId(alice.address));
+ expect(await getTokenOwner(api, collectionId, 3)).to.be.deep.equal(normalizeAccountId(alice.address));
+
+ expect(await getConstMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
+ expect(await getConstMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
+ expect(await getConstMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+
+ expect(await getVariableMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
+ expect(await getVariableMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
+ expect(await getVariableMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+ });
+ });
+
+ it('Create 0x31, 0x32, 0x33 items in active NFT with property AdminConst', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemsListIndexBefore = await getLastTokenId(api, collectionId);
+ expect(itemsListIndexBefore).to.be.equal(0);
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
+ {Nft: {const_data: '0x32', variable_data: '0x32'}},
+ {Nft: {const_data: '0x33', variable_data: '0x33'}}];
+ const createMultipleItemsTx = api.tx.unique
+ .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+ await submitTransactionAsync(alice, createMultipleItemsTx);
+ const itemsListIndexAfter = await getLastTokenId(api, collectionId);
+ expect(itemsListIndexAfter).to.be.equal(3);
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setPropertyPermissions(collectionId, [{key: 'k', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}}]),
+ )).to.not.be.rejected;
+
+ expect(await getTokenOwner(api, collectionId, 1)).to.be.deep.equal(normalizeAccountId(alice.address));
+ expect(await getTokenOwner(api, collectionId, 2)).to.be.deep.equal(normalizeAccountId(alice.address));
+ expect(await getTokenOwner(api, collectionId, 3)).to.be.deep.equal(normalizeAccountId(alice.address));
+
+ expect(await getConstMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
+ expect(await getConstMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
+ expect(await getConstMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+
+ expect(await getVariableMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
+ expect(await getVariableMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
+ expect(await getVariableMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+ });
+ });
+
+ it('Create 0x31, 0x32, 0x33 items in active NFT with property itemOwnerOrAdmin', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemsListIndexBefore = await getLastTokenId(api, collectionId);
+ expect(itemsListIndexBefore).to.be.equal(0);
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
+ {Nft: {const_data: '0x32', variable_data: '0x32'}},
+ {Nft: {const_data: '0x33', variable_data: '0x33'}}];
+ const createMultipleItemsTx = api.tx.unique
+ .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+ await submitTransactionAsync(alice, createMultipleItemsTx);
+ const itemsListIndexAfter = await getLastTokenId(api, collectionId);
+ expect(itemsListIndexAfter).to.be.equal(3);
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setPropertyPermissions(collectionId, [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]),
+ )).to.not.be.rejected;
+
+ expect(await getTokenOwner(api, collectionId, 1)).to.be.deep.equal(normalizeAccountId(alice.address));
+ expect(await getTokenOwner(api, collectionId, 2)).to.be.deep.equal(normalizeAccountId(alice.address));
+ expect(await getTokenOwner(api, collectionId, 3)).to.be.deep.equal(normalizeAccountId(alice.address));
+
+ expect(await getConstMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
+ expect(await getConstMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
+ expect(await getConstMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+
+ expect(await getVariableMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
+ expect(await getVariableMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
+ expect(await getVariableMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+ });
+ });
});
describe('Integration Test createMultipleItems(collection_id, owner, items_data) with collection admin permissions:', () => {
@@ -155,7 +267,9 @@
const itemsListIndexBefore = await getLastTokenId(api, collectionId);
expect(itemsListIndexBefore).to.be.equal(0);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- const args = [{NFT: ['0x31', '0x31']}, {NFT: ['0x32', '0x32']}, {NFT: ['0x33', '0x33']}];
+ const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
+ {Nft: {const_data: '0x32', variable_data: '0x32'}},
+ {Nft: {const_data: '0x33', variable_data: '0x33'}}];
const createMultipleItemsTx = api.tx.unique
.createMultipleItems(collectionId, normalizeAccountId(bob.address), args);
await submitTransactionAsync(bob, createMultipleItemsTx);
@@ -245,7 +359,9 @@
const collectionId = await createCollectionExpectSuccess();
const itemsListIndexBefore = await getLastTokenId(api, collectionId);
expect(itemsListIndexBefore).to.be.equal(0);
- const args = [{NFT: ['0x31', '0x31']}, {NFT: ['0x32', '0x32']}, {NFT: ['0x33', '0x33']}];
+ const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
+ {Nft: {const_data: '0x32', variable_data: '0x32'}},
+ {Nft: {const_data: '0x33', variable_data: '0x33'}}];
const createMultipleItemsTx = api.tx.unique
.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
await expect(submitTransactionAsync(bob, createMultipleItemsTx)).to.be.rejected;
@@ -361,4 +477,146 @@
await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;
});
});
+
+ it('No editing rights', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
+ propPerm: [{key: 'key1', mutable: true, collectionAdmin: false, tokenOwner: false}]});
+ const itemsListIndexBefore = await getLastTokenId(api, collectionId);
+ expect(itemsListIndexBefore).to.be.equal(0);
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
+ {Nft: {const_data: '0x32', variable_data: '0x32'}},
+ {Nft: {const_data: '0x33', variable_data: '0x33'}}];
+
+ const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+
+ const events = await submitTransactionAsync(alice, createMultipleItemsTx);
+ const result = getCreateItemsResult(events);
+
+ for (const elem of result) {
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(elem.collectionId, elem.itemId, [{key: 'key1', value: 'v2'}]),
+ )).to.be.rejected;
+ }
+
+ // await expect(submitTransactionAsync(bob, createMultipleItemsTx)).to.be.rejected;
+ });
+ });
+
+ it('User doesnt have editing rights', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
+ propPerm: [{key: 'key1', mutable: false, collectionAdmin: false, tokenOwner: false}]});
+ const itemsListIndexBefore = await getLastTokenId(api, collectionId);
+ expect(itemsListIndexBefore).to.be.equal(0);
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
+ {Nft: {const_data: '0x32', variable_data: '0x32'}},
+ {Nft: {const_data: '0x33', variable_data: '0x33'}}];
+
+ const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+
+ const events = await submitTransactionAsync(alice, createMultipleItemsTx);
+ const result = getCreateItemsResult(events);
+
+ for (const elem of result) {
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(elem.collectionId, elem.itemId, [{key: 'key1', value: 'v2'}]),
+ )).to.be.rejected;
+ }
+ });
+ });
+
+ it('Adding property without access rights', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}]});
+ const itemsListIndexBefore = await getLastTokenId(api, collectionId);
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ expect(itemsListIndexBefore).to.be.equal(0);
+ const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
+ {Nft: {const_data: '0x32', variable_data: '0x32'}},
+ {Nft: {const_data: '0x33', variable_data: '0x33'}}];
+
+ const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+
+ const events = await submitTransactionAsync(alice, createMultipleItemsTx);
+ const result = getCreateItemsResult(events);
+
+ for (const elem of result) {
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(elem.collectionId, elem.itemId, [{key: 'key1', value: 'v2'}]),
+ )).to.be.rejected;
+ }
+ });
+ });
+
+ it('Adding more than 64 prps', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
+ propPerm: [{key: 'key1', mutable: true, collectionAdmin: true, tokenOwner: false}]});
+ const itemsListIndexBefore = await getLastTokenId(api, collectionId);
+ expect(itemsListIndexBefore).to.be.equal(0);
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+
+ const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
+ {Nft: {const_data: '0x32', variable_data: '0x32'}},
+ {Nft: {const_data: '0x33', variable_data: '0x33'}}];
+
+ const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+ const events = await submitTransactionAsync(alice, createMultipleItemsTx);
+
+ const result = getCreateItemsResult(events);
+
+ const prps = [];
+
+ for (let i = 0; i < 65; i++) {
+ prps.push({key: `key${i}`, value: `value${i}`});
+ }
+
+ await expect(executeTransaction(api, bob, api.tx.unique.setCollectionProperties(collectionId, prps))).to.be.rejectedWith(/common\.PropertyLimitReached/);
+
+ for (const elem of result) {
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(elem.collectionId, elem.itemId, prps),
+ )).to.be.rejected;
+ }
+ });
+ });
+
+ it('Trying to add bigger property than allowed', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
+ propPerm: [{key: 'key1', mutable: true, collectionAdmin: false, tokenOwner: false}]});
+ const itemsListIndexBefore = await getLastTokenId(api, collectionId);
+ expect(itemsListIndexBefore).to.be.equal(0);
+ const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
+ {Nft: {const_data: '0x32', variable_data: '0x32'}},
+ {Nft: {const_data: '0x33', variable_data: '0x33'}}];
+
+ const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+
+ const events = await submitTransactionAsync(alice, createMultipleItemsTx);
+ const result = getCreateItemsResult(events);
+
+
+ await expect(executeTransaction(api, alice, api.tx.unique.setCollectionProperties(collectionId, [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]))).to.be.rejectedWith(/common\.NoSpaceForProperty/);
+
+ for (const elem of result) {
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(elem.collectionId, elem.itemId, [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]),
+ )).to.be.rejected;
+ }
+ });
+ });
});
tests/src/createMultipleItemsEx.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItemsEx.test.ts
+++ b/tests/src/createMultipleItemsEx.test.ts
@@ -16,8 +16,8 @@
import {expect} from 'chai';
import privateKey from './substrate/privateKey';
-import usingApi, {executeTransaction} from './substrate/substrate-api';
-import {createCollectionExpectSuccess} from './util/helpers';
+import usingApi, {executeTransaction, submitTransactionAsync} from './substrate/substrate-api';
+import {createCollectionExpectSuccess, createCollectionWithPropsExpectSuccess, addCollectionAdminExpectSuccess, getCreateItemsResult} from './util/helpers';
describe('createMultipleItemsEx', () => {
it('can initialize multiple NFT with different owners', async () => {
@@ -51,6 +51,362 @@
});
});
+ it('createMultipleItemsEx with property Admin', async () => {
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+ await usingApi(async (api) => {
+ const data = [
+ {
+ owner: {substrate: alice.address},
+ constData: '0x0000',
+ variableData: '0x1111',
+ }, {
+ owner: {substrate: bob.address},
+ constData: '0x2222',
+ variableData: '0x3333',
+ }, {
+ owner: {substrate: charlie.address},
+ constData: '0x4444',
+ variableData: '0x5555',
+ },
+ ];
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setPropertyPermissions(collection, [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: false}}]),
+ )).to.not.be.rejected;
+
+ await executeTransaction(api, alice, api.tx.unique.createMultipleItemsEx(collection, {
+ NFT: data,
+ }));
+ const tokens = await api.query.nonfungible.tokenData.entries(collection);
+ const json = tokens.map(([, token]) => token.toJSON());
+ expect(json).to.be.deep.equal(data);
+ });
+ });
+
+ it('createMultipleItemsEx with property AdminConst', async () => {
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+ await usingApi(async (api) => {
+ const data = [
+ {
+ owner: {substrate: alice.address},
+ constData: '0x0000',
+ variableData: '0x1111',
+ }, {
+ owner: {substrate: bob.address},
+ constData: '0x2222',
+ variableData: '0x3333',
+ }, {
+ owner: {substrate: charlie.address},
+ constData: '0x4444',
+ variableData: '0x5555',
+ },
+ ];
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setPropertyPermissions(collection, [{key: 'k', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}}]),
+ )).to.not.be.rejected;
+
+ await executeTransaction(api, alice, api.tx.unique.createMultipleItemsEx(collection, {
+ NFT: data,
+ }));
+
+
+ const tokens = await api.query.nonfungible.tokenData.entries(collection);
+ const json = tokens.map(([, token]) => token.toJSON());
+ expect(json).to.be.deep.equal(data);
+ });
+ });
+
+ it('createMultipleItemsEx with property itemOwnerOrAdmin', async () => {
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+ await usingApi(async (api) => {
+ const data = [
+ {
+ owner: {substrate: alice.address},
+ constData: '0x0000',
+ variableData: '0x1111',
+ }, {
+ owner: {substrate: bob.address},
+ constData: '0x2222',
+ variableData: '0x3333',
+ }, {
+ owner: {substrate: charlie.address},
+ constData: '0x4444',
+ variableData: '0x5555',
+ },
+ ];
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setPropertyPermissions(collection, [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]),
+ )).to.not.be.rejected;
+
+ await executeTransaction(api, alice, api.tx.unique.createMultipleItemsEx(collection, {
+ NFT: data,
+ }));
+
+
+ const tokens = await api.query.nonfungible.tokenData.entries(collection);
+ const json = tokens.map(([, token]) => token.toJSON());
+ expect(json).to.be.deep.equal(data);
+ });
+ });
+
+ it('No editing rights', async () => {
+ const collection = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
+ propPerm: [{key: 'key1', mutable: true, collectionAdmin: false, tokenOwner: false}]});
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+ await usingApi(async (api) => {
+ const data = [
+ {
+ owner: {substrate: alice.address},
+ }, {
+ owner: {substrate: bob.address},
+ }, {
+ owner: {substrate: charlie.address},
+ },
+ ];
+
+ const tx = api.tx.unique.createMultipleItemsEx(collection, {NFT: data});
+ await executeTransaction(api, alice, tx);
+
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getCreateItemsResult(events);
+
+ for (const elem of result) {
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(elem.collectionId, elem.itemId, [{key: 'key1', value: 'v2'}]),
+ )).to.be.rejected;
+ }
+ });
+ });
+
+ it('User doesnt have editing rights', async () => {
+ const collection = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
+ propPerm: [{key: 'key1', mutable: false, collectionAdmin: false, tokenOwner: false}]});
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+ await usingApi(async (api) => {
+ const data = [
+ {
+ owner: {substrate: alice.address},
+ }, {
+ owner: {substrate: bob.address},
+ }, {
+ owner: {substrate: charlie.address},
+ },
+ ];
+
+ const tx = api.tx.unique.createMultipleItemsEx(collection, {NFT: data});
+ await executeTransaction(api, alice, tx);
+
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getCreateItemsResult(events);
+
+ for (const elem of result) {
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(elem.collectionId, elem.itemId, [{key: 'key1', value: 'v2'}]),
+ )).to.be.rejected;
+ }
+ });
+ });
+
+ it('Adding property without access rights', async () => {
+ const collection = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}]});
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+ await usingApi(async (api) => {
+ const data = [
+ {
+ owner: {substrate: alice.address},
+ }, {
+ owner: {substrate: bob.address},
+ }, {
+ owner: {substrate: charlie.address},
+ },
+ ];
+
+ const tx = api.tx.unique.createMultipleItemsEx(collection, {NFT: data});
+ await executeTransaction(api, alice, tx);
+
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getCreateItemsResult(events);
+
+ for (const elem of result) {
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(elem.collectionId, elem.itemId, [{key: 'key1', value: 'v2'}]),
+ )).to.be.rejected;
+ }
+ });
+ });
+
+ it('Adding more than 64 prps', async () => {
+ const collection = await createCollectionWithPropsExpectSuccess();
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+ await usingApi(async (api) => {
+ const data = [
+ {
+ owner: {substrate: alice.address},
+ }, {
+ owner: {substrate: bob.address},
+ }, {
+ owner: {substrate: charlie.address},
+ },
+ ];
+
+ const tx = api.tx.unique.createMultipleItemsEx(collection, {NFT: data});
+ await executeTransaction(api, alice, tx);
+
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getCreateItemsResult(events);
+
+ const prps = [];
+
+ for (let i = 0; i < 65; i++) {
+ prps.push({key: `key${i}`, value: `value${i}`});
+ }
+
+ await expect(executeTransaction(api, bob, api.tx.unique.setCollectionProperties(collection, prps))).to.be.rejectedWith(/common\.PropertyLimitReached/);
+
+
+ for (const elem of result) {
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(elem.collectionId, elem.itemId, prps),
+ )).to.be.rejected;
+ }
+ });
+ });
+
+ it('Trying to add bigger property than allowed', async () => {
+ const collection = await createCollectionWithPropsExpectSuccess();
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+ await usingApi(async (api) => {
+ const data = [
+ {
+ owner: {substrate: alice.address},
+ }, {
+ owner: {substrate: bob.address},
+ }, {
+ owner: {substrate: charlie.address},
+ },
+ ];
+
+ const tx = api.tx.unique.createMultipleItemsEx(collection, {NFT: data});
+ await executeTransaction(api, alice, tx);
+
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getCreateItemsResult(events);
+
+ const prps = [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}];
+
+ await expect(executeTransaction(api, bob, api.tx.unique.setCollectionProperties(collection, prps))).to.be.rejectedWith(/common\.NoSpaceForProperty/);
+
+
+ for (const elem of result) {
+ await expect(executeTransaction(
+ api,
+ bob,
+ api.tx.unique.setTokenProperties(elem.collectionId, elem.itemId, prps),
+ )).to.be.rejected;
+ }
+ });
+ });
+
+ it('can initialize multiple NFT with different owners', async () => {
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+ await usingApi(async (api) => {
+ const data = [
+ {
+ owner: {substrate: alice.address},
+ constData: '0x0000',
+ variableData: '0x1111',
+ }, {
+ owner: {substrate: bob.address},
+ constData: '0x2222',
+ variableData: '0x3333',
+ }, {
+ owner: {substrate: charlie.address},
+ constData: '0x4444',
+ variableData: '0x5555',
+ },
+ ];
+
+ await executeTransaction(api, alice, api.tx.unique.createMultipleItemsEx(collection, {
+ NFT: data,
+ }));
+ const tokens = await api.query.nonfungible.tokenData.entries(collection);
+ const json = tokens.map(([, token]) => token.toJSON());
+ expect(json).to.be.deep.equal(data);
+ });
+ });
+
+ it('can initialize multiple NFT with different owners', async () => {
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const charlie = privateKey('//Charlie');
+ await usingApi(async (api) => {
+ const data = [
+ {
+ owner: {substrate: alice.address},
+ constData: '0x0000',
+ variableData: '0x1111',
+ }, {
+ owner: {substrate: bob.address},
+ constData: '0x2222',
+ variableData: '0x3333',
+ }, {
+ owner: {substrate: charlie.address},
+ constData: '0x4444',
+ variableData: '0x5555',
+ },
+ ];
+
+ await executeTransaction(api, alice, api.tx.unique.createMultipleItemsEx(collection, {
+ NFT: data,
+ }));
+ const tokens = await api.query.nonfungible.tokenData.entries(collection);
+ const json = tokens.map(([, token]) => token.toJSON());
+ expect(json).to.be.deep.equal(data);
+ });
+ });
+
it('fails when trying to set multiple owners when creating multiple refungibles', async () => {
const collection = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
const alice = privateKey('//Alice');
@@ -72,3 +428,4 @@
});
});
});
+'';
tests/src/util/helpers.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord} from '@polkadot/types/interfaces';21import {IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36 Substrate: string,37} | {38 Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42 if (typeof input === 'string') {43 if (input.length === 48 || input.length === 47) {44 return {Substrate: input};45 } else if (input.length === 42 && input.startsWith('0x')) {46 return {Ethereum: input.toLowerCase()};47 } else if (input.length === 40 && !input.startsWith('0x')) {48 return {Ethereum: '0x' + input.toLowerCase()};49 } else {50 throw new Error(`Unknown address format: "${input}"`);51 }52 }53 if ('address' in input) {54 return {Substrate: input.address};55 }56 if ('Ethereum' in input) {57 return {58 Ethereum: input.Ethereum.toLowerCase(),59 };60 } else if ('ethereum' in input) {61 return {62 Ethereum: (input as any).ethereum.toLowerCase(),63 };64 } else if ('Substrate' in input) {65 return input;66 } else if ('substrate' in input) {67 return {68 Substrate: (input as any).substrate,69 };70 }7172 // AccountId73 return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76 input = normalizeAccountId(input);77 if ('Substrate' in input) {78 return input.Substrate;79 } else {80 return evmToAddress(input.Ethereum);81 }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92 success: boolean,93};9495interface CreateCollectionResult {96 success: boolean;97 collectionId: number;98}99100interface CreateItemResult {101 success: boolean;102 collectionId: number;103 itemId: number;104 recipient?: CrossAccountId;105}106107interface TransferResult {108 success: boolean;109 collectionId: number;110 itemId: number;111 sender?: CrossAccountId;112 recipient?: CrossAccountId;113 value: bigint;114}115116interface IReFungibleOwner {117 fraction: BN;118 owner: number[];119}120121interface IGetMessage {122 checkMsgUnqMethod: string;123 checkMsgTrsMethod: string;124 checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128 value: number;129}130131export interface IChainLimits {132 collectionNumbersLimit: number;133 accountTokenOwnershipLimit: number;134 collectionsAdminsLimit: number;135 customDataLimit: number;136 nftSponsorTransferTimeout: number;137 fungibleSponsorTransferTimeout: number;138 refungibleSponsorTransferTimeout: number;139 offchainSchemaLimit: number;140 variableOnChainSchemaLimit: number;141 constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145 owner: IReFungibleOwner[];146 constData: number[];147 variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151 let checkMsgUnqMethod = '';152 let checkMsgTrsMethod = '';153 let checkMsgSysMethod = '';154 events.forEach(({event: {method, section}}) => {155 if (section === 'common') {156 checkMsgUnqMethod = method;157 } else if (section === 'treasury') {158 checkMsgTrsMethod = method;159 } else if (section === 'system') {160 checkMsgSysMethod = method;161 } else { return null; }162 });163 const result: IGetMessage = {164 checkMsgUnqMethod,165 checkMsgTrsMethod,166 checkMsgSysMethod,167 };168 return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172 const result: GenericResult = {173 success: false,174 };175 events.forEach(({event: {method}}) => {176 // console.log(` ${phase}: ${section}.${method}:: ${data}`);177 if (method === 'ExtrinsicSuccess') {178 result.success = true;179 }180 });181 return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187 let success = false;188 let collectionId = 0;189 events.forEach(({event: {data, method, section}}) => {190 // console.log(` ${phase}: ${section}.${method}:: ${data}`);191 if (method == 'ExtrinsicSuccess') {192 success = true;193 } else if ((section == 'common') && (method == 'CollectionCreated')) {194 collectionId = parseInt(data[0].toString(), 10);195 }196 });197 const result: CreateCollectionResult = {198 success,199 collectionId,200 };201 return result;202}203204export function getCreateItemResult(events: EventRecord[]): CreateItemResult {205 let success = false;206 let collectionId = 0;207 let itemId = 0;208 let recipient;209 events.forEach(({event: {data, method, section}}) => {210 // console.log(` ${phase}: ${section}.${method}:: ${data}`);211 if (method == 'ExtrinsicSuccess') {212 success = true;213 } else if ((section == 'common') && (method == 'ItemCreated')) {214 collectionId = parseInt(data[0].toString(), 10);215 itemId = parseInt(data[1].toString(), 10);216 recipient = normalizeAccountId(data[2].toJSON() as any);217 }218 });219 const result: CreateItemResult = {220 success,221 collectionId,222 itemId,223 recipient,224 };225 return result;226}227228export function getTransferResult(events: EventRecord[]): TransferResult {229 const result: TransferResult = {230 success: false,231 collectionId: 0,232 itemId: 0,233 value: 0n,234 };235236 events.forEach(({event: {data, method, section}}) => {237 if (method === 'ExtrinsicSuccess') {238 result.success = true;239 } else if (section === 'common' && method === 'Transfer') {240 result.collectionId = +data[0].toString();241 result.itemId = +data[1].toString();242 result.sender = normalizeAccountId(data[2].toJSON() as any);243 result.recipient = normalizeAccountId(data[3].toJSON() as any);244 result.value = BigInt(data[4].toString());245 }246 });247248 return result;249}250251interface Nft {252 type: 'NFT';253}254255interface Fungible {256 type: 'Fungible';257 decimalPoints: number;258}259260interface ReFungible {261 type: 'ReFungible';262}263264type CollectionMode = Nft | Fungible | ReFungible;265266export type CreateCollectionParams = {267 mode: CollectionMode,268 name: string,269 description: string,270 tokenPrefix: string,271 schemaVersion: string,272};273274const defaultCreateCollectionParams: CreateCollectionParams = {275 description: 'description',276 mode: {type: 'NFT'},277 name: 'name',278 tokenPrefix: 'prefix',279 schemaVersion: 'ImageURL',280};281282export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {283 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};284285 let collectionId = 0;286 await usingApi(async (api) => {287 // Get number of collections before the transaction288 const collectionCountBefore = await getCreatedCollectionCount(api);289290 // Run the CreateCollection transaction291 const alicePrivateKey = privateKey('//Alice');292293 let modeprm = {};294 if (mode.type === 'NFT') {295 modeprm = {nft: null};296 } else if (mode.type === 'Fungible') {297 modeprm = {fungible: mode.decimalPoints};298 } else if (mode.type === 'ReFungible') {299 modeprm = {refungible: null};300 }301302 const tx = api.tx.unique.createCollectionEx({303 name: strToUTF16(name), 304 description: strToUTF16(description), 305 tokenPrefix: strToUTF16(tokenPrefix), 306 mode: modeprm as any,307 schemaVersion: schemaVersion,308 });309 const events = await submitTransactionAsync(alicePrivateKey, tx);310 const result = getCreateCollectionResult(events);311312 // Get number of collections after the transaction313 const collectionCountAfter = await getCreatedCollectionCount(api);314315 // Get the collection316 const collection = await queryCollectionExpectSuccess(api, result.collectionId);317318 // What to expect319 // tslint:disable-next-line:no-unused-expression320 expect(result.success).to.be.true;321 expect(result.collectionId).to.be.equal(collectionCountAfter);322 // tslint:disable-next-line:no-unused-expression323 expect(collection).to.be.not.null;324 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');325 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));326 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);327 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);328 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);329330 collectionId = result.collectionId;331 });332333 return collectionId;334}335336export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {337 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};338339 let modeprm = {};340 if (mode.type === 'NFT') {341 modeprm = {nft: null};342 } else if (mode.type === 'Fungible') {343 modeprm = {fungible: mode.decimalPoints};344 } else if (mode.type === 'ReFungible') {345 modeprm = {refungible: null};346 }347348 await usingApi(async (api) => {349 // Get number of collections before the transaction350 const collectionCountBefore = await getCreatedCollectionCount(api);351352 // Run the CreateCollection transaction353 const alicePrivateKey = privateKey('//Alice');354 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});355 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;356357 // Get number of collections after the transaction358 const collectionCountAfter = await getCreatedCollectionCount(api);359360 // What to expect361 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');362 });363}364365export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {366 let bal = 0n;367 let unused;368 do {369 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;370 const keyring = new Keyring({type: 'sr25519'});371 unused = keyring.addFromUri(`//${randomSeed}`);372 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();373 } while (bal !== 0n);374 return unused;375}376377export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {378 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();379}380381export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {382 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));383}384385export async function findNotExistingCollection(api: ApiPromise): Promise<number> {386 const totalNumber = await getCreatedCollectionCount(api);387 const newCollection: number = totalNumber + 1;388 return newCollection;389}390391function getDestroyResult(events: EventRecord[]): boolean {392 let success = false;393 events.forEach(({event: {method}}) => {394 if (method == 'ExtrinsicSuccess') {395 success = true;396 }397 });398 return success;399}400401export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {402 await usingApi(async (api) => {403 // Run the DestroyCollection transaction404 const alicePrivateKey = privateKey(senderSeed);405 const tx = api.tx.unique.destroyCollection(collectionId);406 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;407 });408}409410export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {411 await usingApi(async (api) => {412 // Run the DestroyCollection transaction413 const alicePrivateKey = privateKey(senderSeed);414 const tx = api.tx.unique.destroyCollection(collectionId);415 const events = await submitTransactionAsync(alicePrivateKey, tx);416 const result = getDestroyResult(events);417 expect(result).to.be.true;418419 // What to expect420 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;421 });422}423424export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {425 await usingApi(async (api) => {426 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);427 const events = await submitTransactionAsync(sender, tx);428 const result = getGenericResult(events);429430 expect(result.success).to.be.true;431 });432}433434export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {435 await usingApi(async (api) => {436 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);437 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;438 const result = getGenericResult(events);439440 expect(result.success).to.be.false;441 });442}443444export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {445 await usingApi(async (api) => {446447 // Run the transaction448 const senderPrivateKey = privateKey(sender);449 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);450 const events = await submitTransactionAsync(senderPrivateKey, tx);451 const result = getGenericResult(events);452453 // Get the collection454 const collection = await queryCollectionExpectSuccess(api, collectionId);455456 // What to expect457 expect(result.success).to.be.true;458 expect(collection.sponsorship.toJSON()).to.deep.equal({459 unconfirmed: sponsor,460 });461 });462}463464export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {465 await usingApi(async (api) => {466467 // Run the transaction468 const alicePrivateKey = privateKey(sender);469 const tx = api.tx.unique.removeCollectionSponsor(collectionId);470 const events = await submitTransactionAsync(alicePrivateKey, tx);471 const result = getGenericResult(events);472473 // Get the collection474 const collection = await queryCollectionExpectSuccess(api, collectionId);475476 // What to expect477 expect(result.success).to.be.true;478 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});479 });480}481482export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {483 await usingApi(async (api) => {484485 // Run the transaction486 const alicePrivateKey = privateKey(senderSeed);487 const tx = api.tx.unique.removeCollectionSponsor(collectionId);488 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;489 });490}491492export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {493 await usingApi(async (api) => {494495 // Run the transaction496 const alicePrivateKey = privateKey(senderSeed);497 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);498 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;499 });500}501502export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {503 await usingApi(async (api) => {504505 // Run the transaction506 const sender = privateKey(senderSeed);507 const tx = api.tx.unique.confirmSponsorship(collectionId);508 const events = await submitTransactionAsync(sender, tx);509 const result = getGenericResult(events);510511 // Get the collection512 const collection = await queryCollectionExpectSuccess(api, collectionId);513514 // What to expect515 expect(result.success).to.be.true;516 expect(collection.sponsorship.toJSON()).to.be.deep.equal({517 confirmed: sender.address,518 });519 });520}521522523export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {524 await usingApi(async (api) => {525526 // Run the transaction527 const sender = privateKey(senderSeed);528 const tx = api.tx.unique.confirmSponsorship(collectionId);529 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;530 });531}532533export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {534535 await usingApi(async (api) => {536 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);537 const events = await submitTransactionAsync(sender, tx);538 const result = getGenericResult(events);539540 expect(result.success).to.be.true;541 });542}543544export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {545546 await usingApi(async (api) => {547 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);548 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;549 const result = getGenericResult(events);550551 expect(result.success).to.be.false;552 });553}554555export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {556 await usingApi(async (api) => {557 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);558 const events = await submitTransactionAsync(sender, tx);559 const result = getGenericResult(events);560561 expect(result.success).to.be.true;562 });563}564565export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {566 await usingApi(async (api) => {567 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);568 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;569 const result = getGenericResult(events);570571 expect(result.success).to.be.false;572 });573}574575export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {576577 await usingApi(async (api) => {578579 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);580 const events = await submitTransactionAsync(sender, tx);581 const result = getGenericResult(events);582583 expect(result.success).to.be.true;584 });585}586587export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {588589 await usingApi(async (api) => {590591 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);592 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;593 const result = getGenericResult(events);594595 expect(result.success).to.be.false;596 });597}598599export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {600 await usingApi(async (api) => {601 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);602 const events = await submitTransactionAsync(sender, tx);603 const result = getGenericResult(events);604605 expect(result.success).to.be.true;606 });607}608609export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {610 await usingApi(async (api) => {611 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);612 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;613 const result = getGenericResult(events);614615 expect(result.success).to.be.false;616 });617}618619export async function getNextSponsored(620 api: ApiPromise,621 collectionId: number,622 account: string | CrossAccountId,623 tokenId: number,624): Promise<number> {625 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));626}627628export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {629 await usingApi(async (api) => {630 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);631 const events = await submitTransactionAsync(sender, tx);632 const result = getGenericResult(events);633634 expect(result.success).to.be.true;635 });636}637638export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {639 let allowlisted = false;640 await usingApi(async (api) => {641 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;642 });643 return allowlisted;644}645646export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {647 await usingApi(async (api) => {648 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());649 const events = await submitTransactionAsync(sender, tx);650 const result = getGenericResult(events);651652 expect(result.success).to.be.true;653 });654}655656export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {657 await usingApi(async (api) => {658 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());659 const events = await submitTransactionAsync(sender, tx);660 const result = getGenericResult(events);661662 expect(result.success).to.be.true;663 });664}665666export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {667 await usingApi(async (api) => {668 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());669 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;670 const result = getGenericResult(events);671672 expect(result.success).to.be.false;673 });674}675676export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {677 await usingApi(async (api) => {678 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));679 const events = await submitTransactionAsync(sender, tx);680 const result = getGenericResult(events);681682 expect(result.success).to.be.true;683 });684}685686export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {687 await usingApi(async (api) => {688 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));689 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;690 });691}692693export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {694 await usingApi(async (api) => {695 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));696 const events = await submitTransactionAsync(sender, tx);697 const result = getGenericResult(events);698699 expect(result.success).to.be.true;700 });701}702703export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {704 await usingApi(async (api) => {705 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));706 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;707 });708}709710export interface CreateFungibleData {711 readonly Value: bigint;712}713714export interface CreateReFungibleData { }715export interface CreateNftData { }716717export type CreateItemData = {718 NFT: CreateNftData;719} | {720 Fungible: CreateFungibleData;721} | {722 ReFungible: CreateReFungibleData;723};724725export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {726 await usingApi(async (api) => {727 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);728 // if burning token by admin - use adminButnItemExpectSuccess729 expect(balanceBefore >= BigInt(value)).to.be.true;730731 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);732 const events = await submitTransactionAsync(sender, tx);733 const result = getGenericResult(events);734 expect(result.success).to.be.true;735736 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);737 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);738 });739}740741export async function742approveExpectSuccess(743 collectionId: number,744 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,745) {746 await usingApi(async (api: ApiPromise) => {747 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);748 const events = await submitTransactionAsync(owner, approveUniqueTx);749 const result = getGenericResult(events);750 expect(result.success).to.be.true;751752 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));753 });754}755756export async function adminApproveFromExpectSuccess(757 collectionId: number,758 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,759) {760 await usingApi(async (api: ApiPromise) => {761 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);762 const events = await submitTransactionAsync(admin, approveUniqueTx);763 const result = getGenericResult(events);764 expect(result.success).to.be.true;765766 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));767 });768}769770export async function771transferFromExpectSuccess(772 collectionId: number,773 tokenId: number,774 accountApproved: IKeyringPair,775 accountFrom: IKeyringPair | CrossAccountId,776 accountTo: IKeyringPair | CrossAccountId,777 value: number | bigint = 1,778 type = 'NFT',779) {780 await usingApi(async (api: ApiPromise) => {781 const from = normalizeAccountId(accountFrom);782 const to = normalizeAccountId(accountTo);783 let balanceBefore = 0n;784 if (type === 'Fungible') {785 balanceBefore = await getBalance(api, collectionId, to, tokenId);786 }787 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);788 const events = await submitTransactionAsync(accountApproved, transferFromTx);789 const result = getCreateItemResult(events);790 // tslint:disable-next-line:no-unused-expression791 expect(result.success).to.be.true;792 if (type === 'NFT') {793 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);794 }795 if (type === 'Fungible') {796 const balanceAfter = await getBalance(api, collectionId, to, tokenId);797 if (JSON.stringify(to) !== JSON.stringify(from)) {798 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));799 } else {800 expect(balanceAfter).to.be.equal(balanceBefore);801 }802 }803 if (type === 'ReFungible') {804 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));805 }806 });807}808809export async function810transferFromExpectFail(811 collectionId: number,812 tokenId: number,813 accountApproved: IKeyringPair,814 accountFrom: IKeyringPair,815 accountTo: IKeyringPair,816 value: number | bigint = 1,817) {818 await usingApi(async (api: ApiPromise) => {819 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);820 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;821 const result = getCreateCollectionResult(events);822 // tslint:disable-next-line:no-unused-expression823 expect(result.success).to.be.false;824 });825}826827/* eslint no-async-promise-executor: "off" */828async function getBlockNumber(api: ApiPromise): Promise<number> {829 return new Promise<number>(async (resolve) => {830 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {831 unsubscribe();832 resolve(head.number.toNumber());833 });834 });835}836837export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {838 await usingApi(async (api) => {839 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));840 const events = await submitTransactionAsync(sender, changeAdminTx);841 const result = getCreateCollectionResult(events);842 expect(result.success).to.be.true;843 });844}845846export async function847getFreeBalance(account: IKeyringPair): Promise<bigint> {848 let balance = 0n;849 await usingApi(async (api) => {850 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());851 });852853 return balance;854}855856export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {857 const tx = api.tx.balances.transfer(target, amount);858 const events = await submitTransactionAsync(source, tx);859 const result = getGenericResult(events);860 expect(result.success).to.be.true;861}862863export async function864scheduleTransferExpectSuccess(865 collectionId: number,866 tokenId: number,867 sender: IKeyringPair,868 recipient: IKeyringPair,869 value: number | bigint = 1,870 blockSchedule: number,871) {872 await usingApi(async (api: ApiPromise) => {873 const blockNumber: number | undefined = await getBlockNumber(api);874 const expectedBlockNumber = blockNumber + blockSchedule;875876 expect(blockNumber).to.be.greaterThan(0);877 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);878 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);879880 await submitTransactionAsync(sender, scheduleTx);881882 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();883884 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));885886 // sleep for 4 blocks887 await waitNewBlocks(blockSchedule + 1);888889 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();890891 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));892 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);893 });894}895896897export async function898transferExpectSuccess(899 collectionId: number,900 tokenId: number,901 sender: IKeyringPair,902 recipient: IKeyringPair | CrossAccountId,903 value: number | bigint = 1,904 type = 'NFT',905) {906 await usingApi(async (api: ApiPromise) => {907 const from = normalizeAccountId(sender);908 const to = normalizeAccountId(recipient);909910 let balanceBefore = 0n;911 if (type === 'Fungible') {912 balanceBefore = await getBalance(api, collectionId, to, tokenId);913 }914 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);915 const events = await submitTransactionAsync(sender, transferTx);916 const result = getTransferResult(events);917 // tslint:disable-next-line:no-unused-expression918 expect(result.success).to.be.true;919 expect(result.collectionId).to.be.equal(collectionId);920 expect(result.itemId).to.be.equal(tokenId);921 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));922 expect(result.recipient).to.be.deep.equal(to);923 expect(result.value).to.be.equal(BigInt(value));924 if (type === 'NFT') {925 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);926 }927 if (type === 'Fungible') {928 const balanceAfter = await getBalance(api, collectionId, to, tokenId);929 if (JSON.stringify(to) !== JSON.stringify(from)) {930 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));931 } else {932 expect(balanceAfter).to.be.equal(balanceBefore);933 }934 }935 if (type === 'ReFungible') {936 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;937 }938 });939}940941export async function942transferExpectFailure(943 collectionId: number,944 tokenId: number,945 sender: IKeyringPair,946 recipient: IKeyringPair | CrossAccountId,947 value: number | bigint = 1,948) {949 await usingApi(async (api: ApiPromise) => {950 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);951 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;952 const result = getGenericResult(events);953 // if (events && Array.isArray(events)) {954 // const result = getCreateCollectionResult(events);955 // tslint:disable-next-line:no-unused-expression956 expect(result.success).to.be.false;957 //}958 });959}960961export async function962approveExpectFail(963 collectionId: number,964 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,965) {966 await usingApi(async (api: ApiPromise) => {967 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);968 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;969 const result = getCreateCollectionResult(events);970 // tslint:disable-next-line:no-unused-expression971 expect(result.success).to.be.false;972 });973}974975export async function getBalance(976 api: ApiPromise,977 collectionId: number,978 owner: string | CrossAccountId,979 token: number,980): Promise<bigint> {981 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();982}983export async function getTokenOwner(984 api: ApiPromise,985 collectionId: number,986 token: number,987): Promise<CrossAccountId> {988 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;989 if (owner == null) throw new Error('owner == null');990 return normalizeAccountId(owner);991}992export async function getTopmostTokenOwner(993 api: ApiPromise,994 collectionId: number,995 token: number,996): Promise<CrossAccountId> {997 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;998 if (owner == null) throw new Error('owner == null');999 return normalizeAccountId(owner);1000}1001export async function isTokenExists(1002 api: ApiPromise,1003 collectionId: number,1004 token: number,1005): Promise<boolean> {1006 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1007}1008export async function getLastTokenId(1009 api: ApiPromise,1010 collectionId: number,1011): Promise<number> {1012 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1013}1014export async function getAdminList(1015 api: ApiPromise,1016 collectionId: number,1017): Promise<string[]> {1018 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1019}1020export async function getVariableMetadata(1021 api: ApiPromise,1022 collectionId: number,1023 tokenId: number,1024): Promise<number[]> {1025 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1026}1027export async function getConstMetadata(1028 api: ApiPromise,1029 collectionId: number,1030 tokenId: number,1031): Promise<number[]> {1032 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1033}10341035export async function createFungibleItemExpectSuccess(1036 sender: IKeyringPair,1037 collectionId: number,1038 data: CreateFungibleData,1039 owner: CrossAccountId | string = sender.address,1040) {1041 return await usingApi(async (api) => {1042 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10431044 const events = await submitTransactionAsync(sender, tx);1045 const result = getCreateItemResult(events);10461047 expect(result.success).to.be.true;1048 return result.itemId;1049 });1050}10511052export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1053 let newItemId = 0;1054 await usingApi(async (api) => {1055 const to = normalizeAccountId(owner);1056 const itemCountBefore = await getLastTokenId(api, collectionId);1057 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10581059 let tx;1060 if (createMode === 'Fungible') {1061 const createData = {fungible: {value: 10}};1062 tx = api.tx.unique.createItem(collectionId, to, createData as any);1063 } else if (createMode === 'ReFungible') {1064 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1065 tx = api.tx.unique.createItem(collectionId, to, createData as any);1066 } else {1067 const createData = {nft: {const_data: [], variable_data: []}};1068 tx = api.tx.unique.createItem(collectionId, to, createData as any);1069 }10701071 const events = await submitTransactionAsync(sender, tx);1072 const result = getCreateItemResult(events);10731074 const itemCountAfter = await getLastTokenId(api, collectionId);1075 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10761077 // What to expect1078 // tslint:disable-next-line:no-unused-expression1079 expect(result.success).to.be.true;1080 if (createMode === 'Fungible') {1081 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1082 } else {1083 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1084 }1085 expect(collectionId).to.be.equal(result.collectionId);1086 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1087 expect(to).to.be.deep.equal(result.recipient);1088 newItemId = result.itemId;1089 });1090 return newItemId;1091}10921093export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1094 await usingApi(async (api) => {1095 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10961097 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1098 const result = getCreateItemResult(events);10991100 expect(result.success).to.be.false;1101 });1102}11031104export async function setPublicAccessModeExpectSuccess(1105 sender: IKeyringPair, collectionId: number,1106 accessMode: 'Normal' | 'AllowList',1107) {1108 await usingApi(async (api) => {11091110 // Run the transaction1111 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1112 const events = await submitTransactionAsync(sender, tx);1113 const result = getGenericResult(events);11141115 // Get the collection1116 const collection = await queryCollectionExpectSuccess(api, collectionId);11171118 // What to expect1119 // tslint:disable-next-line:no-unused-expression1120 expect(result.success).to.be.true;1121 expect(collection.access.toHuman()).to.be.equal(accessMode);1122 });1123}11241125export async function setPublicAccessModeExpectFail(1126 sender: IKeyringPair, collectionId: number,1127 accessMode: 'Normal' | 'AllowList',1128) {1129 await usingApi(async (api) => {11301131 // Run the transaction1132 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1133 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1134 const result = getGenericResult(events);11351136 // What to expect1137 // tslint:disable-next-line:no-unused-expression1138 expect(result.success).to.be.false;1139 });1140}11411142export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1143 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1144}11451146export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1147 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1148}11491150export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1151 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1152}11531154export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1155 await usingApi(async (api) => {11561157 // Run the transaction1158 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1159 const events = await submitTransactionAsync(sender, tx);1160 const result = getGenericResult(events);1161 expect(result.success).to.be.true;11621163 // Get the collection1164 const collection = await queryCollectionExpectSuccess(api, collectionId);11651166 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1167 });1168}11691170export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1171 await setMintPermissionExpectSuccess(sender, collectionId, true);1172}11731174export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1175 await usingApi(async (api) => {1176 // Run the transaction1177 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1178 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1179 const result = getCreateCollectionResult(events);1180 // tslint:disable-next-line:no-unused-expression1181 expect(result.success).to.be.false;1182 });1183}11841185export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1186 await usingApi(async (api) => {1187 // Run the transaction1188 const tx = api.tx.unique.setChainLimits(limits);1189 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1190 const result = getCreateCollectionResult(events);1191 // tslint:disable-next-line:no-unused-expression1192 expect(result.success).to.be.false;1193 });1194}11951196export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1197 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1198}11991200export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1201 await usingApi(async (api) => {1202 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12031204 // Run the transaction1205 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1206 const events = await submitTransactionAsync(sender, tx);1207 const result = getGenericResult(events);1208 expect(result.success).to.be.true;12091210 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1211 });1212}12131214export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1215 await usingApi(async (api) => {12161217 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12181219 // Run the transaction1220 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1221 const events = await submitTransactionAsync(sender, tx);1222 const result = getGenericResult(events);1223 expect(result.success).to.be.true;12241225 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1226 });1227}12281229export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1230 await usingApi(async (api) => {12311232 // Run the transaction1233 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1234 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1235 const result = getGenericResult(events);12361237 // What to expect1238 // tslint:disable-next-line:no-unused-expression1239 expect(result.success).to.be.false;1240 });1241}12421243export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1244 await usingApi(async (api) => {1245 // Run the transaction1246 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1247 const events = await submitTransactionAsync(sender, tx);1248 const result = getGenericResult(events);12491250 // What to expect1251 // tslint:disable-next-line:no-unused-expression1252 expect(result.success).to.be.true;1253 });1254}12551256export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1257 await usingApi(async (api) => {1258 // Run the transaction1259 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1260 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1261 const result = getGenericResult(events);12621263 // What to expect1264 // tslint:disable-next-line:no-unused-expression1265 expect(result.success).to.be.false;1266 });1267}12681269export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1270 : Promise<UpDataStructsRpcCollection | null> => {1271 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1272};12731274export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1275 // set global object - collectionsCount1276 return (await api.rpc.unique.collectionStats()).created.toNumber();1277};12781279export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1280 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1281}12821283export async function waitNewBlocks(blocksCount = 1): Promise<void> {1284 await usingApi(async (api) => {1285 const promise = new Promise<void>(async (resolve) => {1286 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1287 if (blocksCount > 0) {1288 blocksCount--;1289 } else {1290 unsubscribe();1291 resolve();1292 }1293 });1294 });1295 return promise;1296 });1297}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord} from '@polkadot/types/interfaces';21import {IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36 Substrate: string,37} | {38 Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42 if (typeof input === 'string') {43 if (input.length === 48 || input.length === 47) {44 return {Substrate: input};45 } else if (input.length === 42 && input.startsWith('0x')) {46 return {Ethereum: input.toLowerCase()};47 } else if (input.length === 40 && !input.startsWith('0x')) {48 return {Ethereum: '0x' + input.toLowerCase()};49 } else {50 throw new Error(`Unknown address format: "${input}"`);51 }52 }53 if ('address' in input) {54 return {Substrate: input.address};55 }56 if ('Ethereum' in input) {57 return {58 Ethereum: input.Ethereum.toLowerCase(),59 };60 } else if ('ethereum' in input) {61 return {62 Ethereum: (input as any).ethereum.toLowerCase(),63 };64 } else if ('Substrate' in input) {65 return input;66 } else if ('substrate' in input) {67 return {68 Substrate: (input as any).substrate,69 };70 }7172 // AccountId73 return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76 input = normalizeAccountId(input);77 if ('Substrate' in input) {78 return input.Substrate;79 } else {80 return evmToAddress(input.Ethereum);81 }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92 success: boolean,93};9495interface CreateCollectionResult {96 success: boolean;97 collectionId: number;98}99100interface CreateItemResult {101 success: boolean;102 collectionId: number;103 itemId: number;104 recipient?: CrossAccountId;105}106107interface TransferResult {108 success: boolean;109 collectionId: number;110 itemId: number;111 sender?: CrossAccountId;112 recipient?: CrossAccountId;113 value: bigint;114}115116interface IReFungibleOwner {117 fraction: BN;118 owner: number[];119}120121interface IGetMessage {122 checkMsgUnqMethod: string;123 checkMsgTrsMethod: string;124 checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128 value: number;129}130131export interface IChainLimits {132 collectionNumbersLimit: number;133 accountTokenOwnershipLimit: number;134 collectionsAdminsLimit: number;135 customDataLimit: number;136 nftSponsorTransferTimeout: number;137 fungibleSponsorTransferTimeout: number;138 refungibleSponsorTransferTimeout: number;139 offchainSchemaLimit: number;140 variableOnChainSchemaLimit: number;141 constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145 owner: IReFungibleOwner[];146 constData: number[];147 variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151 let checkMsgUnqMethod = '';152 let checkMsgTrsMethod = '';153 let checkMsgSysMethod = '';154 events.forEach(({event: {method, section}}) => {155 if (section === 'common') {156 checkMsgUnqMethod = method;157 } else if (section === 'treasury') {158 checkMsgTrsMethod = method;159 } else if (section === 'system') {160 checkMsgSysMethod = method;161 } else { return null; }162 });163 const result: IGetMessage = {164 checkMsgUnqMethod,165 checkMsgTrsMethod,166 checkMsgSysMethod,167 };168 return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172 const result: GenericResult = {173 success: false,174 };175 events.forEach(({event: {method}}) => {176 // console.log(` ${phase}: ${section}.${method}:: ${data}`);177 if (method === 'ExtrinsicSuccess') {178 result.success = true;179 }180 });181 return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187 let success = false;188 let collectionId = 0;189 events.forEach(({event: {data, method, section}}) => {190 // console.log(` ${phase}: ${section}.${method}:: ${data}`);191 if (method == 'ExtrinsicSuccess') {192 success = true;193 } else if ((section == 'common') && (method == 'CollectionCreated')) {194 collectionId = parseInt(data[0].toString(), 10);195 }196 });197 const result: CreateCollectionResult = {198 success,199 collectionId,200 };201 return result;202}203204export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {205 let success = false;206 let collectionId = 0;207 let itemId = 0;208 let recipient;209210 const results : CreateItemResult[] = [];211212 events.forEach(({event: {data, method, section}}) => {213 // console.log(` ${phase}: ${section}.${method}:: ${data}`);214 if (method == 'ExtrinsicSuccess') {215 success = true;216 } else if ((section == 'common') && (method == 'ItemCreated')) {217 collectionId = parseInt(data[0].toString(), 10);218 itemId = parseInt(data[1].toString(), 10);219 recipient = normalizeAccountId(data[2].toJSON() as any);220221 const itemRes: CreateItemResult = {222 success,223 collectionId,224 itemId,225 recipient,226 };227228 results.push(itemRes);229 }230 });231232 return results;233}234235export function getCreateItemResult(events: EventRecord[]): CreateItemResult {236 let success = false;237 let collectionId = 0;238 let itemId = 0;239 let recipient;240 events.forEach(({event: {data, method, section}}) => {241 // console.log(` ${phase}: ${section}.${method}:: ${data}`);242 if (method == 'ExtrinsicSuccess') {243 success = true;244 } else if ((section == 'common') && (method == 'ItemCreated')) {245 collectionId = parseInt(data[0].toString(), 10);246 itemId = parseInt(data[1].toString(), 10);247 recipient = normalizeAccountId(data[2].toJSON() as any);248 }249 });250 const result: CreateItemResult = {251 success,252 collectionId,253 itemId,254 recipient,255 };256 return result;257}258259export function getTransferResult(events: EventRecord[]): TransferResult {260 const result: TransferResult = {261 success: false,262 collectionId: 0,263 itemId: 0,264 value: 0n,265 };266267 events.forEach(({event: {data, method, section}}) => {268 if (method === 'ExtrinsicSuccess') {269 result.success = true;270 } else if (section === 'common' && method === 'Transfer') {271 result.collectionId = +data[0].toString();272 result.itemId = +data[1].toString();273 result.sender = normalizeAccountId(data[2].toJSON() as any);274 result.recipient = normalizeAccountId(data[3].toJSON() as any);275 result.value = BigInt(data[4].toString());276 }277 });278279 return result;280}281282interface Nft {283 type: 'NFT';284}285286interface Fungible {287 type: 'Fungible';288 decimalPoints: number;289}290291interface ReFungible {292 type: 'ReFungible';293}294295type CollectionMode = Nft | Fungible | ReFungible;296297export type Property = {298 key: any,299 value: any,300};301302type PropertyPermission = {303 key: any,304 mutable: boolean;305 collectionAdmin: boolean;306 tokenOwner: boolean;307}308309export type CreateCollectionParams = {310 mode: CollectionMode,311 name: string,312 description: string,313 tokenPrefix: string,314 schemaVersion: string,315 properties?: Array<Property>,316 propPerm?: Array<PropertyPermission>317};318319const defaultCreateCollectionParams: CreateCollectionParams = {320 description: 'description',321 mode: {type: 'NFT'},322 name: 'name',323 tokenPrefix: 'prefix',324 schemaVersion: 'ImageURL',325};326327export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {328 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};329330 let collectionId = 0;331 await usingApi(async (api) => {332 // Get number of collections before the transaction333 const collectionCountBefore = await getCreatedCollectionCount(api);334335 // Run the CreateCollection transaction336 const alicePrivateKey = privateKey('//Alice');337338 let modeprm = {};339 if (mode.type === 'NFT') {340 modeprm = {nft: null};341 } else if (mode.type === 'Fungible') {342 modeprm = {fungible: mode.decimalPoints};343 } else if (mode.type === 'ReFungible') {344 modeprm = {refungible: null};345 }346347 const tx = api.tx.unique.createCollectionEx({348 name: strToUTF16(name), 349 description: strToUTF16(description), 350 tokenPrefix: strToUTF16(tokenPrefix), 351 mode: modeprm as any,352 schemaVersion: schemaVersion,353 });354 const events = await submitTransactionAsync(alicePrivateKey, tx);355 const result = getCreateCollectionResult(events);356357 // Get number of collections after the transaction358 const collectionCountAfter = await getCreatedCollectionCount(api);359360 // Get the collection361 const collection = await queryCollectionExpectSuccess(api, result.collectionId);362363 // What to expect364 // tslint:disable-next-line:no-unused-expression365 expect(result.success).to.be.true;366 expect(result.collectionId).to.be.equal(collectionCountAfter);367 // tslint:disable-next-line:no-unused-expression368 expect(collection).to.be.not.null;369 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');370 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));371 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);372 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);373 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);374375 collectionId = result.collectionId;376 });377378 return collectionId;379}380381export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {382 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};383384 let collectionId = 0;385 await usingApi(async (api) => {386 // Get number of collections before the transaction387 const collectionCountBefore = await getCreatedCollectionCount(api);388389 // Run the CreateCollection transaction390 const alicePrivateKey = privateKey('//Alice');391392 let modeprm = {};393 if (mode.type === 'NFT') {394 modeprm = {nft: null};395 } else if (mode.type === 'Fungible') {396 modeprm = {fungible: mode.decimalPoints};397 } else if (mode.type === 'ReFungible') {398 modeprm = {refungible: null};399 }400401 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});402 const events = await submitTransactionAsync(alicePrivateKey, tx);403 const result = getCreateCollectionResult(events);404405 // Get number of collections after the transaction406 const collectionCountAfter = await getCreatedCollectionCount(api);407408 // Get the collection409 const collection = await queryCollectionExpectSuccess(api, result.collectionId);410411 // What to expect412 // tslint:disable-next-line:no-unused-expression413 expect(result.success).to.be.true;414 expect(result.collectionId).to.be.equal(collectionCountAfter);415 // tslint:disable-next-line:no-unused-expression416 expect(collection).to.be.not.null;417 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');418 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));419 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);420 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);421 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);422423424 collectionId = result.collectionId;425 });426427 return collectionId;428}429430export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {431 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};432433 const collectionId = 0;434 await usingApi(async (api) => {435 // Get number of collections before the transaction436 const collectionCountBefore = await getCreatedCollectionCount(api);437438 // Run the CreateCollection transaction439 const alicePrivateKey = privateKey('//Alice');440441 let modeprm = {};442 if (mode.type === 'NFT') {443 modeprm = {nft: null};444 } else if (mode.type === 'Fungible') {445 modeprm = {fungible: mode.decimalPoints};446 } else if (mode.type === 'ReFungible') {447 modeprm = {refungible: null};448 }449450 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});451 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;452453454 // Get number of collections after the transaction455 const collectionCountAfter = await getCreatedCollectionCount(api);456457 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');458 });459}460461export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {462 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};463464 let modeprm = {};465 if (mode.type === 'NFT') {466 modeprm = {nft: null};467 } else if (mode.type === 'Fungible') {468 modeprm = {fungible: mode.decimalPoints};469 } else if (mode.type === 'ReFungible') {470 modeprm = {refungible: null};471 }472473 await usingApi(async (api) => {474 // Get number of collections before the transaction475 const collectionCountBefore = await getCreatedCollectionCount(api);476477 // Run the CreateCollection transaction478 const alicePrivateKey = privateKey('//Alice');479 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});480 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;481482 // Get number of collections after the transaction483 const collectionCountAfter = await getCreatedCollectionCount(api);484485 // What to expect486 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');487 });488}489490export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {491 let bal = 0n;492 let unused;493 do {494 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;495 const keyring = new Keyring({type: 'sr25519'});496 unused = keyring.addFromUri(`//${randomSeed}`);497 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();498 } while (bal !== 0n);499 return unused;500}501502export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {503 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();504}505506export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {507 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));508}509510export async function findNotExistingCollection(api: ApiPromise): Promise<number> {511 const totalNumber = await getCreatedCollectionCount(api);512 const newCollection: number = totalNumber + 1;513 return newCollection;514}515516function getDestroyResult(events: EventRecord[]): boolean {517 let success = false;518 events.forEach(({event: {method}}) => {519 if (method == 'ExtrinsicSuccess') {520 success = true;521 }522 });523 return success;524}525526export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {527 await usingApi(async (api) => {528 // Run the DestroyCollection transaction529 const alicePrivateKey = privateKey(senderSeed);530 const tx = api.tx.unique.destroyCollection(collectionId);531 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;532 });533}534535export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {536 await usingApi(async (api) => {537 // Run the DestroyCollection transaction538 const alicePrivateKey = privateKey(senderSeed);539 const tx = api.tx.unique.destroyCollection(collectionId);540 const events = await submitTransactionAsync(alicePrivateKey, tx);541 const result = getDestroyResult(events);542 expect(result).to.be.true;543544 // What to expect545 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;546 });547}548549export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {550 await usingApi(async (api) => {551 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);552 const events = await submitTransactionAsync(sender, tx);553 const result = getGenericResult(events);554555 expect(result.success).to.be.true;556 });557}558559export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {560 await usingApi(async (api) => {561 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);562 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;563 const result = getGenericResult(events);564565 expect(result.success).to.be.false;566 });567}568569export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {570 await usingApi(async (api) => {571572 // Run the transaction573 const senderPrivateKey = privateKey(sender);574 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);575 const events = await submitTransactionAsync(senderPrivateKey, tx);576 const result = getGenericResult(events);577578 // Get the collection579 const collection = await queryCollectionExpectSuccess(api, collectionId);580581 // What to expect582 expect(result.success).to.be.true;583 expect(collection.sponsorship.toJSON()).to.deep.equal({584 unconfirmed: sponsor,585 });586 });587}588589export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {590 await usingApi(async (api) => {591592 // Run the transaction593 const alicePrivateKey = privateKey(sender);594 const tx = api.tx.unique.removeCollectionSponsor(collectionId);595 const events = await submitTransactionAsync(alicePrivateKey, tx);596 const result = getGenericResult(events);597598 // Get the collection599 const collection = await queryCollectionExpectSuccess(api, collectionId);600601 // What to expect602 expect(result.success).to.be.true;603 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});604 });605}606607export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {608 await usingApi(async (api) => {609610 // Run the transaction611 const alicePrivateKey = privateKey(senderSeed);612 const tx = api.tx.unique.removeCollectionSponsor(collectionId);613 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;614 });615}616617export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {618 await usingApi(async (api) => {619620 // Run the transaction621 const alicePrivateKey = privateKey(senderSeed);622 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);623 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;624 });625}626627export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {628 await usingApi(async (api) => {629630 // Run the transaction631 const sender = privateKey(senderSeed);632 const tx = api.tx.unique.confirmSponsorship(collectionId);633 const events = await submitTransactionAsync(sender, tx);634 const result = getGenericResult(events);635636 // Get the collection637 const collection = await queryCollectionExpectSuccess(api, collectionId);638639 // What to expect640 expect(result.success).to.be.true;641 expect(collection.sponsorship.toJSON()).to.be.deep.equal({642 confirmed: sender.address,643 });644 });645}646647648export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {649 await usingApi(async (api) => {650651 // Run the transaction652 const sender = privateKey(senderSeed);653 const tx = api.tx.unique.confirmSponsorship(collectionId);654 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;655 });656}657658export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {659660 await usingApi(async (api) => {661 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);662 const events = await submitTransactionAsync(sender, tx);663 const result = getGenericResult(events);664665 expect(result.success).to.be.true;666 });667}668669export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {670671 await usingApi(async (api) => {672 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);673 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;674 const result = getGenericResult(events);675676 expect(result.success).to.be.false;677 });678}679680export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {681 await usingApi(async (api) => {682 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);683 const events = await submitTransactionAsync(sender, tx);684 const result = getGenericResult(events);685686 expect(result.success).to.be.true;687 });688}689690export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {691 await usingApi(async (api) => {692 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);693 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;694 const result = getGenericResult(events);695696 expect(result.success).to.be.false;697 });698}699700export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {701702 await usingApi(async (api) => {703704 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);705 const events = await submitTransactionAsync(sender, tx);706 const result = getGenericResult(events);707708 expect(result.success).to.be.true;709 });710}711712export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {713714 await usingApi(async (api) => {715716 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);717 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;718 const result = getGenericResult(events);719720 expect(result.success).to.be.false;721 });722}723724export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {725 await usingApi(async (api) => {726 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);727 const events = await submitTransactionAsync(sender, tx);728 const result = getGenericResult(events);729730 expect(result.success).to.be.true;731 });732}733734export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {735 await usingApi(async (api) => {736 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);737 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;738 const result = getGenericResult(events);739740 expect(result.success).to.be.false;741 });742}743744export async function getNextSponsored(745 api: ApiPromise,746 collectionId: number,747 account: string | CrossAccountId,748 tokenId: number,749): Promise<number> {750 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));751}752753export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {754 await usingApi(async (api) => {755 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);756 const events = await submitTransactionAsync(sender, tx);757 const result = getGenericResult(events);758759 expect(result.success).to.be.true;760 });761}762763export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {764 let allowlisted = false;765 await usingApi(async (api) => {766 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;767 });768 return allowlisted;769}770771export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {772 await usingApi(async (api) => {773 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());774 const events = await submitTransactionAsync(sender, tx);775 const result = getGenericResult(events);776777 expect(result.success).to.be.true;778 });779}780781export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {782 await usingApi(async (api) => {783 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());784 const events = await submitTransactionAsync(sender, tx);785 const result = getGenericResult(events);786787 expect(result.success).to.be.true;788 });789}790791export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {792 await usingApi(async (api) => {793 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());794 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;795 const result = getGenericResult(events);796797 expect(result.success).to.be.false;798 });799}800801export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {802 await usingApi(async (api) => {803 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));804 const events = await submitTransactionAsync(sender, tx);805 const result = getGenericResult(events);806807 expect(result.success).to.be.true;808 });809}810811export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {812 await usingApi(async (api) => {813 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));814 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;815 });816}817818export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {819 await usingApi(async (api) => {820 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));821 const events = await submitTransactionAsync(sender, tx);822 const result = getGenericResult(events);823824 expect(result.success).to.be.true;825 });826}827828export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {829 await usingApi(async (api) => {830 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));831 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;832 });833}834835export interface CreateFungibleData {836 readonly Value: bigint;837}838839export interface CreateReFungibleData { }840export interface CreateNftData { }841842export type CreateItemData = {843 NFT: CreateNftData;844} | {845 Fungible: CreateFungibleData;846} | {847 ReFungible: CreateReFungibleData;848};849850export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {851 await usingApi(async (api) => {852 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);853 // if burning token by admin - use adminButnItemExpectSuccess854 expect(balanceBefore >= BigInt(value)).to.be.true;855856 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);857 const events = await submitTransactionAsync(sender, tx);858 const result = getGenericResult(events);859 expect(result.success).to.be.true;860861 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);862 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);863 });864}865866export async function867approveExpectSuccess(868 collectionId: number,869 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,870) {871 await usingApi(async (api: ApiPromise) => {872 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);873 const events = await submitTransactionAsync(owner, approveUniqueTx);874 const result = getGenericResult(events);875 expect(result.success).to.be.true;876877 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));878 });879}880881export async function adminApproveFromExpectSuccess(882 collectionId: number,883 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,884) {885 await usingApi(async (api: ApiPromise) => {886 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);887 const events = await submitTransactionAsync(admin, approveUniqueTx);888 const result = getGenericResult(events);889 expect(result.success).to.be.true;890891 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));892 });893}894895export async function896transferFromExpectSuccess(897 collectionId: number,898 tokenId: number,899 accountApproved: IKeyringPair,900 accountFrom: IKeyringPair | CrossAccountId,901 accountTo: IKeyringPair | CrossAccountId,902 value: number | bigint = 1,903 type = 'NFT',904) {905 await usingApi(async (api: ApiPromise) => {906 const from = normalizeAccountId(accountFrom);907 const to = normalizeAccountId(accountTo);908 let balanceBefore = 0n;909 if (type === 'Fungible') {910 balanceBefore = await getBalance(api, collectionId, to, tokenId);911 }912 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);913 const events = await submitTransactionAsync(accountApproved, transferFromTx);914 const result = getCreateItemResult(events);915 // tslint:disable-next-line:no-unused-expression916 expect(result.success).to.be.true;917 if (type === 'NFT') {918 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);919 }920 if (type === 'Fungible') {921 const balanceAfter = await getBalance(api, collectionId, to, tokenId);922 if (JSON.stringify(to) !== JSON.stringify(from)) {923 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));924 } else {925 expect(balanceAfter).to.be.equal(balanceBefore);926 }927 }928 if (type === 'ReFungible') {929 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));930 }931 });932}933934export async function935transferFromExpectFail(936 collectionId: number,937 tokenId: number,938 accountApproved: IKeyringPair,939 accountFrom: IKeyringPair,940 accountTo: IKeyringPair,941 value: number | bigint = 1,942) {943 await usingApi(async (api: ApiPromise) => {944 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);945 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;946 const result = getCreateCollectionResult(events);947 // tslint:disable-next-line:no-unused-expression948 expect(result.success).to.be.false;949 });950}951952/* eslint no-async-promise-executor: "off" */953async function getBlockNumber(api: ApiPromise): Promise<number> {954 return new Promise<number>(async (resolve) => {955 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {956 unsubscribe();957 resolve(head.number.toNumber());958 });959 });960}961962export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {963 await usingApi(async (api) => {964 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));965 const events = await submitTransactionAsync(sender, changeAdminTx);966 const result = getCreateCollectionResult(events);967 expect(result.success).to.be.true;968 });969}970971export async function972getFreeBalance(account: IKeyringPair): Promise<bigint> {973 let balance = 0n;974 await usingApi(async (api) => {975 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());976 });977978 return balance;979}980981export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {982 const tx = api.tx.balances.transfer(target, amount);983 const events = await submitTransactionAsync(source, tx);984 const result = getGenericResult(events);985 expect(result.success).to.be.true;986}987988export async function989scheduleTransferExpectSuccess(990 collectionId: number,991 tokenId: number,992 sender: IKeyringPair,993 recipient: IKeyringPair,994 value: number | bigint = 1,995 blockSchedule: number,996) {997 await usingApi(async (api: ApiPromise) => {998 const blockNumber: number | undefined = await getBlockNumber(api);999 const expectedBlockNumber = blockNumber + blockSchedule;10001001 expect(blockNumber).to.be.greaterThan(0);1002 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);1003 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);10041005 await submitTransactionAsync(sender, scheduleTx);10061007 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10081009 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));10101011 // sleep for 4 blocks1012 await waitNewBlocks(blockSchedule + 1);10131014 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10151016 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1017 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1018 });1019}102010211022export async function1023transferExpectSuccess(1024 collectionId: number,1025 tokenId: number,1026 sender: IKeyringPair,1027 recipient: IKeyringPair | CrossAccountId,1028 value: number | bigint = 1,1029 type = 'NFT',1030) {1031 await usingApi(async (api: ApiPromise) => {1032 const from = normalizeAccountId(sender);1033 const to = normalizeAccountId(recipient);10341035 let balanceBefore = 0n;1036 if (type === 'Fungible') {1037 balanceBefore = await getBalance(api, collectionId, to, tokenId);1038 }1039 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1040 const events = await submitTransactionAsync(sender, transferTx);1041 const result = getTransferResult(events);1042 // tslint:disable-next-line:no-unused-expression1043 expect(result.success).to.be.true;1044 expect(result.collectionId).to.be.equal(collectionId);1045 expect(result.itemId).to.be.equal(tokenId);1046 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1047 expect(result.recipient).to.be.deep.equal(to);1048 expect(result.value).to.be.equal(BigInt(value));1049 if (type === 'NFT') {1050 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1051 }1052 if (type === 'Fungible') {1053 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1054 if (JSON.stringify(to) !== JSON.stringify(from)) {1055 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1056 } else {1057 expect(balanceAfter).to.be.equal(balanceBefore);1058 }1059 }1060 if (type === 'ReFungible') {1061 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1062 }1063 });1064}10651066export async function1067transferExpectFailure(1068 collectionId: number,1069 tokenId: number,1070 sender: IKeyringPair,1071 recipient: IKeyringPair | CrossAccountId,1072 value: number | bigint = 1,1073) {1074 await usingApi(async (api: ApiPromise) => {1075 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1076 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1077 const result = getGenericResult(events);1078 // if (events && Array.isArray(events)) {1079 // const result = getCreateCollectionResult(events);1080 // tslint:disable-next-line:no-unused-expression1081 expect(result.success).to.be.false;1082 //}1083 });1084}10851086export async function1087approveExpectFail(1088 collectionId: number,1089 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1090) {1091 await usingApi(async (api: ApiPromise) => {1092 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1093 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1094 const result = getCreateCollectionResult(events);1095 // tslint:disable-next-line:no-unused-expression1096 expect(result.success).to.be.false;1097 });1098}10991100export async function getBalance(1101 api: ApiPromise,1102 collectionId: number,1103 owner: string | CrossAccountId,1104 token: number,1105): Promise<bigint> {1106 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1107}1108export async function getTokenOwner(1109 api: ApiPromise,1110 collectionId: number,1111 token: number,1112): Promise<CrossAccountId> {1113 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1114 if (owner == null) throw new Error('owner == null');1115 return normalizeAccountId(owner);1116}1117export async function getTopmostTokenOwner(1118 api: ApiPromise,1119 collectionId: number,1120 token: number,1121): Promise<CrossAccountId> {1122 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1123 if (owner == null) throw new Error('owner == null');1124 return normalizeAccountId(owner);1125}1126export async function isTokenExists(1127 api: ApiPromise,1128 collectionId: number,1129 token: number,1130): Promise<boolean> {1131 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1132}1133export async function getLastTokenId(1134 api: ApiPromise,1135 collectionId: number,1136): Promise<number> {1137 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1138}1139export async function getAdminList(1140 api: ApiPromise,1141 collectionId: number,1142): Promise<string[]> {1143 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1144}1145export async function getVariableMetadata(1146 api: ApiPromise,1147 collectionId: number,1148 tokenId: number,1149): Promise<number[]> {1150 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1151}1152export async function getConstMetadata(1153 api: ApiPromise,1154 collectionId: number,1155 tokenId: number,1156): Promise<number[]> {1157 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1158}11591160export async function createFungibleItemExpectSuccess(1161 sender: IKeyringPair,1162 collectionId: number,1163 data: CreateFungibleData,1164 owner: CrossAccountId | string = sender.address,1165) {1166 return await usingApi(async (api) => {1167 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11681169 const events = await submitTransactionAsync(sender, tx);1170 const result = getCreateItemResult(events);11711172 expect(result.success).to.be.true;1173 return result.itemId;1174 });1175}11761177export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1178 let newItemId = 0;1179 await usingApi(async (api) => {1180 const to = normalizeAccountId(owner);1181 const itemCountBefore = await getLastTokenId(api, collectionId);1182 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11831184 let tx;1185 if (createMode === 'Fungible') {1186 const createData = {fungible: {value: 10}};1187 tx = api.tx.unique.createItem(collectionId, to, createData as any);1188 } else if (createMode === 'ReFungible') {1189 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1190 tx = api.tx.unique.createItem(collectionId, to, createData as any);1191 } else {1192 const createData = {nft: {const_data: [], variable_data: []}};1193 tx = api.tx.unique.createItem(collectionId, to, createData as any);1194 }11951196 const events = await submitTransactionAsync(sender, tx);1197 const result = getCreateItemResult(events);11981199 const itemCountAfter = await getLastTokenId(api, collectionId);1200 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12011202 // What to expect1203 // tslint:disable-next-line:no-unused-expression1204 expect(result.success).to.be.true;1205 if (createMode === 'Fungible') {1206 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1207 } else {1208 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1209 }1210 expect(collectionId).to.be.equal(result.collectionId);1211 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1212 expect(to).to.be.deep.equal(result.recipient);1213 newItemId = result.itemId;1214 });1215 return newItemId;1216}12171218export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1219 await usingApi(async (api) => {1220 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12211222 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1223 const result = getCreateItemResult(events);12241225 expect(result.success).to.be.false;1226 });1227}12281229export async function setPublicAccessModeExpectSuccess(1230 sender: IKeyringPair, collectionId: number,1231 accessMode: 'Normal' | 'AllowList',1232) {1233 await usingApi(async (api) => {12341235 // Run the transaction1236 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1237 const events = await submitTransactionAsync(sender, tx);1238 const result = getGenericResult(events);12391240 // Get the collection1241 const collection = await queryCollectionExpectSuccess(api, collectionId);12421243 // What to expect1244 // tslint:disable-next-line:no-unused-expression1245 expect(result.success).to.be.true;1246 expect(collection.access.toHuman()).to.be.equal(accessMode);1247 });1248}12491250export async function setPublicAccessModeExpectFail(1251 sender: IKeyringPair, collectionId: number,1252 accessMode: 'Normal' | 'AllowList',1253) {1254 await usingApi(async (api) => {12551256 // Run the transaction1257 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1258 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1259 const result = getGenericResult(events);12601261 // What to expect1262 // tslint:disable-next-line:no-unused-expression1263 expect(result.success).to.be.false;1264 });1265}12661267export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1268 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1269}12701271export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1272 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1273}12741275export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1276 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1277}12781279export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1280 await usingApi(async (api) => {12811282 // Run the transaction1283 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1284 const events = await submitTransactionAsync(sender, tx);1285 const result = getGenericResult(events);1286 expect(result.success).to.be.true;12871288 // Get the collection1289 const collection = await queryCollectionExpectSuccess(api, collectionId);12901291 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1292 });1293}12941295export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1296 await setMintPermissionExpectSuccess(sender, collectionId, true);1297}12981299export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1300 await usingApi(async (api) => {1301 // Run the transaction1302 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1303 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1304 const result = getCreateCollectionResult(events);1305 // tslint:disable-next-line:no-unused-expression1306 expect(result.success).to.be.false;1307 });1308}13091310export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1311 await usingApi(async (api) => {1312 // Run the transaction1313 const tx = api.tx.unique.setChainLimits(limits);1314 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1315 const result = getCreateCollectionResult(events);1316 // tslint:disable-next-line:no-unused-expression1317 expect(result.success).to.be.false;1318 });1319}13201321export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1322 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1323}13241325export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1326 await usingApi(async (api) => {1327 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13281329 // Run the transaction1330 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1331 const events = await submitTransactionAsync(sender, tx);1332 const result = getGenericResult(events);1333 expect(result.success).to.be.true;13341335 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1336 });1337}13381339export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1340 await usingApi(async (api) => {13411342 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13431344 // Run the transaction1345 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1346 const events = await submitTransactionAsync(sender, tx);1347 const result = getGenericResult(events);1348 expect(result.success).to.be.true;13491350 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1351 });1352}13531354export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1355 await usingApi(async (api) => {13561357 // Run the transaction1358 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1359 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1360 const result = getGenericResult(events);13611362 // What to expect1363 // tslint:disable-next-line:no-unused-expression1364 expect(result.success).to.be.false;1365 });1366}13671368export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1369 await usingApi(async (api) => {1370 // Run the transaction1371 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1372 const events = await submitTransactionAsync(sender, tx);1373 const result = getGenericResult(events);13741375 // What to expect1376 // tslint:disable-next-line:no-unused-expression1377 expect(result.success).to.be.true;1378 });1379}13801381export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1382 await usingApi(async (api) => {1383 // Run the transaction1384 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1385 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1386 const result = getGenericResult(events);13871388 // What to expect1389 // tslint:disable-next-line:no-unused-expression1390 expect(result.success).to.be.false;1391 });1392}13931394export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1395 : Promise<UpDataStructsRpcCollection | null> => {1396 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1397};13981399export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1400 // set global object - collectionsCount1401 return (await api.rpc.unique.collectionStats()).created.toNumber();1402};14031404export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1405 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1406}14071408export async function waitNewBlocks(blocksCount = 1): Promise<void> {1409 await usingApi(async (api) => {1410 const promise = new Promise<void>(async (resolve) => {1411 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1412 if (blocksCount > 0) {1413 blocksCount--;1414 } else {1415 unsubscribe();1416 resolve();1417 }1418 });1419 });1420 return promise;1421 });1422}