difftreelog
feat(rpc) token children
in: master
9 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -21,7 +21,7 @@
use jsonrpc_derive::rpc;
use up_data_structs::{
RpcCollection, CollectionId, CollectionStats, CollectionLimits, TokenId, Property,
- PropertyKeyPermission, TokenData,
+ PropertyKeyPermission, TokenData, TokenChild,
};
use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};
use sp_blockchain::HeaderBackend;
@@ -72,6 +72,13 @@
token: TokenId,
at: Option<BlockHash>,
) -> Result<Option<CrossAccountId>>;
+ #[rpc(name = "unique_tokenChildren")]
+ fn token_children(
+ &self,
+ collection: CollectionId,
+ token: TokenId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<TokenChild>>;
#[rpc(name = "unique_collectionProperties")]
fn collection_properties(
@@ -411,6 +418,7 @@
pass_method!(
topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api
);
+ pass_method!(token_children(collection: CollectionId, token: TokenId) -> Vec<TokenChild>, unique_api);
pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);
pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);
pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string(), unique_api);
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -40,6 +40,7 @@
MAX_TOKEN_PREFIX_LENGTH,
COLLECTION_ADMINS_LIMIT,
TokenId,
+ TokenChild,
CollectionStats,
MAX_TOKEN_OWNERSHIP,
CollectionMode,
@@ -502,6 +503,7 @@
CollectionStats,
CollectionId,
TokenId,
+ TokenChild,
PhantomType<(
TokenData<T::CrossAccountId>,
RpcCollection<T::AccountId>,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -22,7 +22,7 @@
use up_data_structs::{
AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,
- PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,
+ PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty, TokenChild,
};
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_common::{
@@ -988,6 +988,15 @@
.is_some()
}
+ pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {
+ <TokenChildren<T>>::iter_prefix((collection_id, token_id))
+ .map(|((child_collection_id, child_id), _)| TokenChild {
+ collection: child_collection_id,
+ token: child_id,
+ })
+ .collect()
+ }
+
/// Delegated to `create_multiple_items`
pub fn create_item(
collection: &NonfungibleHandle<T>,
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -585,6 +585,14 @@
#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+// todo possibly rename to be used generally as an address pair
+pub struct TokenChild {
+ pub token: TokenId,
+ pub collection: CollectionId,
+}
+
+#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct CollectionStats {
pub created: u32,
pub destroyed: u32,
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -18,7 +18,7 @@
use up_data_structs::{
CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits, Property,
- PropertyKeyPermission, TokenData,
+ PropertyKeyPermission, TokenData, TokenChild,
};
use sp_std::vec::Vec;
use codec::Decode;
@@ -41,6 +41,7 @@
fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
+ fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>>;
fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -29,7 +29,9 @@
Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))
}
-
+ fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {
+ Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))
+ }
fn collection_properties(
collection: CollectionId,
keys: Option<Vec<Vec<u8>>>
tests/src/interfaces/unique/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -50,6 +50,7 @@
allowance: fun('Get allowed amount', [collectionParam, crossAccountParam('sender'), crossAccountParam('spender'), tokenParam], 'u128'),
tokenOwner: fun('Get token owner', [collectionParam, tokenParam], `Option<${CROSS_ACCOUNT_ID_TYPE}>`),
topmostTokenOwner: fun('Get token owner, in case of nested token - find parent recursive', [collectionParam, tokenParam], `Option<${CROSS_ACCOUNT_ID_TYPE}>`),
+ tokenChildren: fun('Get tokens nested directly into the token', [collectionParam, tokenParam], 'Vec<UpDataStructsTokenChild>'),
constMetadata: fun('Get token constant metadata', [collectionParam, tokenParam], 'Vec<u8>'),
variableMetadata: fun('Get token variable metadata', [collectionParam, tokenParam], 'Vec<u8>'),
collectionProperties: fun(
tests/src/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -8,6 +8,7 @@
createItemExpectSuccess,
enableAllowListExpectSuccess,
enablePublicMintingExpectSuccess,
+ getTokenChildren,
getTokenOwner,
getTopmostTokenOwner,
normalizeAccountId,
@@ -89,6 +90,63 @@
});
});
+ it('Checks token children', async () => {
+ await usingApi(async api => {
+ const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: 'Owner'});
+ const collectionB = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+
+ const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT');
+ const targetAddress = {Ethereum: tokenIdToAddress(collectionA, targetToken)};
+ let children = await getTokenChildren(api, collectionA, targetToken);
+ expect(children.length).to.be.equal(0, 'Children length check at creation');
+
+ // Create a nested NFT token
+ const tokenA = await createItemExpectSuccess(alice, collectionA, 'NFT', targetAddress);
+ children = await getTokenChildren(api, collectionA, targetToken);
+ expect(children.length).to.be.equal(1, 'Children length check at nesting #1');
+ expect(children).to.have.deep.members([
+ {token: tokenA, collection: collectionA},
+ ], 'Children contents check at nesting #1');
+
+ // Create then nest
+ const tokenB = await createItemExpectSuccess(alice, collectionA, 'NFT');
+ await transferExpectSuccess(collectionA, tokenB, alice, targetAddress);
+ children = await getTokenChildren(api, collectionA, targetToken);
+ expect(children.length).to.be.equal(2, 'Children length check at nesting #2');
+ expect(children).to.have.deep.members([
+ {token: tokenA, collection: collectionA},
+ {token: tokenB, collection: collectionA},
+ ], 'Children contents check at nesting #2');
+
+ // Move token B to a different user outside the nesting tree
+ await transferFromExpectSuccess(collectionA, tokenB, alice, targetAddress, bob);
+ children = await getTokenChildren(api, collectionA, targetToken);
+ expect(children.length).to.be.equal(1, 'Children length check at unnesting');
+ expect(children).to.be.have.deep.members([
+ {token: tokenA, collection: collectionA},
+ ], 'Children contents check at unnesting');
+
+ // Create a fungible token in another collection and then nest
+ const tokenC = await createItemExpectSuccess(alice, collectionB, 'Fungible');
+ await transferExpectSuccess(collectionB, tokenC, alice, targetAddress, 1, 'Fungible');
+ children = await getTokenChildren(api, collectionA, targetToken);
+ expect(children.length).to.be.equal(2, 'Children length check at nesting #3 (from another collection)');
+ expect(children).to.be.have.deep.members([
+ {token: tokenA, collection: collectionA},
+ {token: tokenC, collection: collectionB},
+ ], 'Children contents check at nesting #3 (from another collection)');
+
+ // Move the fungible token inside token A deeper in the nesting tree
+ await transferFromExpectSuccess(collectionB, tokenC, alice, targetAddress, {Ethereum: tokenIdToAddress(collectionA, tokenA)}, 1, 'Fungible');
+ children = await getTokenChildren(api, collectionA, targetToken);
+ expect(children.length).to.be.equal(1, 'Children length check at deeper nesting');
+ expect(children).to.be.have.deep.members([
+ {token: tokenA, collection: collectionA},
+ ], 'Children contents check at deeper nesting');
+ });
+ });
+
// ---------- Non-Fungible ----------
it('NFT: allows an Owner to nest/unnest their token', async () => {
@@ -232,6 +290,20 @@
});
});
+ // TODO delete if this is actually wrong
+ // TODO remake all other nesting tests if this is right
+ it('Affirms that transfer is disallowed to transfer nested tokens', async () => {
+ await usingApi(async () => {
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: 'Owner'});
+
+ const tokenA = await createItemExpectSuccess(alice, collection, 'NFT');
+ const tokenB = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, tokenA)});
+
+ await transferExpectFailure(collection, tokenB, alice, bob);
+ });
+ });
+
it('Disallows excessive token nesting', async () => {
await usingApi(async api => {
const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
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, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, 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, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} 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 collectionId: number;109 itemId: number;110 sender?: CrossAccountId;111 recipient?: CrossAccountId;112 value: bigint;113}114115interface IReFungibleOwner {116 fraction: BN;117 owner: number[];118}119120interface IGetMessage {121 checkMsgUnqMethod: string;122 checkMsgTrsMethod: string;123 checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127 value: number;128}129130export interface IChainLimits {131 collectionNumbersLimit: number;132 accountTokenOwnershipLimit: number;133 collectionsAdminsLimit: number;134 customDataLimit: number;135 nftSponsorTransferTimeout: number;136 fungibleSponsorTransferTimeout: number;137 refungibleSponsorTransferTimeout: number;138 //offchainSchemaLimit: number;139 //constOnChainSchemaLimit: number;140}141142export interface IReFungibleTokenDataType {143 owner: IReFungibleOwner[];144}145146export function uniqueEventMessage(events: EventRecord[]): IGetMessage {147 let checkMsgUnqMethod = '';148 let checkMsgTrsMethod = '';149 let checkMsgSysMethod = '';150 events.forEach(({event: {method, section}}) => {151 if (section === 'common') {152 checkMsgUnqMethod = method;153 } else if (section === 'treasury') {154 checkMsgTrsMethod = method;155 } else if (section === 'system') {156 checkMsgSysMethod = method;157 } else { return null; }158 });159 const result: IGetMessage = {160 checkMsgUnqMethod,161 checkMsgTrsMethod,162 checkMsgSysMethod,163 };164 return result;165}166167export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {168 const event = events.find(r => check(r.event));169 if (!event) return;170 return event.event as T;171}172173export function getGenericResult(events: EventRecord[]): GenericResult {174 const result: GenericResult = {175 success: false,176 };177 events.forEach(({event: {method}}) => {178 // console.log(` ${phase}: ${section}.${method}:: ${data}`);179 if (method === 'ExtrinsicSuccess') {180 result.success = true;181 }182 });183 return result;184}185186187188export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {189 let success = false;190 let collectionId = 0;191 events.forEach(({event: {data, method, section}}) => {192 // console.log(` ${phase}: ${section}.${method}:: ${data}`);193 if (method == 'ExtrinsicSuccess') {194 success = true;195 } else if ((section == 'common') && (method == 'CollectionCreated')) {196 collectionId = parseInt(data[0].toString(), 10);197 }198 });199 const result: CreateCollectionResult = {200 success,201 collectionId,202 };203 return result;204}205206export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {207 let success = false;208 let collectionId = 0;209 let itemId = 0;210 let recipient;211212 const results : CreateItemResult[] = [];213214 events.forEach(({event: {data, method, section}}) => {215 // console.log(` ${phase}: ${section}.${method}:: ${data}`);216 if (method == 'ExtrinsicSuccess') {217 success = true;218 } else if ((section == 'common') && (method == 'ItemCreated')) {219 collectionId = parseInt(data[0].toString(), 10);220 itemId = parseInt(data[1].toString(), 10);221 recipient = normalizeAccountId(data[2].toJSON() as any);222223 const itemRes: CreateItemResult = {224 success,225 collectionId,226 itemId,227 recipient,228 };229230 results.push(itemRes);231 }232 });233234 return results;235}236237export function getCreateItemResult(events: EventRecord[]): CreateItemResult {238 let success = false;239 let collectionId = 0;240 let itemId = 0;241 let recipient;242 events.forEach(({event: {data, method, section}}) => {243 // console.log(` ${phase}: ${section}.${method}:: ${data}`);244 if (method == 'ExtrinsicSuccess') {245 success = true;246 } else if ((section == 'common') && (method == 'ItemCreated')) {247 collectionId = parseInt(data[0].toString(), 10);248 itemId = parseInt(data[1].toString(), 10);249 recipient = normalizeAccountId(data[2].toJSON() as any);250 }251 });252 const result: CreateItemResult = {253 success,254 collectionId,255 itemId,256 recipient,257 };258 return result;259}260261export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {262 for (const {event} of events) {263 if (api.events.common.Transfer.is(event)) {264 const [collection, token, sender, recipient, value] = event.data;265 return {266 collectionId: collection.toNumber(),267 itemId: token.toNumber(),268 sender: normalizeAccountId(sender.toJSON() as any),269 recipient: normalizeAccountId(recipient.toJSON() as any),270 value: value.toBigInt(),271 };272 }273 }274 throw new Error('no transfer event');275}276277interface Nft {278 type: 'NFT';279}280281interface Fungible {282 type: 'Fungible';283 decimalPoints: number;284}285286interface ReFungible {287 type: 'ReFungible';288}289290type CollectionMode = Nft | Fungible | ReFungible;291292export type Property = {293 key: any,294 value: any,295};296297type Permission = {298 mutable: boolean;299 collectionAdmin: boolean;300 tokenOwner: boolean;301}302303type PropertyPermission = {304 key: any;305 permission: Permission;306}307308export type CreateCollectionParams = {309 mode: CollectionMode,310 name: string,311 description: string,312 tokenPrefix: string,313 properties?: Array<Property>,314 propPerm?: Array<PropertyPermission>315};316317const defaultCreateCollectionParams: CreateCollectionParams = {318 description: 'description',319 mode: {type: 'NFT'},320 name: 'name',321 tokenPrefix: 'prefix',322};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};326327 let collectionId = 0;328 await usingApi(async (api) => {329 // Get number of collections before the transaction330 const collectionCountBefore = await getCreatedCollectionCount(api);331332 // Run the CreateCollection transaction333 const alicePrivateKey = privateKey('//Alice');334335 let modeprm = {};336 if (mode.type === 'NFT') {337 modeprm = {nft: null};338 } else if (mode.type === 'Fungible') {339 modeprm = {fungible: mode.decimalPoints};340 } else if (mode.type === 'ReFungible') {341 modeprm = {refungible: null};342 }343344 const tx = api.tx.unique.createCollectionEx({345 name: strToUTF16(name),346 description: strToUTF16(description),347 tokenPrefix: strToUTF16(tokenPrefix),348 mode: modeprm as any,349 });350 const events = await submitTransactionAsync(alicePrivateKey, tx);351 const result = getCreateCollectionResult(events);352353 // Get number of collections after the transaction354 const collectionCountAfter = await getCreatedCollectionCount(api);355356 // Get the collection357 const collection = await queryCollectionExpectSuccess(api, result.collectionId);358359 // What to expect360 // tslint:disable-next-line:no-unused-expression361 expect(result.success).to.be.true;362 expect(result.collectionId).to.be.equal(collectionCountAfter);363 // tslint:disable-next-line:no-unused-expression364 expect(collection).to.be.not.null;365 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');366 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));367 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);368 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);369 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);370371 collectionId = result.collectionId;372 });373374 return collectionId;375}376377export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {378 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};379380 let collectionId = 0;381 await usingApi(async (api) => {382 // Get number of collections before the transaction383 const collectionCountBefore = await getCreatedCollectionCount(api);384385 // Run the CreateCollection transaction386 const alicePrivateKey = privateKey('//Alice');387388 let modeprm = {};389 if (mode.type === 'NFT') {390 modeprm = {nft: null};391 } else if (mode.type === 'Fungible') {392 modeprm = {fungible: mode.decimalPoints};393 } else if (mode.type === 'ReFungible') {394 modeprm = {refungible: null};395 }396397 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});398 const events = await submitTransactionAsync(alicePrivateKey, tx);399 const result = getCreateCollectionResult(events);400401 // Get number of collections after the transaction402 const collectionCountAfter = await getCreatedCollectionCount(api);403404 // Get the collection405 const collection = await queryCollectionExpectSuccess(api, result.collectionId);406407 // What to expect408 // tslint:disable-next-line:no-unused-expression409 expect(result.success).to.be.true;410 expect(result.collectionId).to.be.equal(collectionCountAfter);411 // tslint:disable-next-line:no-unused-expression412 expect(collection).to.be.not.null;413 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');414 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));415 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);416 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);417 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);418419420 collectionId = result.collectionId;421 });422423 return collectionId;424}425426export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {427 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};428429 await usingApi(async (api) => {430 // Get number of collections before the transaction431 const collectionCountBefore = await getCreatedCollectionCount(api);432433 // Run the CreateCollection transaction434 const alicePrivateKey = privateKey('//Alice');435436 let modeprm = {};437 if (mode.type === 'NFT') {438 modeprm = {nft: null};439 } else if (mode.type === 'Fungible') {440 modeprm = {fungible: mode.decimalPoints};441 } else if (mode.type === 'ReFungible') {442 modeprm = {refungible: null};443 }444445 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});446 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;447448449 // Get number of collections after the transaction450 const collectionCountAfter = await getCreatedCollectionCount(api);451452 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');453 });454}455456export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {457 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};458459 let modeprm = {};460 if (mode.type === 'NFT') {461 modeprm = {nft: null};462 } else if (mode.type === 'Fungible') {463 modeprm = {fungible: mode.decimalPoints};464 } else if (mode.type === 'ReFungible') {465 modeprm = {refungible: null};466 }467468 await usingApi(async (api) => {469 // Get number of collections before the transaction470 const collectionCountBefore = await getCreatedCollectionCount(api);471472 // Run the CreateCollection transaction473 const alicePrivateKey = privateKey('//Alice');474 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});475 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;476477 // Get number of collections after the transaction478 const collectionCountAfter = await getCreatedCollectionCount(api);479480 // What to expect481 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');482 });483}484485export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {486 let bal = 0n;487 let unused;488 do {489 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;490 const keyring = new Keyring({type: 'sr25519'});491 unused = keyring.addFromUri(`//${randomSeed}`);492 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();493 } while (bal !== 0n);494 return unused;495}496497export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {498 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();499}500501export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {502 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));503}504505export async function findNotExistingCollection(api: ApiPromise): Promise<number> {506 const totalNumber = await getCreatedCollectionCount(api);507 const newCollection: number = totalNumber + 1;508 return newCollection;509}510511function getDestroyResult(events: EventRecord[]): boolean {512 let success = false;513 events.forEach(({event: {method}}) => {514 if (method == 'ExtrinsicSuccess') {515 success = true;516 }517 });518 return success;519}520521export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {522 await usingApi(async (api) => {523 // Run the DestroyCollection transaction524 const alicePrivateKey = privateKey(senderSeed);525 const tx = api.tx.unique.destroyCollection(collectionId);526 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;527 });528}529530export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {531 await usingApi(async (api) => {532 // Run the DestroyCollection transaction533 const alicePrivateKey = privateKey(senderSeed);534 const tx = api.tx.unique.destroyCollection(collectionId);535 const events = await submitTransactionAsync(alicePrivateKey, tx);536 const result = getDestroyResult(events);537 expect(result).to.be.true;538539 // What to expect540 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;541 });542}543544export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {545 await usingApi(async (api) => {546 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);547 const events = await submitTransactionAsync(sender, tx);548 const result = getGenericResult(events);549550 expect(result.success).to.be.true;551 });552}553554export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {555 await usingApi(async(api) => {556 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);557 const events = await submitTransactionAsync(sender, tx);558 const result = getGenericResult(events);559560 expect(result.success).to.be.true;561 });562};563564export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {565 await usingApi(async (api) => {566 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);567 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;568 const result = getGenericResult(events);569570 expect(result.success).to.be.false;571 });572}573574export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {575 await usingApi(async (api) => {576577 // Run the transaction578 const senderPrivateKey = privateKey(sender);579 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);580 const events = await submitTransactionAsync(senderPrivateKey, tx);581 const result = getGenericResult(events);582583 // Get the collection584 const collection = await queryCollectionExpectSuccess(api, collectionId);585586 // What to expect587 expect(result.success).to.be.true;588 expect(collection.sponsorship.toJSON()).to.deep.equal({589 unconfirmed: sponsor,590 });591 });592}593594export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {595 await usingApi(async (api) => {596597 // Run the transaction598 const alicePrivateKey = privateKey(sender);599 const tx = api.tx.unique.removeCollectionSponsor(collectionId);600 const events = await submitTransactionAsync(alicePrivateKey, tx);601 const result = getGenericResult(events);602603 // Get the collection604 const collection = await queryCollectionExpectSuccess(api, collectionId);605606 // What to expect607 expect(result.success).to.be.true;608 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});609 });610}611612export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {613 await usingApi(async (api) => {614615 // Run the transaction616 const alicePrivateKey = privateKey(senderSeed);617 const tx = api.tx.unique.removeCollectionSponsor(collectionId);618 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;619 });620}621622export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {623 await usingApi(async (api) => {624625 // Run the transaction626 const alicePrivateKey = privateKey(senderSeed);627 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);628 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;629 });630}631632export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {633 await usingApi(async (api) => {634635 // Run the transaction636 const sender = privateKey(senderSeed);637 const tx = api.tx.unique.confirmSponsorship(collectionId);638 const events = await submitTransactionAsync(sender, tx);639 const result = getGenericResult(events);640641 // Get the collection642 const collection = await queryCollectionExpectSuccess(api, collectionId);643644 // What to expect645 expect(result.success).to.be.true;646 expect(collection.sponsorship.toJSON()).to.be.deep.equal({647 confirmed: sender.address,648 });649 });650}651652653export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {654 await usingApi(async (api) => {655656 // Run the transaction657 const sender = privateKey(senderSeed);658 const tx = api.tx.unique.confirmSponsorship(collectionId);659 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;660 });661}662663export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {664 await usingApi(async (api) => {665 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);666 const events = await submitTransactionAsync(sender, tx);667 const result = getGenericResult(events);668669 expect(result.success).to.be.true;670 });671}672673export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {674 await usingApi(async (api) => {675 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);676 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;677 const result = getGenericResult(events);678679 expect(result.success).to.be.false;680 });681}682683export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {684685 await usingApi(async (api) => {686687 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);688 const events = await submitTransactionAsync(sender, tx);689 const result = getGenericResult(events);690691 expect(result.success).to.be.true;692 });693}694695export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {696697 await usingApi(async (api) => {698699 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);700 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;701 const result = getGenericResult(events);702703 expect(result.success).to.be.false;704 });705}706707export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {708 await usingApi(async (api) => {709 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);710 const events = await submitTransactionAsync(sender, tx);711 const result = getGenericResult(events);712713 expect(result.success).to.be.true;714 });715}716717export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {718 await usingApi(async (api) => {719 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);720 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;721 const result = getGenericResult(events);722723 expect(result.success).to.be.false;724 });725}726727export async function getNextSponsored(728 api: ApiPromise,729 collectionId: number,730 account: string | CrossAccountId,731 tokenId: number,732): Promise<number> {733 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));734}735736export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {737 await usingApi(async (api) => {738 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);739 const events = await submitTransactionAsync(sender, tx);740 const result = getGenericResult(events);741742 expect(result.success).to.be.true;743 });744}745746export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {747 let allowlisted = false;748 await usingApi(async (api) => {749 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;750 });751 return allowlisted;752}753754export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {755 await usingApi(async (api) => {756 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());757 const events = await submitTransactionAsync(sender, tx);758 const result = getGenericResult(events);759760 expect(result.success).to.be.true;761 });762}763764export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {765 await usingApi(async (api) => {766 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());767 const events = await submitTransactionAsync(sender, tx);768 const result = getGenericResult(events);769770 expect(result.success).to.be.true;771 });772}773774export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {775 await usingApi(async (api) => {776 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());777 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;778 const result = getGenericResult(events);779780 expect(result.success).to.be.false;781 });782}783784export interface CreateFungibleData {785 readonly Value: bigint;786}787788export interface CreateReFungibleData { }789export interface CreateNftData { }790791export type CreateItemData = {792 NFT: CreateNftData;793} | {794 Fungible: CreateFungibleData;795} | {796 ReFungible: CreateReFungibleData;797};798799export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {800 await usingApi(async (api) => {801 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);802 // if burning token by admin - use adminButnItemExpectSuccess803 expect(balanceBefore >= BigInt(value)).to.be.true;804805 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);806 const events = await submitTransactionAsync(sender, tx);807 const result = getGenericResult(events);808 expect(result.success).to.be.true;809810 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);811 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);812 });813}814815export async function816approveExpectSuccess(817 collectionId: number,818 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,819) {820 await usingApi(async (api: ApiPromise) => {821 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);822 const events = await submitTransactionAsync(owner, approveUniqueTx);823 const result = getGenericResult(events);824 expect(result.success).to.be.true;825826 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));827 });828}829830export async function adminApproveFromExpectSuccess(831 collectionId: number,832 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,833) {834 await usingApi(async (api: ApiPromise) => {835 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);836 const events = await submitTransactionAsync(admin, approveUniqueTx);837 const result = getGenericResult(events);838 expect(result.success).to.be.true;839840 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));841 });842}843844export async function845transferFromExpectSuccess(846 collectionId: number,847 tokenId: number,848 accountApproved: IKeyringPair,849 accountFrom: IKeyringPair | CrossAccountId,850 accountTo: IKeyringPair | CrossAccountId,851 value: number | bigint = 1,852 type = 'NFT',853) {854 await usingApi(async (api: ApiPromise) => {855 const from = normalizeAccountId(accountFrom);856 const to = normalizeAccountId(accountTo);857 let balanceBefore = 0n;858 if (type === 'Fungible' || type === 'ReFungible') {859 balanceBefore = await getBalance(api, collectionId, to, tokenId);860 }861 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);862 const events = await submitTransactionAsync(accountApproved, transferFromTx);863 const result = getCreateItemResult(events);864 // tslint:disable-next-line:no-unused-expression865 expect(result.success).to.be.true;866 if (type === 'NFT') {867 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);868 }869 if (type === 'Fungible') {870 const balanceAfter = await getBalance(api, collectionId, to, tokenId);871 if (JSON.stringify(to) !== JSON.stringify(from)) {872 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));873 } else {874 expect(balanceAfter).to.be.equal(balanceBefore);875 }876 }877 if (type === 'ReFungible') {878 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));879 }880 });881}882883export async function884transferFromExpectFail(885 collectionId: number,886 tokenId: number,887 accountApproved: IKeyringPair,888 accountFrom: IKeyringPair,889 accountTo: IKeyringPair,890 value: number | bigint = 1,891) {892 await usingApi(async (api: ApiPromise) => {893 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);894 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;895 const result = getCreateCollectionResult(events);896 // tslint:disable-next-line:no-unused-expression897 expect(result.success).to.be.false;898 });899}900901/* eslint no-async-promise-executor: "off" */902async function getBlockNumber(api: ApiPromise): Promise<number> {903 return new Promise<number>(async (resolve) => {904 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {905 unsubscribe();906 resolve(head.number.toNumber());907 });908 });909}910911export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {912 await usingApi(async (api) => {913 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));914 const events = await submitTransactionAsync(sender, changeAdminTx);915 const result = getCreateCollectionResult(events);916 expect(result.success).to.be.true;917 });918}919920export async function921getFreeBalance(account: IKeyringPair): Promise<bigint> {922 let balance = 0n;923 await usingApi(async (api) => {924 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());925 });926927 return balance;928}929930export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {931 const tx = api.tx.balances.transfer(target, amount);932 const events = await submitTransactionAsync(source, tx);933 const result = getGenericResult(events);934 expect(result.success).to.be.true;935}936937export async function938scheduleTransferExpectSuccess(939 collectionId: number,940 tokenId: number,941 sender: IKeyringPair,942 recipient: IKeyringPair,943 value: number | bigint = 1,944 blockSchedule: number,945) {946 await usingApi(async (api: ApiPromise) => {947 const blockNumber: number | undefined = await getBlockNumber(api);948 const expectedBlockNumber = blockNumber + blockSchedule;949950 expect(blockNumber).to.be.greaterThan(0);951 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);952 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);953954 await submitTransactionAsync(sender, scheduleTx);955956 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();957958 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));959960 // sleep for 4 blocks961 await waitNewBlocks(blockSchedule + 1);962963 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();964965 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));966 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);967 });968}969970971export async function972transferExpectSuccess(973 collectionId: number,974 tokenId: number,975 sender: IKeyringPair,976 recipient: IKeyringPair | CrossAccountId,977 value: number | bigint = 1,978 type = 'NFT',979) {980 await usingApi(async (api: ApiPromise) => {981 const from = normalizeAccountId(sender);982 const to = normalizeAccountId(recipient);983984 let balanceBefore = 0n;985 if (type === 'Fungible') {986 balanceBefore = await getBalance(api, collectionId, to, tokenId);987 }988 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);989 const events = await executeTransaction(api, sender, transferTx);990991 const result = getTransferResult(api, events);992 expect(result.collectionId).to.be.equal(collectionId);993 expect(result.itemId).to.be.equal(tokenId);994 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));995 expect(result.recipient).to.be.deep.equal(to);996 expect(result.value).to.be.equal(BigInt(value));997998 if (type === 'NFT') {999 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1000 }1001 if (type === 'Fungible') {1002 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1003 if (JSON.stringify(to) !== JSON.stringify(from)) {1004 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1005 } else {1006 expect(balanceAfter).to.be.equal(balanceBefore);1007 }1008 }1009 if (type === 'ReFungible') {1010 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1011 }1012 });1013}10141015export async function1016transferExpectFailure(1017 collectionId: number,1018 tokenId: number,1019 sender: IKeyringPair,1020 recipient: IKeyringPair | CrossAccountId,1021 value: number | bigint = 1,1022) {1023 await usingApi(async (api: ApiPromise) => {1024 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1025 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1026 const result = getGenericResult(events);1027 // if (events && Array.isArray(events)) {1028 // const result = getCreateCollectionResult(events);1029 // tslint:disable-next-line:no-unused-expression1030 expect(result.success).to.be.false;1031 //}1032 });1033}10341035export async function1036approveExpectFail(1037 collectionId: number,1038 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1039) {1040 await usingApi(async (api: ApiPromise) => {1041 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1042 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1043 const result = getCreateCollectionResult(events);1044 // tslint:disable-next-line:no-unused-expression1045 expect(result.success).to.be.false;1046 });1047}10481049export async function getBalance(1050 api: ApiPromise,1051 collectionId: number,1052 owner: string | CrossAccountId,1053 token: number,1054): Promise<bigint> {1055 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1056}1057export async function getTokenOwner(1058 api: ApiPromise,1059 collectionId: number,1060 token: number,1061): Promise<CrossAccountId> {1062 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1063 if (owner == null) throw new Error('owner == null');1064 return normalizeAccountId(owner);1065}1066export async function getTopmostTokenOwner(1067 api: ApiPromise,1068 collectionId: number,1069 token: number,1070): Promise<CrossAccountId> {1071 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1072 if (owner == null) throw new Error('owner == null');1073 return normalizeAccountId(owner);1074}1075export async function isTokenExists(1076 api: ApiPromise,1077 collectionId: number,1078 token: number,1079): Promise<boolean> {1080 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1081}1082export async function getLastTokenId(1083 api: ApiPromise,1084 collectionId: number,1085): Promise<number> {1086 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1087}1088export async function getAdminList(1089 api: ApiPromise,1090 collectionId: number,1091): Promise<string[]> {1092 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1093}1094export async function getTokenProperties(1095 api: ApiPromise,1096 collectionId: number,1097 tokenId: number,1098 propertyKeys: string[],1099): Promise<UpDataStructsProperty[]> {1100 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1101}11021103export async function createFungibleItemExpectSuccess(1104 sender: IKeyringPair,1105 collectionId: number,1106 data: CreateFungibleData,1107 owner: CrossAccountId | string = sender.address,1108) {1109 return await usingApi(async (api) => {1110 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11111112 const events = await submitTransactionAsync(sender, tx);1113 const result = getCreateItemResult(events);11141115 expect(result.success).to.be.true;1116 return result.itemId;1117 });1118}11191120export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1121 await usingApi(async (api) => {1122 const to = normalizeAccountId(owner);1123 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);11241125 const events = await submitTransactionAsync(sender, tx);1126 const result = getCreateItemsResult(events);11271128 for (const res of result) {1129 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1130 }1131 });1132}11331134export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1135 await usingApi(async (api) => {1136 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);11371138 const events = await submitTransactionAsync(sender, tx);1139 const result = getCreateItemsResult(events);11401141 for (const res of result) {1142 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1143 }1144 });1145}11461147export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1148 let newItemId = 0;1149 await usingApi(async (api) => {1150 const to = normalizeAccountId(owner);1151 const itemCountBefore = await getLastTokenId(api, collectionId);1152 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11531154 let tx;1155 if (createMode === 'Fungible') {1156 const createData = {fungible: {value: 10}};1157 tx = api.tx.unique.createItem(collectionId, to, createData as any);1158 } else if (createMode === 'ReFungible') {1159 const createData = {refungible: {pieces: 100}};1160 tx = api.tx.unique.createItem(collectionId, to, createData as any);1161 } else {1162 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1163 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1164 }11651166 const events = await submitTransactionAsync(sender, tx);1167 const result = getCreateItemResult(events);11681169 const itemCountAfter = await getLastTokenId(api, collectionId);1170 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11711172 if (createMode === 'NFT') {1173 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1174 }11751176 // What to expect1177 // tslint:disable-next-line:no-unused-expression1178 expect(result.success).to.be.true;1179 if (createMode === 'Fungible') {1180 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1181 } else {1182 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1183 }1184 expect(collectionId).to.be.equal(result.collectionId);1185 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1186 expect(to).to.be.deep.equal(result.recipient);1187 newItemId = result.itemId;1188 });1189 return newItemId;1190}11911192export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1193 await usingApi(async (api) => {11941195 let tx;1196 if (createMode === 'NFT') {1197 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1198 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1199 } else {1200 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1201 }120212031204 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1205 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1206 const result = getCreateItemResult(events);12071208 expect(result.success).to.be.false;1209 });1210}12111212export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1213 let newItemId = 0;1214 await usingApi(async (api) => {1215 const to = normalizeAccountId(owner);1216 const itemCountBefore = await getLastTokenId(api, collectionId);1217 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12181219 let tx;1220 if (createMode === 'Fungible') {1221 const createData = {fungible: {value: 10}};1222 tx = api.tx.unique.createItem(collectionId, to, createData as any);1223 } else if (createMode === 'ReFungible') {1224 const createData = {refungible: {pieces: 100}};1225 tx = api.tx.unique.createItem(collectionId, to, createData as any);1226 } else {1227 const createData = {nft: {}};1228 tx = api.tx.unique.createItem(collectionId, to, createData as any);1229 }12301231 const events = await submitTransactionAsync(sender, tx);1232 const result = getCreateItemResult(events);12331234 const itemCountAfter = await getLastTokenId(api, collectionId);1235 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12361237 // What to expect1238 // tslint:disable-next-line:no-unused-expression1239 expect(result.success).to.be.true;1240 if (createMode === 'Fungible') {1241 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1242 } else {1243 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1244 }1245 expect(collectionId).to.be.equal(result.collectionId);1246 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1247 expect(to).to.be.deep.equal(result.recipient);1248 newItemId = result.itemId;1249 });1250 return newItemId;1251}12521253export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1254 await usingApi(async (api) => {1255 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12561257 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1258 const result = getCreateItemResult(events);12591260 expect(result.success).to.be.false;1261 });1262}12631264export async function setPublicAccessModeExpectSuccess(1265 sender: IKeyringPair, collectionId: number,1266 accessMode: 'Normal' | 'AllowList',1267) {1268 await usingApi(async (api) => {12691270 // Run the transaction1271 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1272 const events = await submitTransactionAsync(sender, tx);1273 const result = getGenericResult(events);12741275 // Get the collection1276 const collection = await queryCollectionExpectSuccess(api, collectionId);12771278 // What to expect1279 // tslint:disable-next-line:no-unused-expression1280 expect(result.success).to.be.true;1281 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1282 });1283}12841285export async function setPublicAccessModeExpectFail(1286 sender: IKeyringPair, collectionId: number,1287 accessMode: 'Normal' | 'AllowList',1288) {1289 await usingApi(async (api) => {12901291 // Run the transaction1292 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1293 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1294 const result = getGenericResult(events);12951296 // What to expect1297 // tslint:disable-next-line:no-unused-expression1298 expect(result.success).to.be.false;1299 });1300}13011302export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1303 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1304}13051306export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1307 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1308}13091310export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1311 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1312}13131314export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1315 await usingApi(async (api) => {13161317 // Run the transaction1318 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1319 const events = await submitTransactionAsync(sender, tx);1320 const result = getGenericResult(events);1321 expect(result.success).to.be.true;13221323 // Get the collection1324 const collection = await queryCollectionExpectSuccess(api, collectionId);13251326 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1327 });1328}13291330export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1331 await setMintPermissionExpectSuccess(sender, collectionId, true);1332}13331334export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1335 await usingApi(async (api) => {1336 // Run the transaction1337 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1338 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1339 const result = getCreateCollectionResult(events);1340 // tslint:disable-next-line:no-unused-expression1341 expect(result.success).to.be.false;1342 });1343}13441345export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1346 await usingApi(async (api) => {1347 // Run the transaction1348 const tx = api.tx.unique.setChainLimits(limits);1349 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1350 const result = getCreateCollectionResult(events);1351 // tslint:disable-next-line:no-unused-expression1352 expect(result.success).to.be.false;1353 });1354}13551356export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1357 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1358}13591360export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1361 await usingApi(async (api) => {1362 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13631364 // Run the transaction1365 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1366 const events = await submitTransactionAsync(sender, tx);1367 const result = getGenericResult(events);1368 expect(result.success).to.be.true;13691370 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1371 });1372}13731374export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1375 await usingApi(async (api) => {13761377 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13781379 // Run the transaction1380 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1381 const events = await submitTransactionAsync(sender, tx);1382 const result = getGenericResult(events);1383 expect(result.success).to.be.true;13841385 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1386 });1387}13881389export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1390 await usingApi(async (api) => {13911392 // Run the transaction1393 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1394 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1395 const result = getGenericResult(events);13961397 // What to expect1398 // tslint:disable-next-line:no-unused-expression1399 expect(result.success).to.be.false;1400 });1401}14021403export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1404 await usingApi(async (api) => {1405 // Run the transaction1406 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1407 const events = await submitTransactionAsync(sender, tx);1408 const result = getGenericResult(events);14091410 // What to expect1411 // tslint:disable-next-line:no-unused-expression1412 expect(result.success).to.be.true;1413 });1414}14151416export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1417 await usingApi(async (api) => {1418 // Run the transaction1419 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1420 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1421 const result = getGenericResult(events);14221423 // What to expect1424 // tslint:disable-next-line:no-unused-expression1425 expect(result.success).to.be.false;1426 });1427}14281429export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1430 : Promise<UpDataStructsRpcCollection | null> => {1431 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1432};14331434export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1435 // set global object - collectionsCount1436 return (await api.rpc.unique.collectionStats()).created.toNumber();1437};14381439export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1440 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1441}14421443export async function waitNewBlocks(blocksCount = 1): Promise<void> {1444 await usingApi(async (api) => {1445 const promise = new Promise<void>(async (resolve) => {1446 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1447 if (blocksCount > 0) {1448 blocksCount--;1449 } else {1450 unsubscribe();1451 resolve();1452 }1453 });1454 });1455 return promise;1456 });1457}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, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, 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, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37 Substrate: string,38} | {39 Ethereum: string,40};4142export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {43 if (typeof input === 'string') {44 if (input.length === 48 || input.length === 47) {45 return {Substrate: input};46 } else if (input.length === 42 && input.startsWith('0x')) {47 return {Ethereum: input.toLowerCase()};48 } else if (input.length === 40 && !input.startsWith('0x')) {49 return {Ethereum: '0x' + input.toLowerCase()};50 } else {51 throw new Error(`Unknown address format: "${input}"`);52 }53 }54 if ('address' in input) {55 return {Substrate: input.address};56 }57 if ('Ethereum' in input) {58 return {59 Ethereum: input.Ethereum.toLowerCase(),60 };61 } else if ('ethereum' in input) {62 return {63 Ethereum: (input as any).ethereum.toLowerCase(),64 };65 } else if ('Substrate' in input) {66 return input;67 } else if ('substrate' in input) {68 return {69 Substrate: (input as any).substrate,70 };71 }7273 // AccountId74 return {Substrate: input.toString()};75}76export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {77 input = normalizeAccountId(input);78 if ('Substrate' in input) {79 return input.Substrate;80 } else {81 return evmToAddress(input.Ethereum);82 }83}8485export const U128_MAX = (1n << 128n) - 1n;8687const MICROUNIQUE = 1_000_000_000_000n;88const MILLIUNIQUE = 1_000n * MICROUNIQUE;89const CENTIUNIQUE = 10n * MILLIUNIQUE;90export const UNIQUE = 100n * CENTIUNIQUE;9192type GenericResult = {93 success: boolean,94};9596interface CreateCollectionResult {97 success: boolean;98 collectionId: number;99}100101interface CreateItemResult {102 success: boolean;103 collectionId: number;104 itemId: number;105 recipient?: CrossAccountId;106}107108interface TransferResult {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 //constOnChainSchemaLimit: number;141}142143export interface IReFungibleTokenDataType {144 owner: IReFungibleOwner[];145}146147export function uniqueEventMessage(events: EventRecord[]): IGetMessage {148 let checkMsgUnqMethod = '';149 let checkMsgTrsMethod = '';150 let checkMsgSysMethod = '';151 events.forEach(({event: {method, section}}) => {152 if (section === 'common') {153 checkMsgUnqMethod = method;154 } else if (section === 'treasury') {155 checkMsgTrsMethod = method;156 } else if (section === 'system') {157 checkMsgSysMethod = method;158 } else { return null; }159 });160 const result: IGetMessage = {161 checkMsgUnqMethod,162 checkMsgTrsMethod,163 checkMsgSysMethod,164 };165 return result;166}167168export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {169 const event = events.find(r => check(r.event));170 if (!event) return;171 return event.event as T;172}173174export function getGenericResult(events: EventRecord[]): GenericResult {175 const result: GenericResult = {176 success: false,177 };178 events.forEach(({event: {method}}) => {179 // console.log(` ${phase}: ${section}.${method}:: ${data}`);180 if (method === 'ExtrinsicSuccess') {181 result.success = true;182 }183 });184 return result;185}186187188189export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {190 let success = false;191 let collectionId = 0;192 events.forEach(({event: {data, method, section}}) => {193 // console.log(` ${phase}: ${section}.${method}:: ${data}`);194 if (method == 'ExtrinsicSuccess') {195 success = true;196 } else if ((section == 'common') && (method == 'CollectionCreated')) {197 collectionId = parseInt(data[0].toString(), 10);198 }199 });200 const result: CreateCollectionResult = {201 success,202 collectionId,203 };204 return result;205}206207export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {208 let success = false;209 let collectionId = 0;210 let itemId = 0;211 let recipient;212213 const results : CreateItemResult[] = [];214215 events.forEach(({event: {data, method, section}}) => {216 // console.log(` ${phase}: ${section}.${method}:: ${data}`);217 if (method == 'ExtrinsicSuccess') {218 success = true;219 } else if ((section == 'common') && (method == 'ItemCreated')) {220 collectionId = parseInt(data[0].toString(), 10);221 itemId = parseInt(data[1].toString(), 10);222 recipient = normalizeAccountId(data[2].toJSON() as any);223224 const itemRes: CreateItemResult = {225 success,226 collectionId,227 itemId,228 recipient,229 };230231 results.push(itemRes);232 }233 });234235 return results;236}237238export function getCreateItemResult(events: EventRecord[]): CreateItemResult {239 let success = false;240 let collectionId = 0;241 let itemId = 0;242 let recipient;243 events.forEach(({event: {data, method, section}}) => {244 // console.log(` ${phase}: ${section}.${method}:: ${data}`);245 if (method == 'ExtrinsicSuccess') {246 success = true;247 } else if ((section == 'common') && (method == 'ItemCreated')) {248 collectionId = parseInt(data[0].toString(), 10);249 itemId = parseInt(data[1].toString(), 10);250 recipient = normalizeAccountId(data[2].toJSON() as any);251 }252 });253 const result: CreateItemResult = {254 success,255 collectionId,256 itemId,257 recipient,258 };259 return result;260}261262export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {263 for (const {event} of events) {264 if (api.events.common.Transfer.is(event)) {265 const [collection, token, sender, recipient, value] = event.data;266 return {267 collectionId: collection.toNumber(),268 itemId: token.toNumber(),269 sender: normalizeAccountId(sender.toJSON() as any),270 recipient: normalizeAccountId(recipient.toJSON() as any),271 value: value.toBigInt(),272 };273 }274 }275 throw new Error('no transfer event');276}277278interface Nft {279 type: 'NFT';280}281282interface Fungible {283 type: 'Fungible';284 decimalPoints: number;285}286287interface ReFungible {288 type: 'ReFungible';289}290291type CollectionMode = Nft | Fungible | ReFungible;292293export type Property = {294 key: any,295 value: any,296};297298type Permission = {299 mutable: boolean;300 collectionAdmin: boolean;301 tokenOwner: boolean;302}303304type PropertyPermission = {305 key: any;306 permission: Permission;307}308309export type CreateCollectionParams = {310 mode: CollectionMode,311 name: string,312 description: string,313 tokenPrefix: string,314 properties?: Array<Property>,315 propPerm?: Array<PropertyPermission>316};317318const defaultCreateCollectionParams: CreateCollectionParams = {319 description: 'description',320 mode: {type: 'NFT'},321 name: 'name',322 tokenPrefix: 'prefix',323};324325export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {326 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};327328 let collectionId = 0;329 await usingApi(async (api) => {330 // Get number of collections before the transaction331 const collectionCountBefore = await getCreatedCollectionCount(api);332333 // Run the CreateCollection transaction334 const alicePrivateKey = privateKey('//Alice');335336 let modeprm = {};337 if (mode.type === 'NFT') {338 modeprm = {nft: null};339 } else if (mode.type === 'Fungible') {340 modeprm = {fungible: mode.decimalPoints};341 } else if (mode.type === 'ReFungible') {342 modeprm = {refungible: null};343 }344345 const tx = api.tx.unique.createCollectionEx({346 name: strToUTF16(name),347 description: strToUTF16(description),348 tokenPrefix: strToUTF16(tokenPrefix),349 mode: modeprm as any,350 });351 const events = await submitTransactionAsync(alicePrivateKey, tx);352 const result = getCreateCollectionResult(events);353354 // Get number of collections after the transaction355 const collectionCountAfter = await getCreatedCollectionCount(api);356357 // Get the collection358 const collection = await queryCollectionExpectSuccess(api, result.collectionId);359360 // What to expect361 // tslint:disable-next-line:no-unused-expression362 expect(result.success).to.be.true;363 expect(result.collectionId).to.be.equal(collectionCountAfter);364 // tslint:disable-next-line:no-unused-expression365 expect(collection).to.be.not.null;366 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');367 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));368 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);369 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);370 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);371372 collectionId = result.collectionId;373 });374375 return collectionId;376}377378export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {379 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};380381 let collectionId = 0;382 await usingApi(async (api) => {383 // Get number of collections before the transaction384 const collectionCountBefore = await getCreatedCollectionCount(api);385386 // Run the CreateCollection transaction387 const alicePrivateKey = privateKey('//Alice');388389 let modeprm = {};390 if (mode.type === 'NFT') {391 modeprm = {nft: null};392 } else if (mode.type === 'Fungible') {393 modeprm = {fungible: mode.decimalPoints};394 } else if (mode.type === 'ReFungible') {395 modeprm = {refungible: null};396 }397398 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});399 const events = await submitTransactionAsync(alicePrivateKey, tx);400 const result = getCreateCollectionResult(events);401402 // Get number of collections after the transaction403 const collectionCountAfter = await getCreatedCollectionCount(api);404405 // Get the collection406 const collection = await queryCollectionExpectSuccess(api, result.collectionId);407408 // What to expect409 // tslint:disable-next-line:no-unused-expression410 expect(result.success).to.be.true;411 expect(result.collectionId).to.be.equal(collectionCountAfter);412 // tslint:disable-next-line:no-unused-expression413 expect(collection).to.be.not.null;414 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');415 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));416 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);417 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);418 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);419420421 collectionId = result.collectionId;422 });423424 return collectionId;425}426427export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {428 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};429430 await usingApi(async (api) => {431 // Get number of collections before the transaction432 const collectionCountBefore = await getCreatedCollectionCount(api);433434 // Run the CreateCollection transaction435 const alicePrivateKey = privateKey('//Alice');436437 let modeprm = {};438 if (mode.type === 'NFT') {439 modeprm = {nft: null};440 } else if (mode.type === 'Fungible') {441 modeprm = {fungible: mode.decimalPoints};442 } else if (mode.type === 'ReFungible') {443 modeprm = {refungible: null};444 }445446 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});447 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;448449450 // Get number of collections after the transaction451 const collectionCountAfter = await getCreatedCollectionCount(api);452453 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');454 });455}456457export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {458 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};459460 let modeprm = {};461 if (mode.type === 'NFT') {462 modeprm = {nft: null};463 } else if (mode.type === 'Fungible') {464 modeprm = {fungible: mode.decimalPoints};465 } else if (mode.type === 'ReFungible') {466 modeprm = {refungible: null};467 }468469 await usingApi(async (api) => {470 // Get number of collections before the transaction471 const collectionCountBefore = await getCreatedCollectionCount(api);472473 // Run the CreateCollection transaction474 const alicePrivateKey = privateKey('//Alice');475 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});476 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;477478 // Get number of collections after the transaction479 const collectionCountAfter = await getCreatedCollectionCount(api);480481 // What to expect482 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');483 });484}485486export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {487 let bal = 0n;488 let unused;489 do {490 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;491 const keyring = new Keyring({type: 'sr25519'});492 unused = keyring.addFromUri(`//${randomSeed}`);493 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();494 } while (bal !== 0n);495 return unused;496}497498export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {499 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();500}501502export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {503 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));504}505506export async function findNotExistingCollection(api: ApiPromise): Promise<number> {507 const totalNumber = await getCreatedCollectionCount(api);508 const newCollection: number = totalNumber + 1;509 return newCollection;510}511512function getDestroyResult(events: EventRecord[]): boolean {513 let success = false;514 events.forEach(({event: {method}}) => {515 if (method == 'ExtrinsicSuccess') {516 success = true;517 }518 });519 return success;520}521522export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {523 await usingApi(async (api) => {524 // Run the DestroyCollection transaction525 const alicePrivateKey = privateKey(senderSeed);526 const tx = api.tx.unique.destroyCollection(collectionId);527 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;528 });529}530531export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {532 await usingApi(async (api) => {533 // Run the DestroyCollection transaction534 const alicePrivateKey = privateKey(senderSeed);535 const tx = api.tx.unique.destroyCollection(collectionId);536 const events = await submitTransactionAsync(alicePrivateKey, tx);537 const result = getDestroyResult(events);538 expect(result).to.be.true;539540 // What to expect541 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;542 });543}544545export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {546 await usingApi(async (api) => {547 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);548 const events = await submitTransactionAsync(sender, tx);549 const result = getGenericResult(events);550551 expect(result.success).to.be.true;552 });553}554555export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {556 await usingApi(async(api) => {557 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);558 const events = await submitTransactionAsync(sender, tx);559 const result = getGenericResult(events);560561 expect(result.success).to.be.true;562 });563};564565export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {566 await usingApi(async (api) => {567 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);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 setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {576 await usingApi(async (api) => {577578 // Run the transaction579 const senderPrivateKey = privateKey(sender);580 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);581 const events = await submitTransactionAsync(senderPrivateKey, tx);582 const result = getGenericResult(events);583584 // Get the collection585 const collection = await queryCollectionExpectSuccess(api, collectionId);586587 // What to expect588 expect(result.success).to.be.true;589 expect(collection.sponsorship.toJSON()).to.deep.equal({590 unconfirmed: sponsor,591 });592 });593}594595export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {596 await usingApi(async (api) => {597598 // Run the transaction599 const alicePrivateKey = privateKey(sender);600 const tx = api.tx.unique.removeCollectionSponsor(collectionId);601 const events = await submitTransactionAsync(alicePrivateKey, tx);602 const result = getGenericResult(events);603604 // Get the collection605 const collection = await queryCollectionExpectSuccess(api, collectionId);606607 // What to expect608 expect(result.success).to.be.true;609 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});610 });611}612613export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {614 await usingApi(async (api) => {615616 // Run the transaction617 const alicePrivateKey = privateKey(senderSeed);618 const tx = api.tx.unique.removeCollectionSponsor(collectionId);619 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;620 });621}622623export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {624 await usingApi(async (api) => {625626 // Run the transaction627 const alicePrivateKey = privateKey(senderSeed);628 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);629 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;630 });631}632633export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {634 await usingApi(async (api) => {635636 // Run the transaction637 const sender = privateKey(senderSeed);638 const tx = api.tx.unique.confirmSponsorship(collectionId);639 const events = await submitTransactionAsync(sender, tx);640 const result = getGenericResult(events);641642 // Get the collection643 const collection = await queryCollectionExpectSuccess(api, collectionId);644645 // What to expect646 expect(result.success).to.be.true;647 expect(collection.sponsorship.toJSON()).to.be.deep.equal({648 confirmed: sender.address,649 });650 });651}652653654export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {655 await usingApi(async (api) => {656657 // Run the transaction658 const sender = privateKey(senderSeed);659 const tx = api.tx.unique.confirmSponsorship(collectionId);660 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;661 });662}663664export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {665 await usingApi(async (api) => {666 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);667 const events = await submitTransactionAsync(sender, tx);668 const result = getGenericResult(events);669670 expect(result.success).to.be.true;671 });672}673674export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {675 await usingApi(async (api) => {676 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);677 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;678 const result = getGenericResult(events);679680 expect(result.success).to.be.false;681 });682}683684export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {685686 await usingApi(async (api) => {687688 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);689 const events = await submitTransactionAsync(sender, tx);690 const result = getGenericResult(events);691692 expect(result.success).to.be.true;693 });694}695696export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {697698 await usingApi(async (api) => {699700 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);701 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;702 const result = getGenericResult(events);703704 expect(result.success).to.be.false;705 });706}707708export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {709 await usingApi(async (api) => {710 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);711 const events = await submitTransactionAsync(sender, tx);712 const result = getGenericResult(events);713714 expect(result.success).to.be.true;715 });716}717718export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {719 await usingApi(async (api) => {720 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);721 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;722 const result = getGenericResult(events);723724 expect(result.success).to.be.false;725 });726}727728export async function getNextSponsored(729 api: ApiPromise,730 collectionId: number,731 account: string | CrossAccountId,732 tokenId: number,733): Promise<number> {734 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));735}736737export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {738 await usingApi(async (api) => {739 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);740 const events = await submitTransactionAsync(sender, tx);741 const result = getGenericResult(events);742743 expect(result.success).to.be.true;744 });745}746747export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {748 let allowlisted = false;749 await usingApi(async (api) => {750 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;751 });752 return allowlisted;753}754755export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {756 await usingApi(async (api) => {757 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());758 const events = await submitTransactionAsync(sender, tx);759 const result = getGenericResult(events);760761 expect(result.success).to.be.true;762 });763}764765export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {766 await usingApi(async (api) => {767 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());768 const events = await submitTransactionAsync(sender, tx);769 const result = getGenericResult(events);770771 expect(result.success).to.be.true;772 });773}774775export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {776 await usingApi(async (api) => {777 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());778 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;779 const result = getGenericResult(events);780781 expect(result.success).to.be.false;782 });783}784785export interface CreateFungibleData {786 readonly Value: bigint;787}788789export interface CreateReFungibleData { }790export interface CreateNftData { }791792export type CreateItemData = {793 NFT: CreateNftData;794} | {795 Fungible: CreateFungibleData;796} | {797 ReFungible: CreateReFungibleData;798};799800export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {801 await usingApi(async (api) => {802 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);803 // if burning token by admin - use adminButnItemExpectSuccess804 expect(balanceBefore >= BigInt(value)).to.be.true;805806 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);807 const events = await submitTransactionAsync(sender, tx);808 const result = getGenericResult(events);809 expect(result.success).to.be.true;810811 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);812 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);813 });814}815816export async function817approveExpectSuccess(818 collectionId: number,819 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,820) {821 await usingApi(async (api: ApiPromise) => {822 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);823 const events = await submitTransactionAsync(owner, approveUniqueTx);824 const result = getGenericResult(events);825 expect(result.success).to.be.true;826827 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));828 });829}830831export async function adminApproveFromExpectSuccess(832 collectionId: number,833 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,834) {835 await usingApi(async (api: ApiPromise) => {836 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);837 const events = await submitTransactionAsync(admin, approveUniqueTx);838 const result = getGenericResult(events);839 expect(result.success).to.be.true;840841 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));842 });843}844845export async function846transferFromExpectSuccess(847 collectionId: number,848 tokenId: number,849 accountApproved: IKeyringPair,850 accountFrom: IKeyringPair | CrossAccountId,851 accountTo: IKeyringPair | CrossAccountId,852 value: number | bigint = 1,853 type = 'NFT',854) {855 await usingApi(async (api: ApiPromise) => {856 const from = normalizeAccountId(accountFrom);857 const to = normalizeAccountId(accountTo);858 let balanceBefore = 0n;859 if (type === 'Fungible' || type === 'ReFungible') {860 balanceBefore = await getBalance(api, collectionId, to, tokenId);861 }862 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);863 const events = await submitTransactionAsync(accountApproved, transferFromTx);864 const result = getCreateItemResult(events);865 // tslint:disable-next-line:no-unused-expression866 expect(result.success).to.be.true;867 if (type === 'NFT') {868 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);869 }870 if (type === 'Fungible') {871 const balanceAfter = await getBalance(api, collectionId, to, tokenId);872 if (JSON.stringify(to) !== JSON.stringify(from)) {873 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));874 } else {875 expect(balanceAfter).to.be.equal(balanceBefore);876 }877 }878 if (type === 'ReFungible') {879 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));880 }881 });882}883884export async function885transferFromExpectFail(886 collectionId: number,887 tokenId: number,888 accountApproved: IKeyringPair,889 accountFrom: IKeyringPair,890 accountTo: IKeyringPair,891 value: number | bigint = 1,892) {893 await usingApi(async (api: ApiPromise) => {894 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);895 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;896 const result = getCreateCollectionResult(events);897 // tslint:disable-next-line:no-unused-expression898 expect(result.success).to.be.false;899 });900}901902/* eslint no-async-promise-executor: "off" */903async function getBlockNumber(api: ApiPromise): Promise<number> {904 return new Promise<number>(async (resolve) => {905 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {906 unsubscribe();907 resolve(head.number.toNumber());908 });909 });910}911912export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {913 await usingApi(async (api) => {914 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));915 const events = await submitTransactionAsync(sender, changeAdminTx);916 const result = getCreateCollectionResult(events);917 expect(result.success).to.be.true;918 });919}920921export async function922getFreeBalance(account: IKeyringPair): Promise<bigint> {923 let balance = 0n;924 await usingApi(async (api) => {925 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());926 });927928 return balance;929}930931export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {932 const tx = api.tx.balances.transfer(target, amount);933 const events = await submitTransactionAsync(source, tx);934 const result = getGenericResult(events);935 expect(result.success).to.be.true;936}937938export async function939scheduleTransferExpectSuccess(940 collectionId: number,941 tokenId: number,942 sender: IKeyringPair,943 recipient: IKeyringPair,944 value: number | bigint = 1,945 blockSchedule: number,946) {947 await usingApi(async (api: ApiPromise) => {948 const blockNumber: number | undefined = await getBlockNumber(api);949 const expectedBlockNumber = blockNumber + blockSchedule;950951 expect(blockNumber).to.be.greaterThan(0);952 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);953 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);954955 await submitTransactionAsync(sender, scheduleTx);956957 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();958959 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));960961 // sleep for 4 blocks962 await waitNewBlocks(blockSchedule + 1);963964 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();965966 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));967 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);968 });969}970971972export async function973transferExpectSuccess(974 collectionId: number,975 tokenId: number,976 sender: IKeyringPair,977 recipient: IKeyringPair | CrossAccountId,978 value: number | bigint = 1,979 type = 'NFT',980) {981 await usingApi(async (api: ApiPromise) => {982 const from = normalizeAccountId(sender);983 const to = normalizeAccountId(recipient);984985 let balanceBefore = 0n;986 if (type === 'Fungible') {987 balanceBefore = await getBalance(api, collectionId, to, tokenId);988 }989 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);990 const events = await executeTransaction(api, sender, transferTx);991992 const result = getTransferResult(api, events);993 expect(result.collectionId).to.be.equal(collectionId);994 expect(result.itemId).to.be.equal(tokenId);995 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));996 expect(result.recipient).to.be.deep.equal(to);997 expect(result.value).to.be.equal(BigInt(value));998999 if (type === 'NFT') {1000 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1001 }1002 if (type === 'Fungible') {1003 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1004 if (JSON.stringify(to) !== JSON.stringify(from)) {1005 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1006 } else {1007 expect(balanceAfter).to.be.equal(balanceBefore);1008 }1009 }1010 if (type === 'ReFungible') {1011 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1012 }1013 });1014}10151016export async function1017transferExpectFailure(1018 collectionId: number,1019 tokenId: number,1020 sender: IKeyringPair,1021 recipient: IKeyringPair | CrossAccountId,1022 value: number | bigint = 1,1023) {1024 await usingApi(async (api: ApiPromise) => {1025 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1026 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1027 const result = getGenericResult(events);1028 // if (events && Array.isArray(events)) {1029 // const result = getCreateCollectionResult(events);1030 // tslint:disable-next-line:no-unused-expression1031 expect(result.success).to.be.false;1032 //}1033 });1034}10351036export async function1037approveExpectFail(1038 collectionId: number,1039 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1040) {1041 await usingApi(async (api: ApiPromise) => {1042 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1043 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1044 const result = getCreateCollectionResult(events);1045 // tslint:disable-next-line:no-unused-expression1046 expect(result.success).to.be.false;1047 });1048}10491050export async function getBalance(1051 api: ApiPromise,1052 collectionId: number,1053 owner: string | CrossAccountId,1054 token: number,1055): Promise<bigint> {1056 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1057}1058export async function getTokenOwner(1059 api: ApiPromise,1060 collectionId: number,1061 token: number,1062): Promise<CrossAccountId> {1063 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1064 if (owner == null) throw new Error('owner == null');1065 return normalizeAccountId(owner);1066}1067export async function getTopmostTokenOwner(1068 api: ApiPromise,1069 collectionId: number,1070 token: number,1071): Promise<CrossAccountId> {1072 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1073 if (owner == null) throw new Error('owner == null');1074 return normalizeAccountId(owner);1075}1076export async function getTokenChildren(1077 api: ApiPromise,1078 collectionId: number,1079 tokenId: number,1080): Promise<UpDataStructsTokenChild[]> {1081 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1082}1083export async function isTokenExists(1084 api: ApiPromise,1085 collectionId: number,1086 token: number,1087): Promise<boolean> {1088 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1089}1090export async function getLastTokenId(1091 api: ApiPromise,1092 collectionId: number,1093): Promise<number> {1094 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1095}1096export async function getAdminList(1097 api: ApiPromise,1098 collectionId: number,1099): Promise<string[]> {1100 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1101}1102export async function getTokenProperties(1103 api: ApiPromise,1104 collectionId: number,1105 tokenId: number,1106 propertyKeys: string[],1107): Promise<UpDataStructsProperty[]> {1108 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1109}11101111export async function createFungibleItemExpectSuccess(1112 sender: IKeyringPair,1113 collectionId: number,1114 data: CreateFungibleData,1115 owner: CrossAccountId | string = sender.address,1116) {1117 return await usingApi(async (api) => {1118 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11191120 const events = await submitTransactionAsync(sender, tx);1121 const result = getCreateItemResult(events);11221123 expect(result.success).to.be.true;1124 return result.itemId;1125 });1126}11271128export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1129 await usingApi(async (api) => {1130 const to = normalizeAccountId(owner);1131 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);11321133 const events = await submitTransactionAsync(sender, tx);1134 const result = getCreateItemsResult(events);11351136 for (const res of result) {1137 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1138 }1139 });1140}11411142export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1143 await usingApi(async (api) => {1144 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);11451146 const events = await submitTransactionAsync(sender, tx);1147 const result = getCreateItemsResult(events);11481149 for (const res of result) {1150 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1151 }1152 });1153}11541155export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1156 let newItemId = 0;1157 await usingApi(async (api) => {1158 const to = normalizeAccountId(owner);1159 const itemCountBefore = await getLastTokenId(api, collectionId);1160 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11611162 let tx;1163 if (createMode === 'Fungible') {1164 const createData = {fungible: {value: 10}};1165 tx = api.tx.unique.createItem(collectionId, to, createData as any);1166 } else if (createMode === 'ReFungible') {1167 const createData = {refungible: {pieces: 100}};1168 tx = api.tx.unique.createItem(collectionId, to, createData as any);1169 } else {1170 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1171 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1172 }11731174 const events = await submitTransactionAsync(sender, tx);1175 const result = getCreateItemResult(events);11761177 const itemCountAfter = await getLastTokenId(api, collectionId);1178 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11791180 if (createMode === 'NFT') {1181 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1182 }11831184 // What to expect1185 // tslint:disable-next-line:no-unused-expression1186 expect(result.success).to.be.true;1187 if (createMode === 'Fungible') {1188 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1189 } else {1190 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1191 }1192 expect(collectionId).to.be.equal(result.collectionId);1193 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1194 expect(to).to.be.deep.equal(result.recipient);1195 newItemId = result.itemId;1196 });1197 return newItemId;1198}11991200export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1201 await usingApi(async (api) => {12021203 let tx;1204 if (createMode === 'NFT') {1205 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1206 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1207 } else {1208 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1209 }121012111212 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1213 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1214 const result = getCreateItemResult(events);12151216 expect(result.success).to.be.false;1217 });1218}12191220export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1221 let newItemId = 0;1222 await usingApi(async (api) => {1223 const to = normalizeAccountId(owner);1224 const itemCountBefore = await getLastTokenId(api, collectionId);1225 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12261227 let tx;1228 if (createMode === 'Fungible') {1229 const createData = {fungible: {value: 10}};1230 tx = api.tx.unique.createItem(collectionId, to, createData as any);1231 } else if (createMode === 'ReFungible') {1232 const createData = {refungible: {pieces: 100}};1233 tx = api.tx.unique.createItem(collectionId, to, createData as any);1234 } else {1235 const createData = {nft: {}};1236 tx = api.tx.unique.createItem(collectionId, to, createData as any);1237 }12381239 const events = await submitTransactionAsync(sender, tx);1240 const result = getCreateItemResult(events);12411242 const itemCountAfter = await getLastTokenId(api, collectionId);1243 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12441245 // What to expect1246 // tslint:disable-next-line:no-unused-expression1247 expect(result.success).to.be.true;1248 if (createMode === 'Fungible') {1249 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1250 } else {1251 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1252 }1253 expect(collectionId).to.be.equal(result.collectionId);1254 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1255 expect(to).to.be.deep.equal(result.recipient);1256 newItemId = result.itemId;1257 });1258 return newItemId;1259}12601261export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1262 await usingApi(async (api) => {1263 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12641265 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1266 const result = getCreateItemResult(events);12671268 expect(result.success).to.be.false;1269 });1270}12711272export async function setPublicAccessModeExpectSuccess(1273 sender: IKeyringPair, collectionId: number,1274 accessMode: 'Normal' | 'AllowList',1275) {1276 await usingApi(async (api) => {12771278 // Run the transaction1279 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1280 const events = await submitTransactionAsync(sender, tx);1281 const result = getGenericResult(events);12821283 // Get the collection1284 const collection = await queryCollectionExpectSuccess(api, collectionId);12851286 // What to expect1287 // tslint:disable-next-line:no-unused-expression1288 expect(result.success).to.be.true;1289 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1290 });1291}12921293export async function setPublicAccessModeExpectFail(1294 sender: IKeyringPair, collectionId: number,1295 accessMode: 'Normal' | 'AllowList',1296) {1297 await usingApi(async (api) => {12981299 // Run the transaction1300 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1301 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1302 const result = getGenericResult(events);13031304 // What to expect1305 // tslint:disable-next-line:no-unused-expression1306 expect(result.success).to.be.false;1307 });1308}13091310export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1311 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1312}13131314export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1315 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1316}13171318export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1319 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1320}13211322export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1323 await usingApi(async (api) => {13241325 // Run the transaction1326 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1327 const events = await submitTransactionAsync(sender, tx);1328 const result = getGenericResult(events);1329 expect(result.success).to.be.true;13301331 // Get the collection1332 const collection = await queryCollectionExpectSuccess(api, collectionId);13331334 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1335 });1336}13371338export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1339 await setMintPermissionExpectSuccess(sender, collectionId, true);1340}13411342export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1343 await usingApi(async (api) => {1344 // Run the transaction1345 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1346 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1347 const result = getCreateCollectionResult(events);1348 // tslint:disable-next-line:no-unused-expression1349 expect(result.success).to.be.false;1350 });1351}13521353export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1354 await usingApi(async (api) => {1355 // Run the transaction1356 const tx = api.tx.unique.setChainLimits(limits);1357 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1358 const result = getCreateCollectionResult(events);1359 // tslint:disable-next-line:no-unused-expression1360 expect(result.success).to.be.false;1361 });1362}13631364export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1365 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1366}13671368export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1369 await usingApi(async (api) => {1370 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13711372 // Run the transaction1373 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1374 const events = await submitTransactionAsync(sender, tx);1375 const result = getGenericResult(events);1376 expect(result.success).to.be.true;13771378 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1379 });1380}13811382export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1383 await usingApi(async (api) => {13841385 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13861387 // Run the transaction1388 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1389 const events = await submitTransactionAsync(sender, tx);1390 const result = getGenericResult(events);1391 expect(result.success).to.be.true;13921393 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1394 });1395}13961397export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1398 await usingApi(async (api) => {13991400 // Run the transaction1401 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1402 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1403 const result = getGenericResult(events);14041405 // What to expect1406 // tslint:disable-next-line:no-unused-expression1407 expect(result.success).to.be.false;1408 });1409}14101411export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1412 await usingApi(async (api) => {1413 // Run the transaction1414 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1415 const events = await submitTransactionAsync(sender, tx);1416 const result = getGenericResult(events);14171418 // What to expect1419 // tslint:disable-next-line:no-unused-expression1420 expect(result.success).to.be.true;1421 });1422}14231424export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1425 await usingApi(async (api) => {1426 // Run the transaction1427 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1428 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1429 const result = getGenericResult(events);14301431 // What to expect1432 // tslint:disable-next-line:no-unused-expression1433 expect(result.success).to.be.false;1434 });1435}14361437export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1438 : Promise<UpDataStructsRpcCollection | null> => {1439 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1440};14411442export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1443 // set global object - collectionsCount1444 return (await api.rpc.unique.collectionStats()).created.toNumber();1445};14461447export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1448 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1449}14501451export async function waitNewBlocks(blocksCount = 1): Promise<void> {1452 await usingApi(async (api) => {1453 const promise = new Promise<void>(async (resolve) => {1454 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1455 if (blocksCount > 0) {1456 blocksCount--;1457 } else {1458 unsubscribe();1459 resolve();1460 }1461 });1462 });1463 return promise;1464 });1465}