difftreelog
feat Add `collection_admins` method to eth collection.
in: master
19 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -580,7 +580,7 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
fn collection_owner(&self) -> Result<(address, uint256)> {
Ok(convert_cross_account_to_tuple::<T>(
@@ -616,13 +616,16 @@
// .map_err(dispatch_to_evm::<T>)
// }
- // TODO: need implement AbiWriter for &Vec<T>
- // fn collection_admins(&self) -> Result<Vec<(address, uint256)>> {
- // let result = pallet_common::IsAdmin::<T>::iter_prefix((self.id,))
- // .map(|(admin, _)| pallet_common::eth::convert_cross_account_to_tuple::<T>(&admin))
- // .collect();
- // Ok(result)
- // }
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ fn collection_admins(&self) -> Result<Vec<(address, uint256)>> {
+ let result = crate::IsAdmin::<T>::iter_prefix((self.id,))
+ .map(|(admin, _)| crate::eth::convert_cross_account_to_tuple::<T>(&admin))
+ .collect();
+ Ok(result)
+ }
}
/// ### Note
pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -18,7 +18,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0x3af103fb
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -282,7 +282,7 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
@@ -303,6 +303,18 @@
newOwner;
dummy = 0;
}
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0x5813216b,
+ /// or in textual repr: collectionAdmins()
+ function collectionAdmins() public view returns (Tuple6[] memory) {
+ require(false, stub_error);
+ dummy;
+ return new Tuple6[](0);
+ }
}
/// @dev the ERC-165 identifier for this interface is 0x63034ac5
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -91,7 +91,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0x3af103fb
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -355,7 +355,7 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
@@ -376,6 +376,18 @@
newOwner;
dummy = 0;
}
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0x5813216b,
+ /// or in textual repr: collectionAdmins()
+ function collectionAdmins() public view returns (Tuple17[] memory) {
+ require(false, stub_error);
+ dummy;
+ return new Tuple17[](0);
+ }
}
/// @dev anonymous struct
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -91,7 +91,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0x3af103fb
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -355,7 +355,7 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
@@ -376,6 +376,18 @@
newOwner;
dummy = 0;
}
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0x5813216b,
+ /// or in textual repr: collectionAdmins()
+ function collectionAdmins() public view returns (Tuple17[] memory) {
+ require(false, stub_error);
+ dummy;
+ return new Tuple17[](0);
+ }
}
/// @dev anonymous struct
pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -13,7 +13,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0x3af103fb
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -184,7 +184,7 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
@@ -197,6 +197,14 @@
/// @dev EVM selector for this function is: 0x4f53e226,
/// or in textual repr: changeCollectionOwner(address)
function changeCollectionOwner(address newOwner) external;
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0x5813216b,
+ /// or in textual repr: collectionAdmins()
+ function collectionAdmins() external view returns (Tuple6[] memory);
}
/// @dev the ERC-165 identifier for this interface is 0x63034ac5
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -62,7 +62,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0x3af103fb
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -233,7 +233,7 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
@@ -246,6 +246,14 @@
/// @dev EVM selector for this function is: 0x4f53e226,
/// or in textual repr: changeCollectionOwner(address)
function changeCollectionOwner(address newOwner) external;
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0x5813216b,
+ /// or in textual repr: collectionAdmins()
+ function collectionAdmins() external view returns (Tuple17[] memory);
}
/// @dev anonymous struct
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -62,7 +62,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0x3af103fb
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -233,7 +233,7 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
@@ -246,6 +246,14 @@
/// @dev EVM selector for this function is: 0x4f53e226,
/// or in textual repr: changeCollectionOwner(address)
function changeCollectionOwner(address newOwner) external;
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0x5813216b,
+ /// or in textual repr: collectionAdmins()
+ function collectionAdmins() external view returns (Tuple17[] memory);
}
/// @dev anonymous struct
tests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -14,6 +14,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
+import {IEthCrossAccountId} from '../util/playgrounds/types';
import {usingEthPlaygrounds, itEth, expect, EthUniqueHelper} from './util';
async function recordEthFee(helper: EthUniqueHelper, userAddress: string, call: () => Promise<any>) {
@@ -68,11 +69,31 @@
const newAdmin = helper.eth.createAccount();
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
expect(await collectionEvm.methods.isOwnerOrAdmin(newAdmin).call()).to.be.false;
await collectionEvm.methods.addCollectionAdmin(newAdmin).send();
expect(await collectionEvm.methods.isOwnerOrAdmin(newAdmin).call()).to.be.true;
});
+
+ itEth.skip('Check adminlist', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ const admin1 = helper.eth.createAccount();
+ const [admin2] = await helper.arrange.createAccounts([10n], donor);
+ await collectionEvm.methods.addCollectionAdmin(admin1).send();
+ await collectionEvm.methods.addCollectionAdminSubstrate(admin2.addressRaw).send();
+ const adminListRpc = await helper.collection.getAdmins(collectionId);
+ let adminListEth = await collectionEvm.methods.collectionAdmins().call();
+ adminListEth = adminListEth.map((element: IEthCrossAccountId) => {
+ return helper.address.convertCrossAccountFromEthCrossAcoount(element);
+ });
+ expect(adminListRpc).to.be.like(adminListEth);
+ });
+
itEth('(!negative tests!) Add admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
tests/src/eth/fungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -126,6 +126,23 @@
},
{
"inputs": [],
+ "name": "collectionAdmins",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "collectionOwner",
"outputs": [
{
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -156,6 +156,23 @@
},
{
"inputs": [],
+ "name": "collectionAdmins",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple17[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "collectionOwner",
"outputs": [
{
tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -156,6 +156,23 @@
},
{
"inputs": [],
+ "name": "collectionAdmins",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple17[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "collectionOwner",
"outputs": [
{
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -70,6 +70,13 @@
ethereum?: TEthereumAccount;
}
+export interface IEthCrossAccountId {
+ 0: TEthereumAccount;
+ 1: TSubstrateAccount;
+ field_0: TEthereumAccount;
+ field_1: TSubstrateAccount;
+}
+
export interface ICollectionLimits {
accountTokenOwnershipLimit?: number | null;
sponsoredDataSize?: number | null;
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 // If ith character is 8 to f then make it uppercase84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255256 static bigIntToDecimals(number: bigint, decimals = 18) {257 const numberStr = number.toString();258 const dotPos = numberStr.length - decimals;259 260 if (dotPos <= 0) {261 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;262 } else {263 const intPart = numberStr.substring(0, dotPos);264 const fractPart = numberStr.substring(dotPos);265 return intPart + '.' + fractPart;266 }267 }268}269270class UniqueEventHelper {271 private static extractIndex(index: any): [number, number] | string {272 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];273 return index.toJSON();274 }275276 private static extractSub(data: any, subTypes: any): {[key: string]: any} {277 let obj: any = {};278 let index = 0;279280 if (data.entries) {281 for(const [key, value] of data.entries()) {282 obj[key] = this.extractData(value, subTypes[index]);283 index++;284 }285 } else obj = data.toJSON();286287 return obj;288 }289 290 private static extractData(data: any, type: any): any {291 if(!type) return data.toHuman();292 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();293 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();294 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);295 return data.toHuman();296 }297298 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {299 const parsedEvents: IEvent[] = [];300301 events.forEach((record) => {302 const {event, phase} = record;303 const types = event.typeDef;304305 const eventData: IEvent = {306 section: event.section.toString(),307 method: event.method.toString(),308 index: this.extractIndex(event.index),309 data: [],310 phase: phase.toJSON(),311 };312313 event.data.forEach((val: any, index: number) => {314 eventData.data.push(this.extractData(val, types[index]));315 });316317 parsedEvents.push(eventData);318 });319320 return parsedEvents;321 }322}323324export class ChainHelperBase {325 helperBase: any;326327 transactionStatus = UniqueUtil.transactionStatus;328 chainLogType = UniqueUtil.chainLogType;329 util: typeof UniqueUtil;330 eventHelper: typeof UniqueEventHelper;331 logger: ILogger;332 api: ApiPromise | null;333 forcedNetwork: TNetworks | null;334 network: TNetworks | null;335 chainLog: IUniqueHelperLog[];336 children: ChainHelperBase[];337 address: AddressGroup;338 chain: ChainGroup;339340 constructor(logger?: ILogger, helperBase?: any) {341 this.helperBase = helperBase;342343 this.util = UniqueUtil;344 this.eventHelper = UniqueEventHelper;345 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();346 this.logger = logger;347 this.api = null;348 this.forcedNetwork = null;349 this.network = null;350 this.chainLog = [];351 this.children = [];352 this.address = new AddressGroup(this);353 this.chain = new ChainGroup(this);354 }355356 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {357 Object.setPrototypeOf(helperCls.prototype, this);358 const newHelper = new helperCls(this.logger, options);359360 newHelper.api = this.api;361 newHelper.network = this.network;362 newHelper.forceNetwork = this.forceNetwork;363364 this.children.push(newHelper);365366 return newHelper;367 }368369 getApi(): ApiPromise {370 if(this.api === null) throw Error('API not initialized');371 return this.api;372 }373374 clearChainLog(): void {375 this.chainLog = [];376 }377378 forceNetwork(value: TNetworks): void {379 this.forcedNetwork = value;380 }381382 async connect(wsEndpoint: string, listeners?: IApiListeners) {383 if (this.api !== null) throw Error('Already connected');384 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);385 this.api = api;386 this.network = network;387 }388389 async disconnect() {390 for (const child of this.children) {391 child.clearApi();392 }393394 if (this.api === null) return;395 await this.api.disconnect();396 this.clearApi();397 }398399 clearApi() {400 this.api = null;401 this.network = null;402 }403404 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {405 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;406 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];407408 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;409410 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;411 return 'opal';412 }413414 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {415 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});416 await api.isReady;417418 const network = await this.detectNetwork(api);419420 await api.disconnect();421422 return network;423 }424425 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{426 api: ApiPromise;427 network: TNetworks;428 }> {429 if(typeof network === 'undefined' || network === null) network = 'opal';430 const supportedRPC = {431 opal: {432 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,433 },434 quartz: {435 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,436 },437 unique: {438 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,439 },440 rococo: {},441 westend: {},442 moonbeam: {},443 moonriver: {},444 acala: {},445 karura: {},446 westmint: {},447 };448 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);449 const rpc = supportedRPC[network];450451 // TODO: investigate how to replace rpc in runtime452 // api._rpcCore.addUserInterfaces(rpc);453454 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});455456 await api.isReadyOrError;457458 if (typeof listeners === 'undefined') listeners = {};459 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {460 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;461 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);462 }463464 return {api, network};465 }466467 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {468 const {events, status} = data;469 if (status.isReady) {470 return this.transactionStatus.NOT_READY;471 }472 if (status.isBroadcast) {473 return this.transactionStatus.NOT_READY;474 }475 if (status.isInBlock || status.isFinalized) {476 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');477 if (errors.length > 0) {478 return this.transactionStatus.FAIL;479 }480 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {481 return this.transactionStatus.SUCCESS;482 }483 }484485 return this.transactionStatus.FAIL;486 }487488 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {489 const sign = (callback: any) => {490 if(options !== null) return transaction.signAndSend(sender, options, callback);491 return transaction.signAndSend(sender, callback);492 };493 // eslint-disable-next-line no-async-promise-executor494 return new Promise(async (resolve, reject) => {495 try {496 const unsub = await sign((result: any) => {497 const status = this.getTransactionStatus(result);498499 if (status === this.transactionStatus.SUCCESS) {500 this.logger.log(`${label} successful`);501 unsub();502 resolve({result, status});503 } else if (status === this.transactionStatus.FAIL) {504 let moduleError = null;505506 if (result.hasOwnProperty('dispatchError')) {507 const dispatchError = result['dispatchError'];508509 if (dispatchError) {510 if (dispatchError.isModule) {511 const modErr = dispatchError.asModule;512 const errorMeta = dispatchError.registry.findMetaError(modErr);513514 moduleError = `${errorMeta.section}.${errorMeta.name}`;515 } else {516 moduleError = dispatchError.toHuman();517 }518 } else {519 this.logger.log(result, this.logger.level.ERROR);520 }521 }522523 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);524 unsub();525 reject({status, moduleError, result});526 }527 });528 } catch (e) {529 this.logger.log(e, this.logger.level.ERROR);530 reject(e);531 }532 });533 }534535 constructApiCall(apiCall: string, params: any[]) {536 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);537 let call = this.getApi() as any;538 for(const part of apiCall.slice(4).split('.')) {539 call = call[part];540 }541 return call(...params);542 }543544 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {545 if(this.api === null) throw Error('API not initialized');546 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);547548 const startTime = (new Date()).getTime();549 let result: ITransactionResult;550 let events: IEvent[] = [];551 try {552 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;553 events = this.eventHelper.extractEvents(result.result.events);554 }555 catch(e) {556 if(!(e as object).hasOwnProperty('status')) throw e;557 result = e as ITransactionResult;558 }559560 const endTime = (new Date()).getTime();561562 const log = {563 executedAt: endTime,564 executionTime: endTime - startTime,565 type: this.chainLogType.EXTRINSIC,566 status: result.status,567 call: extrinsic,568 signer: this.getSignerAddress(sender),569 params,570 } as IUniqueHelperLog;571572 if(result.status !== this.transactionStatus.SUCCESS) {573 if (result.moduleError) log.moduleError = result.moduleError;574 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;575 }576 if(events.length > 0) log.events = events;577578 this.chainLog.push(log);579580 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {581 if (result.moduleError) throw Error(`${result.moduleError}`);582 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));583 }584 return result;585 }586587 async callRpc(rpc: string, params?: any[]) {588 if(typeof params === 'undefined') params = [];589 if(this.api === null) throw Error('API not initialized');590 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);591592 const startTime = (new Date()).getTime();593 let result;594 let error = null;595 const log = {596 type: this.chainLogType.RPC,597 call: rpc,598 params,599 } as IUniqueHelperLog;600601 try {602 result = await this.constructApiCall(rpc, params);603 }604 catch(e) {605 error = e;606 }607608 const endTime = (new Date()).getTime();609610 log.executedAt = endTime;611 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';612 log.executionTime = endTime - startTime;613614 this.chainLog.push(log);615616 if(error !== null) throw error;617618 return result;619 }620621 getSignerAddress(signer: IKeyringPair | string): string {622 if(typeof signer === 'string') return signer;623 return signer.address;624 }625626 fetchAllPalletNames(): string[] {627 if(this.api === null) throw Error('API not initialized');628 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());629 }630631 fetchMissingPalletNames(requiredPallets: string[]): string[] {632 const palletNames = this.fetchAllPalletNames();633 return requiredPallets.filter(p => !palletNames.includes(p));634 }635}636637638class HelperGroup<T extends ChainHelperBase> {639 helper: T;640641 constructor(uniqueHelper: T) {642 this.helper = uniqueHelper;643 }644}645646647class CollectionGroup extends HelperGroup<UniqueHelper> {648 /**649 * Get number of blocks when sponsored transaction is available.650 *651 * @param collectionId ID of collection652 * @param tokenId ID of token653 * @param addressObj address for which the sponsorship is checked654 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});655 * @returns number of blocks or null if sponsorship hasn't been set656 */657 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {658 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();659 }660661 /**662 * Get the number of created collections.663 *664 * @returns number of created collections665 */666 async getTotalCount(): Promise<number> {667 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();668 }669670 /**671 * Get information about the collection with additional data,672 * including the number of tokens it contains, its administrators,673 * the normalized address of the collection's owner, and decoded name and description.674 *675 * @param collectionId ID of collection676 * @example await getData(2)677 * @returns collection information object678 */679 async getData(collectionId: number): Promise<{680 id: number;681 name: string;682 description: string;683 tokensCount: number;684 admins: CrossAccountId[];685 normalizedOwner: TSubstrateAccount;686 raw: any687 } | null> {688 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);689 const humanCollection = collection.toHuman(), collectionData = {690 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],691 raw: humanCollection,692 } as any, jsonCollection = collection.toJSON();693 if (humanCollection === null) return null;694 collectionData.raw.limits = jsonCollection.limits;695 collectionData.raw.permissions = jsonCollection.permissions;696 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);697 for (const key of ['name', 'description']) {698 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);699 }700701 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))702 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)703 : 0;704 collectionData.admins = await this.getAdmins(collectionId);705706 return collectionData;707 }708709 /**710 * Get the addresses of the collection's administrators, optionally normalized.711 *712 * @param collectionId ID of collection713 * @param normalize whether to normalize the addresses to the default ss58 format714 * @example await getAdmins(1)715 * @returns array of administrators716 */717 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {718 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();719720 return normalize721 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())722 : admins;723 }724725 /**726 * Get the addresses added to the collection allow-list, optionally normalized.727 * @param collectionId ID of collection728 * @param normalize whether to normalize the addresses to the default ss58 format729 * @example await getAllowList(1)730 * @returns array of allow-listed addresses731 */732 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {733 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();734 return normalize735 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())736 : allowListed;737 }738739 /**740 * Get the effective limits of the collection instead of null for default values741 *742 * @param collectionId ID of collection743 * @example await getEffectiveLimits(2)744 * @returns object of collection limits745 */746 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {747 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();748 }749750 /**751 * Burns the collection if the signer has sufficient permissions and collection is empty.752 *753 * @param signer keyring of signer754 * @param collectionId ID of collection755 * @example await helper.collection.burn(aliceKeyring, 3);756 * @returns ```true``` if extrinsic success, otherwise ```false```757 */758 async burn(signer: TSigner, collectionId: number): Promise<boolean> {759 const result = await this.helper.executeExtrinsic(760 signer,761 'api.tx.unique.destroyCollection', [collectionId],762 true,763 );764765 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');766 }767768 /**769 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.770 *771 * @param signer keyring of signer772 * @param collectionId ID of collection773 * @param sponsorAddress Sponsor substrate address774 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")775 * @returns ```true``` if extrinsic success, otherwise ```false```776 */777 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {778 const result = await this.helper.executeExtrinsic(779 signer,780 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],781 true,782 );783784 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');785 }786787 /**788 * Confirms consent to sponsor the collection on behalf of the signer.789 *790 * @param signer keyring of signer791 * @param collectionId ID of collection792 * @example confirmSponsorship(aliceKeyring, 10)793 * @returns ```true``` if extrinsic success, otherwise ```false```794 */795 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {796 const result = await this.helper.executeExtrinsic(797 signer,798 'api.tx.unique.confirmSponsorship', [collectionId],799 true,800 );801802 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');803 }804805 /**806 * Removes the sponsor of a collection, regardless if it consented or not.807 *808 * @param signer keyring of signer809 * @param collectionId ID of collection810 * @example removeSponsor(aliceKeyring, 10)811 * @returns ```true``` if extrinsic success, otherwise ```false```812 */813 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {814 const result = await this.helper.executeExtrinsic(815 signer,816 'api.tx.unique.removeCollectionSponsor', [collectionId],817 true,818 );819820 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');821 }822823 /**824 * Sets the limits of the collection. At least one limit must be specified for a correct call.825 *826 * @param signer keyring of signer827 * @param collectionId ID of collection828 * @param limits collection limits object829 * @example830 * await setLimits(831 * aliceKeyring,832 * 10,833 * {834 * sponsorTransferTimeout: 0,835 * ownerCanDestroy: false836 * }837 * )838 * @returns ```true``` if extrinsic success, otherwise ```false```839 */840 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {841 const result = await this.helper.executeExtrinsic(842 signer,843 'api.tx.unique.setCollectionLimits', [collectionId, limits],844 true,845 );846847 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');848 }849850 /**851 * Changes the owner of the collection to the new Substrate address.852 *853 * @param signer keyring of signer854 * @param collectionId ID of collection855 * @param ownerAddress substrate address of new owner856 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")857 * @returns ```true``` if extrinsic success, otherwise ```false```858 */859 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {860 const result = await this.helper.executeExtrinsic(861 signer,862 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],863 true,864 );865866 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');867 }868869 /**870 * Adds a collection administrator.871 *872 * @param signer keyring of signer873 * @param collectionId ID of collection874 * @param adminAddressObj Administrator address (substrate or ethereum)875 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})876 * @returns ```true``` if extrinsic success, otherwise ```false```877 */878 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {879 const result = await this.helper.executeExtrinsic(880 signer,881 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],882 true,883 );884885 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');886 }887888 /**889 * Removes a collection administrator.890 *891 * @param signer keyring of signer892 * @param collectionId ID of collection893 * @param adminAddressObj Administrator address (substrate or ethereum)894 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})895 * @returns ```true``` if extrinsic success, otherwise ```false```896 */897 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {898 const result = await this.helper.executeExtrinsic(899 signer,900 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],901 true,902 );903904 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');905 }906907 /**908 * Check if user is in allow list.909 * 910 * @param collectionId ID of collection911 * @param user Account to check912 * @example await getAdmins(1)913 * @returns is user in allow list914 */915 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {916 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();917 }918919 /**920 * Adds an address to allow list921 * @param signer keyring of signer922 * @param collectionId ID of collection923 * @param addressObj address to add to the allow list924 * @returns ```true``` if extrinsic success, otherwise ```false```925 */926 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {927 const result = await this.helper.executeExtrinsic(928 signer,929 'api.tx.unique.addToAllowList', [collectionId, addressObj],930 true,931 );932933 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');934 }935936 /**937 * Removes an address from allow list938 *939 * @param signer keyring of signer940 * @param collectionId ID of collection941 * @param addressObj address to remove from the allow list942 * @returns ```true``` if extrinsic success, otherwise ```false```943 */944 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {945 const result = await this.helper.executeExtrinsic(946 signer,947 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],948 true,949 );950951 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');952 }953954 /**955 * Sets onchain permissions for selected collection.956 *957 * @param signer keyring of signer958 * @param collectionId ID of collection959 * @param permissions collection permissions object960 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});961 * @returns ```true``` if extrinsic success, otherwise ```false```962 */963 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {964 const result = await this.helper.executeExtrinsic(965 signer,966 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],967 true,968 );969970 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');971 }972973 /**974 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.975 *976 * @param signer keyring of signer977 * @param collectionId ID of collection978 * @param permissions nesting permissions object979 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});980 * @returns ```true``` if extrinsic success, otherwise ```false```981 */982 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {983 return await this.setPermissions(signer, collectionId, {nesting: permissions});984 }985986 /**987 * Disables nesting for selected collection.988 *989 * @param signer keyring of signer990 * @param collectionId ID of collection991 * @example disableNesting(aliceKeyring, 10);992 * @returns ```true``` if extrinsic success, otherwise ```false```993 */994 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {995 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});996 }997998 /**999 * Sets onchain properties to the collection.1000 *1001 * @param signer keyring of signer1002 * @param collectionId ID of collection1003 * @param properties array of property objects1004 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1005 * @returns ```true``` if extrinsic success, otherwise ```false```1006 */1007 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1008 const result = await this.helper.executeExtrinsic(1009 signer,1010 'api.tx.unique.setCollectionProperties', [collectionId, properties],1011 true,1012 );10131014 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1015 }10161017 /**1018 * Get collection properties.1019 * 1020 * @param collectionId ID of collection1021 * @param propertyKeys optionally filter the returned properties to only these keys1022 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1023 * @returns array of key-value pairs1024 */1025 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1026 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1027 }10281029 async getCollectionOptions(collectionId: number) {1030 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1031 }10321033 /**1034 * Deletes onchain properties from the collection.1035 *1036 * @param signer keyring of signer1037 * @param collectionId ID of collection1038 * @param propertyKeys array of property keys to delete1039 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1040 * @returns ```true``` if extrinsic success, otherwise ```false```1041 */1042 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1043 const result = await this.helper.executeExtrinsic(1044 signer,1045 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1046 true,1047 );10481049 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1050 }10511052 /**1053 * Changes the owner of the token.1054 *1055 * @param signer keyring of signer1056 * @param collectionId ID of collection1057 * @param tokenId ID of token1058 * @param addressObj address of a new owner1059 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1060 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1061 * @returns true if the token success, otherwise false1062 */1063 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1064 const result = await this.helper.executeExtrinsic(1065 signer,1066 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1067 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1068 );10691070 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1071 }10721073 /**1074 *1075 * Change ownership of a token(s) on behalf of the owner.1076 *1077 * @param signer keyring of signer1078 * @param collectionId ID of collection1079 * @param tokenId ID of token1080 * @param fromAddressObj address on behalf of which the token will be sent1081 * @param toAddressObj new token owner1082 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1083 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1084 * @returns true if the token success, otherwise false1085 */1086 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1087 const result = await this.helper.executeExtrinsic(1088 signer,1089 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1090 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1091 );1092 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1093 }10941095 /**1096 *1097 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1098 *1099 * @param signer keyring of signer1100 * @param collectionId ID of collection1101 * @param tokenId ID of token1102 * @param amount amount of tokens to be burned. For NFT must be set to 1n1103 * @example burnToken(aliceKeyring, 10, 5);1104 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1105 */1106 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1107 const burnResult = await this.helper.executeExtrinsic(1108 signer,1109 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1110 true, // `Unable to burn token for ${label}`,1111 );1112 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1113 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1114 return burnedTokens.success;1115 }11161117 /**1118 * Destroys a concrete instance of NFT on behalf of the owner1119 *1120 * @param signer keyring of signer1121 * @param collectionId ID of collection1122 * @param tokenId ID of token1123 * @param fromAddressObj address on behalf of which the token will be burnt1124 * @param amount amount of tokens to be burned. For NFT must be set to 1n1125 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1126 * @returns ```true``` if extrinsic success, otherwise ```false```1127 */1128 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1129 const burnResult = await this.helper.executeExtrinsic(1130 signer,1131 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1132 true, // `Unable to burn token from for ${label}`,1133 );1134 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1135 return burnedTokens.success && burnedTokens.tokens.length > 0;1136 }11371138 /**1139 * Set, change, or remove approved address to transfer the ownership of the NFT.1140 *1141 * @param signer keyring of signer1142 * @param collectionId ID of collection1143 * @param tokenId ID of token1144 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1145 * @param amount amount of token to be approved. For NFT must be set to 1n1146 * @returns ```true``` if extrinsic success, otherwise ```false```1147 */1148 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1149 const approveResult = await this.helper.executeExtrinsic(1150 signer,1151 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1152 true, // `Unable to approve token for ${label}`,1153 );11541155 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1156 }11571158 /**1159 * Get the amount of token pieces approved to transfer or burn. Normally 0.1160 *1161 * @param collectionId ID of collection1162 * @param tokenId ID of token1163 * @param toAccountObj address which is approved to use token pieces1164 * @param fromAccountObj address which may have allowed the use of its owned tokens1165 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1166 * @returns number of approved to transfer pieces1167 */1168 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1169 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1170 }11711172 /**1173 * Get the last created token ID in a collection1174 *1175 * @param collectionId ID of collection1176 * @example getLastTokenId(10);1177 * @returns id of the last created token1178 */1179 async getLastTokenId(collectionId: number): Promise<number> {1180 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1181 }11821183 /**1184 * Check if token exists1185 *1186 * @param collectionId ID of collection1187 * @param tokenId ID of token1188 * @example doesTokenExist(10, 20);1189 * @returns true if the token exists, otherwise false1190 */1191 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1192 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1193 }1194}11951196class NFTnRFT extends CollectionGroup {1197 /**1198 * Get tokens owned by account1199 *1200 * @param collectionId ID of collection1201 * @param addressObj tokens owner1202 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1203 * @returns array of token ids owned by account1204 */1205 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1206 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1207 }12081209 /**1210 * Get token data1211 *1212 * @param collectionId ID of collection1213 * @param tokenId ID of token1214 * @param propertyKeys optionally filter the token properties to only these keys1215 * @param blockHashAt optionally query the data at some block with this hash1216 * @example getToken(10, 5);1217 * @returns human readable token data1218 */1219 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1220 properties: IProperty[];1221 owner: CrossAccountId;1222 normalizedOwner: CrossAccountId;1223 }| null> {1224 let tokenData;1225 if(typeof blockHashAt === 'undefined') {1226 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1227 }1228 else {1229 if(propertyKeys.length == 0) {1230 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1231 if(!collection) return null;1232 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1233 }1234 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1235 }1236 tokenData = tokenData.toHuman();1237 if (tokenData === null || tokenData.owner === null) return null;1238 const owner = {} as any;1239 for (const key of Object.keys(tokenData.owner)) {1240 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1241 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1242 : tokenData.owner[key];1243 }1244 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1245 return tokenData;1246 }12471248 /**1249 * Set permissions to change token properties1250 *1251 * @param signer keyring of signer1252 * @param collectionId ID of collection1253 * @param permissions permissions to change a property by the collection admin or token owner1254 * @example setTokenPropertyPermissions(1255 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1256 * )1257 * @returns true if extrinsic success otherwise false1258 */1259 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1260 const result = await this.helper.executeExtrinsic(1261 signer,1262 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1263 true,1264 );12651266 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1267 }12681269 /**1270 * Get token property permissions.1271 * 1272 * @param collectionId ID of collection1273 * @param propertyKeys optionally filter the returned property permissions to only these keys1274 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1275 * @returns array of key-permission pairs1276 */1277 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1278 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1279 }12801281 /**1282 * Set token properties1283 *1284 * @param signer keyring of signer1285 * @param collectionId ID of collection1286 * @param tokenId ID of token1287 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1288 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1289 * @returns ```true``` if extrinsic success, otherwise ```false```1290 */1291 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1292 const result = await this.helper.executeExtrinsic(1293 signer,1294 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1295 true,1296 );12971298 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1299 }13001301 /**1302 * Get properties, metadata assigned to a token.1303 * 1304 * @param collectionId ID of collection1305 * @param tokenId ID of token1306 * @param propertyKeys optionally filter the returned properties to only these keys1307 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1308 * @returns array of key-value pairs1309 */1310 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1311 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1312 }13131314 /**1315 * Delete the provided properties of a token1316 * @param signer keyring of signer1317 * @param collectionId ID of collection1318 * @param tokenId ID of token1319 * @param propertyKeys property keys to be deleted1320 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1321 * @returns ```true``` if extrinsic success, otherwise ```false```1322 */1323 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1324 const result = await this.helper.executeExtrinsic(1325 signer,1326 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1327 true,1328 );13291330 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1331 }13321333 /**1334 * Mint new collection1335 *1336 * @param signer keyring of signer1337 * @param collectionOptions basic collection options and properties1338 * @param mode NFT or RFT type of a collection1339 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1340 * @returns object of the created collection1341 */1342 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1343 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1344 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1345 for (const key of ['name', 'description', 'tokenPrefix']) {1346 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1347 }1348 const creationResult = await this.helper.executeExtrinsic(1349 signer,1350 'api.tx.unique.createCollectionEx', [collectionOptions],1351 true, // errorLabel,1352 );1353 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1354 }13551356 getCollectionObject(_collectionId: number): any {1357 return null;1358 }13591360 getTokenObject(_collectionId: number, _tokenId: number): any {1361 return null;1362 }1363}136413651366class NFTGroup extends NFTnRFT {1367 /**1368 * Get collection object1369 * @param collectionId ID of collection1370 * @example getCollectionObject(2);1371 * @returns instance of UniqueNFTCollection1372 */1373 getCollectionObject(collectionId: number): UniqueNFTCollection {1374 return new UniqueNFTCollection(collectionId, this.helper);1375 }13761377 /**1378 * Get token object1379 * @param collectionId ID of collection1380 * @param tokenId ID of token1381 * @example getTokenObject(10, 5);1382 * @returns instance of UniqueNFTToken1383 */1384 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1385 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1386 }13871388 /**1389 * Get token's owner1390 * @param collectionId ID of collection1391 * @param tokenId ID of token1392 * @param blockHashAt optionally query the data at the block with this hash1393 * @example getTokenOwner(10, 5);1394 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1395 */1396 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1397 let owner;1398 if (typeof blockHashAt === 'undefined') {1399 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1400 } else {1401 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1402 }1403 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1404 }14051406 /**1407 * Is token approved to transfer1408 * @param collectionId ID of collection1409 * @param tokenId ID of token1410 * @param toAccountObj address to be approved1411 * @returns ```true``` if extrinsic success, otherwise ```false```1412 */1413 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1414 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1415 }14161417 /**1418 * Changes the owner of the token.1419 *1420 * @param signer keyring of signer1421 * @param collectionId ID of collection1422 * @param tokenId ID of token1423 * @param addressObj address of a new owner1424 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1425 * @returns ```true``` if extrinsic success, otherwise ```false```1426 */1427 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1428 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1429 }14301431 /**1432 *1433 * Change ownership of a NFT on behalf of the owner.1434 *1435 * @param signer keyring of signer1436 * @param collectionId ID of collection1437 * @param tokenId ID of token1438 * @param fromAddressObj address on behalf of which the token will be sent1439 * @param toAddressObj new token owner1440 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1441 * @returns ```true``` if extrinsic success, otherwise ```false```1442 */1443 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1444 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1445 }14461447 /**1448 * Recursively find the address that owns the token1449 * @param collectionId ID of collection1450 * @param tokenId ID of token1451 * @param blockHashAt1452 * @example getTokenTopmostOwner(10, 5);1453 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1454 */1455 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1456 let owner;1457 if (typeof blockHashAt === 'undefined') {1458 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1459 } else {1460 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1461 }14621463 if (owner === null) return null;14641465 return owner.toHuman();1466 }14671468 /**1469 * Get tokens nested in the provided token1470 * @param collectionId ID of collection1471 * @param tokenId ID of token1472 * @param blockHashAt optionally query the data at the block with this hash1473 * @example getTokenChildren(10, 5);1474 * @returns tokens whose depth of nesting is <= 51475 */1476 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1477 let children;1478 if(typeof blockHashAt === 'undefined') {1479 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1480 } else {1481 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1482 }14831484 return children.toJSON().map((x: any) => {1485 return {collectionId: x.collection, tokenId: x.token};1486 });1487 }14881489 /**1490 * Nest one token into another1491 * @param signer keyring of signer1492 * @param tokenObj token to be nested1493 * @param rootTokenObj token to be parent1494 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1495 * @returns ```true``` if extrinsic success, otherwise ```false```1496 */1497 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1498 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1499 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1500 if(!result) {1501 throw Error('Unable to nest token!');1502 }1503 return result;1504 }15051506 /**1507 * Remove token from nested state1508 * @param signer keyring of signer1509 * @param tokenObj token to unnest1510 * @param rootTokenObj parent of a token1511 * @param toAddressObj address of a new token owner1512 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1513 * @returns ```true``` if extrinsic success, otherwise ```false```1514 */1515 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1516 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1517 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1518 if(!result) {1519 throw Error('Unable to unnest token!');1520 }1521 return result;1522 }15231524 /**1525 * Mint new collection1526 * @param signer keyring of signer1527 * @param collectionOptions Collection options1528 * @example1529 * mintCollection(aliceKeyring, {1530 * name: 'New',1531 * description: 'New collection',1532 * tokenPrefix: 'NEW',1533 * })1534 * @returns object of the created collection1535 */1536 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1537 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1538 }15391540 /**1541 * Mint new token1542 * @param signer keyring of signer1543 * @param data token data1544 * @returns created token object1545 */1546 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1547 const creationResult = await this.helper.executeExtrinsic(1548 signer,1549 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1550 nft: {1551 properties: data.properties,1552 },1553 }],1554 true,1555 );1556 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1557 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1558 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1559 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1560 }15611562 /**1563 * Mint multiple NFT tokens1564 * @param signer keyring of signer1565 * @param collectionId ID of collection1566 * @param tokens array of tokens with owner and properties1567 * @example1568 * mintMultipleTokens(aliceKeyring, 10, [{1569 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1570 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1571 * },{1572 * owner: {Ethereum: "0x9F0583DbB855d..."},1573 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1574 * }]);1575 * @returns ```true``` if extrinsic success, otherwise ```false```1576 */1577 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1578 const creationResult = await this.helper.executeExtrinsic(1579 signer,1580 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1581 true,1582 );1583 const collection = this.getCollectionObject(collectionId);1584 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1585 }15861587 /**1588 * Mint multiple NFT tokens with one owner1589 * @param signer keyring of signer1590 * @param collectionId ID of collection1591 * @param owner tokens owner1592 * @param tokens array of tokens with owner and properties1593 * @example1594 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1595 * properties: [{1596 * key: "gender",1597 * value: "female",1598 * },{1599 * key: "age",1600 * value: "33",1601 * }],1602 * }]);1603 * @returns array of newly created tokens1604 */1605 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1606 const rawTokens = [];1607 for (const token of tokens) {1608 const raw = {NFT: {properties: token.properties}};1609 rawTokens.push(raw);1610 }1611 const creationResult = await this.helper.executeExtrinsic(1612 signer,1613 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1614 true,1615 );1616 const collection = this.getCollectionObject(collectionId);1617 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1618 }16191620 /**1621 * Set, change, or remove approved address to transfer the ownership of the NFT.1622 *1623 * @param signer keyring of signer1624 * @param collectionId ID of collection1625 * @param tokenId ID of token1626 * @param toAddressObj address to approve1627 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1628 * @returns ```true``` if extrinsic success, otherwise ```false```1629 */1630 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1631 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1632 }1633}163416351636class RFTGroup extends NFTnRFT {1637 /**1638 * Get collection object1639 * @param collectionId ID of collection1640 * @example getCollectionObject(2);1641 * @returns instance of UniqueRFTCollection1642 */1643 getCollectionObject(collectionId: number): UniqueRFTCollection {1644 return new UniqueRFTCollection(collectionId, this.helper);1645 }16461647 /**1648 * Get token object1649 * @param collectionId ID of collection1650 * @param tokenId ID of token1651 * @example getTokenObject(10, 5);1652 * @returns instance of UniqueNFTToken1653 */1654 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1655 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1656 }16571658 /**1659 * Get top 10 token owners with the largest number of pieces1660 * @param collectionId ID of collection1661 * @param tokenId ID of token1662 * @example getTokenTop10Owners(10, 5);1663 * @returns array of top 10 owners1664 */1665 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1666 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1667 }16681669 /**1670 * Get number of pieces owned by address1671 * @param collectionId ID of collection1672 * @param tokenId ID of token1673 * @param addressObj address token owner1674 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1675 * @returns number of pieces ownerd by address1676 */1677 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1678 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1679 }16801681 /**1682 * Transfer pieces of token to another address1683 * @param signer keyring of signer1684 * @param collectionId ID of collection1685 * @param tokenId ID of token1686 * @param addressObj address of a new owner1687 * @param amount number of pieces to be transfered1688 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1689 * @returns ```true``` if extrinsic success, otherwise ```false```1690 */1691 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1692 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1693 }16941695 /**1696 * Change ownership of some pieces of RFT on behalf of the owner.1697 * @param signer keyring of signer1698 * @param collectionId ID of collection1699 * @param tokenId ID of token1700 * @param fromAddressObj address on behalf of which the token will be sent1701 * @param toAddressObj new token owner1702 * @param amount number of pieces to be transfered1703 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1704 * @returns ```true``` if extrinsic success, otherwise ```false```1705 */1706 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1707 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1708 }17091710 /**1711 * Mint new collection1712 * @param signer keyring of signer1713 * @param collectionOptions Collection options1714 * @example1715 * mintCollection(aliceKeyring, {1716 * name: 'New',1717 * description: 'New collection',1718 * tokenPrefix: 'NEW',1719 * })1720 * @returns object of the created collection1721 */1722 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1723 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1724 }17251726 /**1727 * Mint new token1728 * @param signer keyring of signer1729 * @param data token data1730 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1731 * @returns created token object1732 */1733 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1734 const creationResult = await this.helper.executeExtrinsic(1735 signer,1736 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1737 refungible: {1738 pieces: data.pieces,1739 properties: data.properties,1740 },1741 }],1742 true,1743 );1744 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1745 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1746 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1747 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1748 }17491750 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1751 throw Error('Not implemented');1752 const creationResult = await this.helper.executeExtrinsic(1753 signer,1754 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1755 true, // `Unable to mint RFT tokens for ${label}`,1756 );1757 const collection = this.getCollectionObject(collectionId);1758 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1759 }17601761 /**1762 * Mint multiple RFT tokens with one owner1763 * @param signer keyring of signer1764 * @param collectionId ID of collection1765 * @param owner tokens owner1766 * @param tokens array of tokens with properties and pieces1767 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1768 * @returns array of newly created RFT tokens1769 */1770 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1771 const rawTokens = [];1772 for (const token of tokens) {1773 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1774 rawTokens.push(raw);1775 }1776 const creationResult = await this.helper.executeExtrinsic(1777 signer,1778 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1779 true,1780 );1781 const collection = this.getCollectionObject(collectionId);1782 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1783 }17841785 /**1786 * Destroys a concrete instance of RFT.1787 * @param signer keyring of signer1788 * @param collectionId ID of collection1789 * @param tokenId ID of token1790 * @param amount number of pieces to be burnt1791 * @example burnToken(aliceKeyring, 10, 5);1792 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1793 */1794 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1795 return await super.burnToken(signer, collectionId, tokenId, amount);1796 }17971798 /**1799 * Destroys a concrete instance of RFT on behalf of the owner.1800 * @param signer keyring of signer1801 * @param collectionId ID of collection1802 * @param tokenId ID of token1803 * @param fromAddressObj address on behalf of which the token will be burnt1804 * @param amount number of pieces to be burnt1805 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1806 * @returns ```true``` if extrinsic success, otherwise ```false```1807 */1808 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1809 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1810 }18111812 /**1813 * Set, change, or remove approved address to transfer the ownership of the RFT.1814 *1815 * @param signer keyring of signer1816 * @param collectionId ID of collection1817 * @param tokenId ID of token1818 * @param toAddressObj address to approve1819 * @param amount number of pieces to be approved1820 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1821 * @returns true if the token success, otherwise false1822 */1823 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1824 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1825 }18261827 /**1828 * Get total number of pieces1829 * @param collectionId ID of collection1830 * @param tokenId ID of token1831 * @example getTokenTotalPieces(10, 5);1832 * @returns number of pieces1833 */1834 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1835 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1836 }18371838 /**1839 * Change number of token pieces. Signer must be the owner of all token pieces.1840 * @param signer keyring of signer1841 * @param collectionId ID of collection1842 * @param tokenId ID of token1843 * @param amount new number of pieces1844 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1845 * @returns true if the repartion was success, otherwise false1846 */1847 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1848 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1849 const repartitionResult = await this.helper.executeExtrinsic(1850 signer,1851 'api.tx.unique.repartition', [collectionId, tokenId, amount],1852 true,1853 );1854 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1855 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1856 }1857}185818591860class FTGroup extends CollectionGroup {1861 /**1862 * Get collection object1863 * @param collectionId ID of collection1864 * @example getCollectionObject(2);1865 * @returns instance of UniqueFTCollection1866 */1867 getCollectionObject(collectionId: number): UniqueFTCollection {1868 return new UniqueFTCollection(collectionId, this.helper);1869 }18701871 /**1872 * Mint new fungible collection1873 * @param signer keyring of signer1874 * @param collectionOptions Collection options1875 * @param decimalPoints number of token decimals1876 * @example1877 * mintCollection(aliceKeyring, {1878 * name: 'New',1879 * description: 'New collection',1880 * tokenPrefix: 'NEW',1881 * }, 18)1882 * @returns newly created fungible collection1883 */1884 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1885 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1886 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1887 collectionOptions.mode = {fungible: decimalPoints};1888 for (const key of ['name', 'description', 'tokenPrefix']) {1889 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1890 }1891 const creationResult = await this.helper.executeExtrinsic(1892 signer,1893 'api.tx.unique.createCollectionEx', [collectionOptions],1894 true,1895 );1896 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1897 }18981899 /**1900 * Mint tokens1901 * @param signer keyring of signer1902 * @param collectionId ID of collection1903 * @param owner address owner of new tokens1904 * @param amount amount of tokens to be meanted1905 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1906 * @returns ```true``` if extrinsic success, otherwise ```false```1907 */1908 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1909 const creationResult = await this.helper.executeExtrinsic(1910 signer,1911 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1912 fungible: {1913 value: amount,1914 },1915 }],1916 true, // `Unable to mint fungible tokens for ${label}`,1917 );1918 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1919 }19201921 /**1922 * Mint multiple Fungible tokens with one owner1923 * @param signer keyring of signer1924 * @param collectionId ID of collection1925 * @param owner tokens owner1926 * @param tokens array of tokens with properties and pieces1927 * @returns ```true``` if extrinsic success, otherwise ```false```1928 */1929 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1930 const rawTokens = [];1931 for (const token of tokens) {1932 const raw = {Fungible: {Value: token.value}};1933 rawTokens.push(raw);1934 }1935 const creationResult = await this.helper.executeExtrinsic(1936 signer,1937 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1938 true,1939 );1940 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1941 }19421943 /**1944 * Get the top 10 owners with the largest balance for the Fungible collection1945 * @param collectionId ID of collection1946 * @example getTop10Owners(10);1947 * @returns array of ```ICrossAccountId```1948 */1949 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1950 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1951 }19521953 /**1954 * Get account balance1955 * @param collectionId ID of collection1956 * @param addressObj address of owner1957 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1958 * @returns amount of fungible tokens owned by address1959 */1960 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1961 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1962 }19631964 /**1965 * Transfer tokens to address1966 * @param signer keyring of signer1967 * @param collectionId ID of collection1968 * @param toAddressObj address recipient1969 * @param amount amount of tokens to be sent1970 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1971 * @returns ```true``` if extrinsic success, otherwise ```false```1972 */1973 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1974 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1975 }19761977 /**1978 * Transfer some tokens on behalf of the owner.1979 * @param signer keyring of signer1980 * @param collectionId ID of collection1981 * @param fromAddressObj address on behalf of which tokens will be sent1982 * @param toAddressObj address where token to be sent1983 * @param amount number of tokens to be sent1984 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1985 * @returns ```true``` if extrinsic success, otherwise ```false```1986 */1987 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1988 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1989 }19901991 /**1992 * Destroy some amount of tokens1993 * @param signer keyring of signer1994 * @param collectionId ID of collection1995 * @param amount amount of tokens to be destroyed1996 * @example burnTokens(aliceKeyring, 10, 1000n);1997 * @returns ```true``` if extrinsic success, otherwise ```false```1998 */1999 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2000 return await super.burnToken(signer, collectionId, 0, amount);2001 }20022003 /**2004 * Burn some tokens on behalf of the owner.2005 * @param signer keyring of signer2006 * @param collectionId ID of collection2007 * @param fromAddressObj address on behalf of which tokens will be burnt2008 * @param amount amount of tokens to be burnt2009 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2010 * @returns ```true``` if extrinsic success, otherwise ```false```2011 */2012 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2013 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2014 }20152016 /**2017 * Get total collection supply2018 * @param collectionId2019 * @returns2020 */2021 async getTotalPieces(collectionId: number): Promise<bigint> {2022 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2023 }20242025 /**2026 * Set, change, or remove approved address to transfer tokens.2027 *2028 * @param signer keyring of signer2029 * @param collectionId ID of collection2030 * @param toAddressObj address to be approved2031 * @param amount amount of tokens to be approved2032 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2033 * @returns ```true``` if extrinsic success, otherwise ```false```2034 */2035 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2036 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2037 }20382039 /**2040 * Get amount of fungible tokens approved to transfer2041 * @param collectionId ID of collection2042 * @param fromAddressObj owner of tokens2043 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2044 * @returns number of tokens approved for the transfer2045 */2046 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2047 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2048 }2049}205020512052class ChainGroup extends HelperGroup<ChainHelperBase> {2053 /**2054 * Get system properties of a chain2055 * @example getChainProperties();2056 * @returns ss58Format, token decimals, and token symbol2057 */2058 getChainProperties(): IChainProperties {2059 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2060 return {2061 ss58Format: properties.ss58Format.toJSON(),2062 tokenDecimals: properties.tokenDecimals.toJSON(),2063 tokenSymbol: properties.tokenSymbol.toJSON(),2064 };2065 }20662067 /**2068 * Get chain header2069 * @example getLatestBlockNumber();2070 * @returns the number of the last block2071 */2072 async getLatestBlockNumber(): Promise<number> {2073 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2074 }20752076 /**2077 * Get block hash by block number2078 * @param blockNumber number of block2079 * @example getBlockHashByNumber(12345);2080 * @returns hash of a block2081 */2082 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2083 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2084 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2085 return blockHash;2086 }20872088 // TODO add docs2089 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2090 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2091 if (!blockHash) return null;2092 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2093 }20942095 /**2096 * Get account nonce2097 * @param address substrate address2098 * @example getNonce("5GrwvaEF5zXb26Fz...");2099 * @returns number, account's nonce2100 */2101 async getNonce(address: TSubstrateAccount): Promise<number> {2102 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2103 }2104}21052106class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2107 /**2108 * Get substrate address balance2109 * @param address substrate address2110 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2111 * @returns amount of tokens on address2112 */2113 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2114 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2115 }21162117 /**2118 * Transfer tokens to substrate address2119 * @param signer keyring of signer2120 * @param address substrate address of a recipient2121 * @param amount amount of tokens to be transfered2122 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2123 * @returns ```true``` if extrinsic success, otherwise ```false```2124 */2125 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2126 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);21272128 let transfer = {from: null, to: null, amount: 0n} as any;2129 result.result.events.forEach(({event: {data, method, section}}) => {2130 if ((section === 'balances') && (method === 'Transfer')) {2131 transfer = {2132 from: this.helper.address.normalizeSubstrate(data[0]),2133 to: this.helper.address.normalizeSubstrate(data[1]),2134 amount: BigInt(data[2]),2135 };2136 }2137 });2138 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2139 && this.helper.address.normalizeSubstrate(address) === transfer.to 2140 && BigInt(amount) === transfer.amount;2141 return isSuccess;2142 }21432144 /**2145 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2146 * @param address substrate address2147 * @returns2148 */2149 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2150 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2151 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2152 }2153}21542155class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2156 /**2157 * Get ethereum address balance2158 * @param address ethereum address2159 * @example getEthereum("0x9F0583DbB855d...")2160 * @returns amount of tokens on address2161 */2162 async getEthereum(address: TEthereumAccount): Promise<bigint> {2163 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2164 }21652166 /**2167 * Transfer tokens to address2168 * @param signer keyring of signer2169 * @param address Ethereum address of a recipient2170 * @param amount amount of tokens to be transfered2171 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2172 * @returns ```true``` if extrinsic success, otherwise ```false```2173 */2174 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2175 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21762177 let transfer = {from: null, to: null, amount: 0n} as any;2178 result.result.events.forEach(({event: {data, method, section}}) => {2179 if ((section === 'balances') && (method === 'Transfer')) {2180 transfer = {2181 from: data[0].toString(),2182 to: data[1].toString(),2183 amount: BigInt(data[2]),2184 };2185 }2186 });2187 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2188 && address === transfer.to 2189 && BigInt(amount) === transfer.amount;2190 return isSuccess;2191 }2192}21932194class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2195 subBalanceGroup: SubstrateBalanceGroup<T>;2196 ethBalanceGroup: EthereumBalanceGroup<T>;21972198 constructor(helper: T) {2199 super(helper);2200 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2201 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2202 }22032204 getCollectionCreationPrice(): bigint {2205 return 2n * this.getOneTokenNominal();2206 }2207 /**2208 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2209 * @example getOneTokenNominal()2210 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2211 */2212 getOneTokenNominal(): bigint {2213 const chainProperties = this.helper.chain.getChainProperties();2214 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2215 }22162217 /**2218 * Get substrate address balance2219 * @param address substrate address2220 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2221 * @returns amount of tokens on address2222 */2223 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2224 return this.subBalanceGroup.getSubstrate(address);2225 }22262227 /**2228 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2229 * @param address substrate address2230 * @returns2231 */2232 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2233 return this.subBalanceGroup.getSubstrateFull(address);2234 }22352236 /**2237 * Get ethereum address balance2238 * @param address ethereum address2239 * @example getEthereum("0x9F0583DbB855d...")2240 * @returns amount of tokens on address2241 */2242 async getEthereum(address: TEthereumAccount): Promise<bigint> {2243 return this.ethBalanceGroup.getEthereum(address);2244 }22452246 /**2247 * Transfer tokens to substrate address2248 * @param signer keyring of signer2249 * @param address substrate address of a recipient2250 * @param amount amount of tokens to be transfered2251 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2252 * @returns ```true``` if extrinsic success, otherwise ```false```2253 */2254 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2255 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2256 }2257}22582259class AddressGroup extends HelperGroup<ChainHelperBase> {2260 /**2261 * Normalizes the address to the specified ss58 format, by default ```42```.2262 * @param address substrate address2263 * @param ss58Format format for address conversion, by default ```42```2264 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2265 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2266 */2267 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2268 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2269 }22702271 /**2272 * Get address in the connected chain format2273 * @param address substrate address2274 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2275 * @returns address in chain format2276 */2277 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2278 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2279 }22802281 /**2282 * Get substrate mirror of an ethereum address2283 * @param ethAddress ethereum address2284 * @param toChainFormat false for normalized account2285 * @example ethToSubstrate('0x9F0583DbB855d...')2286 * @returns substrate mirror of a provided ethereum address2287 */2288 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2289 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2290 }22912292 /**2293 * Get ethereum mirror of a substrate address2294 * @param subAddress substrate account2295 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2296 * @returns ethereum mirror of a provided substrate address2297 */2298 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2299 return CrossAccountId.translateSubToEth(subAddress);2300 }23012302 paraSiblingSovereignAccount(paraid: number) {2303 // We are getting a *sibling* parachain sovereign account,2304 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2305 const siblingPrefix = '0x7369626c';23062307 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2308 const suffix = '000000000000000000000000000000000000000000000000';23092310 return siblingPrefix + encodedParaId + suffix;2311 }2312}23132314class StakingGroup extends HelperGroup<UniqueHelper> {2315 /**2316 * Stake tokens for App Promotion2317 * @param signer keyring of signer2318 * @param amountToStake amount of tokens to stake2319 * @param label extra label for log2320 * @returns2321 */2322 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2323 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2324 const _stakeResult = await this.helper.executeExtrinsic(2325 signer, 'api.tx.appPromotion.stake',2326 [amountToStake], true,2327 );2328 // TODO extract info from stakeResult2329 return true;2330 }23312332 /**2333 * Unstake tokens for App Promotion2334 * @param signer keyring of signer2335 * @param amountToUnstake amount of tokens to unstake2336 * @param label extra label for log2337 * @returns block number where balances will be unlocked2338 */2339 async unstake(signer: TSigner, label?: string): Promise<number> {2340 if(typeof label === 'undefined') label = `${signer.address}`;2341 const _unstakeResult = await this.helper.executeExtrinsic(2342 signer, 'api.tx.appPromotion.unstake',2343 [], true,2344 );2345 // TODO extract block number fron events2346 return 1;2347 }23482349 /**2350 * Get total staked amount for address2351 * @param address substrate or ethereum address2352 * @returns total staked amount2353 */2354 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2355 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2356 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2357 }23582359 /**2360 * Get total staked per block2361 * @param address substrate or ethereum address2362 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2363 */2364 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2365 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2366 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2367 return { 2368 block: block.toBigInt(),2369 amount: amount.toBigInt(),2370 };2371 });2372 }23732374 /**2375 * Get total pending unstake amount for address2376 * @param address substrate or ethereum address2377 * @returns total pending unstake amount2378 */2379 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2380 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2381 }23822383 /**2384 * Get pending unstake amount per block for address2385 * @param address substrate or ethereum address2386 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2387 */2388 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2389 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2390 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2391 return {2392 block: block.toBigInt(),2393 amount: amount.toBigInt(),2394 };2395 });2396 return result;2397 }2398}23992400class SchedulerGroup extends HelperGroup<UniqueHelper> {2401 constructor(helper: UniqueHelper) {2402 super(helper);2403 }24042405 async cancelScheduled(signer: TSigner, scheduledId: string) {2406 return this.helper.executeExtrinsic(2407 signer,2408 'api.tx.scheduler.cancelNamed',2409 [scheduledId],2410 true,2411 );2412 }24132414 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2415 return this.helper.executeExtrinsic(2416 signer,2417 'api.tx.scheduler.changeNamedPriority',2418 [scheduledId, priority],2419 true,2420 );2421 }24222423 scheduleAt<T extends UniqueHelper>(2424 scheduledId: string,2425 executionBlockNumber: number,2426 options: ISchedulerOptions = {},2427 ) {2428 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2429 }24302431 scheduleAfter<T extends UniqueHelper>(2432 scheduledId: string,2433 blocksBeforeExecution: number,2434 options: ISchedulerOptions = {},2435 ) {2436 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2437 }24382439 schedule<T extends UniqueHelper>(2440 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2441 scheduledId: string,2442 blocksNum: number,2443 options: ISchedulerOptions = {},2444 ) {2445 // eslint-disable-next-line @typescript-eslint/naming-convention2446 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2447 return this.helper.clone(ScheduledHelperType, {2448 scheduleFn,2449 scheduledId,2450 blocksNum,2451 options,2452 }) as T;2453 }2454}24552456class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2457 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2458 await this.helper.executeExtrinsic(2459 signer,2460 'api.tx.foreignAssets.registerForeignAsset',2461 [ownerAddress, location, metadata],2462 true,2463 );2464 }24652466 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2467 await this.helper.executeExtrinsic(2468 signer,2469 'api.tx.foreignAssets.updateForeignAsset',2470 [foreignAssetId, location, metadata],2471 true,2472 );2473 }2474}24752476class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2477 palletName: string;24782479 constructor(helper: T, palletName: string) {2480 super(helper);24812482 this.palletName = palletName;2483 }24842485 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2486 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2487 }2488}24892490class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2491 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2492 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2493 }24942495 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2496 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2497 }24982499 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2500 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2501 }2502}25032504class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2505 async accounts(address: string, currencyId: any) {2506 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2507 return BigInt(free);2508 }2509}25102511class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2512 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2513 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2514 }25152516 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2517 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2518 }25192520 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2521 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2522 }25232524 async account(assetId: string | number, address: string) {2525 const accountAsset = (2526 await this.helper.callRpc('api.query.assets.account', [assetId, address])2527 ).toJSON()! as any;25282529 if (accountAsset !== null) {2530 return BigInt(accountAsset['balance']);2531 } else {2532 return null;2533 }2534 }2535}25362537class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2538 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2539 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2540 }2541}25422543class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2544 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2545 const apiPrefix = 'api.tx.assetManager.';25462547 const registerTx = this.helper.constructApiCall(2548 apiPrefix + 'registerForeignAsset',2549 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2550 );25512552 const setUnitsTx = this.helper.constructApiCall(2553 apiPrefix + 'setAssetUnitsPerSecond',2554 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2555 );25562557 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2558 const encodedProposal = batchCall?.method.toHex() || '';2559 return encodedProposal;2560 }25612562 async assetTypeId(location: any) {2563 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2564 }2565}25662567class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2568 async notePreimage(signer: TSigner, encodedProposal: string) {2569 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2570 }25712572 externalProposeMajority(proposalHash: string) {2573 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2574 }25752576 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2577 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2578 }25792580 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2581 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2582 }2583}25842585class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2586 collective: string;25872588 constructor(helper: MoonbeamHelper, collective: string) {2589 super(helper);25902591 this.collective = collective;2592 }25932594 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2595 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2596 }25972598 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2599 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2600 }26012602 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2603 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2604 }26052606 async proposalCount() {2607 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2608 }2609}26102611export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2612export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26132614export class UniqueHelper extends ChainHelperBase {2615 balance: BalanceGroup<UniqueHelper>;2616 collection: CollectionGroup;2617 nft: NFTGroup;2618 rft: RFTGroup;2619 ft: FTGroup;2620 staking: StakingGroup;2621 scheduler: SchedulerGroup;2622 foreignAssets: ForeignAssetsGroup;2623 xcm: XcmGroup<UniqueHelper>;2624 xTokens: XTokensGroup<UniqueHelper>;2625 tokens: TokensGroup<UniqueHelper>;26262627 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2628 super(logger, options.helperBase ?? UniqueHelper);26292630 this.balance = new BalanceGroup(this);2631 this.collection = new CollectionGroup(this);2632 this.nft = new NFTGroup(this);2633 this.rft = new RFTGroup(this);2634 this.ft = new FTGroup(this);2635 this.staking = new StakingGroup(this);2636 this.scheduler = new SchedulerGroup(this);2637 this.foreignAssets = new ForeignAssetsGroup(this);2638 this.xcm = new XcmGroup(this, 'polkadotXcm');2639 this.xTokens = new XTokensGroup(this);2640 this.tokens = new TokensGroup(this);2641 }26422643 getSudo<T extends UniqueHelper>() {2644 // eslint-disable-next-line @typescript-eslint/naming-convention2645 const SudoHelperType = SudoHelper(this.helperBase);2646 return this.clone(SudoHelperType) as T;2647 }2648}26492650export class XcmChainHelper extends ChainHelperBase {2651 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2652 const wsProvider = new WsProvider(wsEndpoint);2653 this.api = new ApiPromise({2654 provider: wsProvider,2655 });2656 await this.api.isReadyOrError;2657 this.network = await UniqueHelper.detectNetwork(this.api);2658 }2659}26602661export class RelayHelper extends XcmChainHelper {2662 xcm: XcmGroup<RelayHelper>;26632664 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2665 super(logger, options.helperBase ?? RelayHelper);26662667 this.xcm = new XcmGroup(this, 'xcmPallet');2668 }2669}26702671export class WestmintHelper extends XcmChainHelper {2672 balance: SubstrateBalanceGroup<WestmintHelper>;2673 xcm: XcmGroup<WestmintHelper>;2674 assets: AssetsGroup<WestmintHelper>;2675 xTokens: XTokensGroup<WestmintHelper>;26762677 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2678 super(logger, options.helperBase ?? WestmintHelper);26792680 this.balance = new SubstrateBalanceGroup(this);2681 this.xcm = new XcmGroup(this, 'polkadotXcm');2682 this.assets = new AssetsGroup(this);2683 this.xTokens = new XTokensGroup(this);2684 }2685}26862687export class MoonbeamHelper extends XcmChainHelper {2688 balance: EthereumBalanceGroup<MoonbeamHelper>;2689 assetManager: MoonbeamAssetManagerGroup;2690 assets: AssetsGroup<MoonbeamHelper>;2691 xTokens: XTokensGroup<MoonbeamHelper>;2692 democracy: MoonbeamDemocracyGroup;2693 collective: {2694 council: MoonbeamCollectiveGroup,2695 techCommittee: MoonbeamCollectiveGroup,2696 };26972698 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2699 super(logger, options.helperBase ?? MoonbeamHelper);27002701 this.balance = new EthereumBalanceGroup(this);2702 this.assetManager = new MoonbeamAssetManagerGroup(this);2703 this.assets = new AssetsGroup(this);2704 this.xTokens = new XTokensGroup(this);2705 this.democracy = new MoonbeamDemocracyGroup(this);2706 this.collective = {2707 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2708 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2709 };2710 }2711}27122713export class AcalaHelper extends XcmChainHelper {2714 balance: SubstrateBalanceGroup<AcalaHelper>;2715 assetRegistry: AcalaAssetRegistryGroup;2716 xTokens: XTokensGroup<AcalaHelper>;2717 tokens: TokensGroup<AcalaHelper>;27182719 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2720 super(logger, options.helperBase ?? AcalaHelper);27212722 this.balance = new SubstrateBalanceGroup(this);2723 this.assetRegistry = new AcalaAssetRegistryGroup(this);2724 this.xTokens = new XTokensGroup(this);2725 this.tokens = new TokensGroup(this);2726 }27272728 getSudo<T extends AcalaHelper>() {2729 // eslint-disable-next-line @typescript-eslint/naming-convention2730 const SudoHelperType = SudoHelper(this.helperBase);2731 return this.clone(SudoHelperType) as T;2732 }2733}27342735// eslint-disable-next-line @typescript-eslint/naming-convention2736function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2737 return class extends Base {2738 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2739 scheduledId: string;2740 blocksNum: number;2741 options: ISchedulerOptions;27422743 constructor(...args: any[]) {2744 const logger = args[0] as ILogger;2745 const options = args[1] as {2746 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2747 scheduledId: string,2748 blocksNum: number,2749 options: ISchedulerOptions2750 };27512752 super(logger);27532754 this.scheduleFn = options.scheduleFn;2755 this.scheduledId = options.scheduledId;2756 this.blocksNum = options.blocksNum;2757 this.options = options.options;2758 }27592760 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2761 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2762 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;27632764 return super.executeExtrinsic(2765 sender,2766 extrinsic,2767 [2768 this.scheduledId,2769 this.blocksNum,2770 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2771 this.options.priority ?? null,2772 {Value: scheduledTx},2773 ],2774 expectSuccess,2775 );2776 }2777 };2778}27792780// eslint-disable-next-line @typescript-eslint/naming-convention2781function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2782 return class extends Base {2783 constructor(...args: any[]) {2784 super(...args);2785 }27862787 executeExtrinsic (2788 sender: IKeyringPair,2789 extrinsic: string,2790 params: any[],2791 expectSuccess?: boolean,2792 ): Promise<ITransactionResult> {2793 const call = this.constructApiCall(extrinsic, params);27942795 return super.executeExtrinsic(2796 sender,2797 'api.tx.sudo.sudo',2798 [call],2799 expectSuccess,2800 );2801 }2802 };2803}28042805export class UniqueBaseCollection {2806 helper: UniqueHelper;2807 collectionId: number;28082809 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2810 this.collectionId = collectionId;2811 this.helper = uniqueHelper;2812 }28132814 async getData() {2815 return await this.helper.collection.getData(this.collectionId);2816 }28172818 async getLastTokenId() {2819 return await this.helper.collection.getLastTokenId(this.collectionId);2820 }28212822 async doesTokenExist(tokenId: number) {2823 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2824 }28252826 async getAdmins() {2827 return await this.helper.collection.getAdmins(this.collectionId);2828 }28292830 async getAllowList() {2831 return await this.helper.collection.getAllowList(this.collectionId);2832 }28332834 async getEffectiveLimits() {2835 return await this.helper.collection.getEffectiveLimits(this.collectionId);2836 }28372838 async getProperties(propertyKeys?: string[] | null) {2839 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2840 }28412842 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2843 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2844 }28452846 async getOptions() {2847 return await this.helper.collection.getCollectionOptions(this.collectionId);2848 }28492850 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2851 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2852 }28532854 async confirmSponsorship(signer: TSigner) {2855 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2856 }28572858 async removeSponsor(signer: TSigner) {2859 return await this.helper.collection.removeSponsor(signer, this.collectionId);2860 }28612862 async setLimits(signer: TSigner, limits: ICollectionLimits) {2863 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2864 }28652866 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2867 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2868 }28692870 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2871 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2872 }28732874 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2875 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2876 }28772878 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2879 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2880 }28812882 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2883 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2884 }28852886 async setProperties(signer: TSigner, properties: IProperty[]) {2887 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2888 }28892890 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2891 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2892 }28932894 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2895 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2896 }28972898 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2899 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2900 }29012902 async disableNesting(signer: TSigner) {2903 return await this.helper.collection.disableNesting(signer, this.collectionId);2904 }29052906 async burn(signer: TSigner) {2907 return await this.helper.collection.burn(signer, this.collectionId);2908 }29092910 scheduleAt<T extends UniqueHelper>(2911 scheduledId: string,2912 executionBlockNumber: number,2913 options: ISchedulerOptions = {},2914 ) {2915 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2916 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2917 }29182919 scheduleAfter<T extends UniqueHelper>(2920 scheduledId: string,2921 blocksBeforeExecution: number,2922 options: ISchedulerOptions = {},2923 ) {2924 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2925 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2926 }29272928 getSudo<T extends UniqueHelper>() {2929 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2930 }2931}293229332934export class UniqueNFTCollection extends UniqueBaseCollection {2935 getTokenObject(tokenId: number) {2936 return new UniqueNFToken(tokenId, this);2937 }29382939 async getTokensByAddress(addressObj: ICrossAccountId) {2940 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2941 }29422943 async getToken(tokenId: number, blockHashAt?: string) {2944 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2945 }29462947 async getTokenOwner(tokenId: number, blockHashAt?: string) {2948 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2949 }29502951 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2952 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2953 }29542955 async getTokenChildren(tokenId: number, blockHashAt?: string) {2956 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2957 }29582959 async getPropertyPermissions(propertyKeys: string[] | null = null) {2960 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2961 }29622963 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2964 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2965 }29662967 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2968 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2969 }29702971 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2972 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2973 }29742975 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2976 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2977 }29782979 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2980 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2981 }29822983 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2984 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2985 }29862987 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2988 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2989 }29902991 async burnToken(signer: TSigner, tokenId: number) {2992 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2993 }29942995 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2996 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2997 }29982999 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3000 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3001 }30023003 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3004 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3005 }30063007 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3008 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3009 }30103011 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3012 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3013 }30143015 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3016 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3017 }30183019 scheduleAt<T extends UniqueHelper>(3020 scheduledId: string,3021 executionBlockNumber: number,3022 options: ISchedulerOptions = {},3023 ) {3024 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3025 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3026 }30273028 scheduleAfter<T extends UniqueHelper>(3029 scheduledId: string,3030 blocksBeforeExecution: number,3031 options: ISchedulerOptions = {},3032 ) {3033 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3034 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3035 }30363037 getSudo<T extends UniqueHelper>() {3038 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3039 }3040}304130423043export class UniqueRFTCollection extends UniqueBaseCollection {3044 getTokenObject(tokenId: number) {3045 return new UniqueRFToken(tokenId, this);3046 }30473048 async getToken(tokenId: number, blockHashAt?: string) {3049 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3050 }30513052 async getTokensByAddress(addressObj: ICrossAccountId) {3053 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3054 }30553056 async getTop10TokenOwners(tokenId: number) {3057 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3058 }30593060 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3061 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3062 }30633064 async getTokenTotalPieces(tokenId: number) {3065 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3066 }30673068 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3069 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3070 }30713072 async getPropertyPermissions(propertyKeys: string[] | null = null) {3073 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3074 }30753076 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3077 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3078 }30793080 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3081 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3082 }30833084 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3085 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3086 }30873088 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3089 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3090 }30913092 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3093 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3094 }30953096 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3097 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3098 }30993100 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3101 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3102 }31033104 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3105 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3106 }31073108 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3109 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3110 }31113112 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3113 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3114 }31153116 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3117 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3118 }31193120 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3121 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3122 }31233124 scheduleAt<T extends UniqueHelper>(3125 scheduledId: string,3126 executionBlockNumber: number,3127 options: ISchedulerOptions = {},3128 ) {3129 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3130 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3131 }31323133 scheduleAfter<T extends UniqueHelper>(3134 scheduledId: string,3135 blocksBeforeExecution: number,3136 options: ISchedulerOptions = {},3137 ) {3138 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3139 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3140 }31413142 getSudo<T extends UniqueHelper>() {3143 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3144 }3145}314631473148export class UniqueFTCollection extends UniqueBaseCollection {3149 async getBalance(addressObj: ICrossAccountId) {3150 return await this.helper.ft.getBalance(this.collectionId, addressObj);3151 }31523153 async getTotalPieces() {3154 return await this.helper.ft.getTotalPieces(this.collectionId);3155 }31563157 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3158 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3159 }31603161 async getTop10Owners() {3162 return await this.helper.ft.getTop10Owners(this.collectionId);3163 }31643165 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3166 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3167 }31683169 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3170 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3171 }31723173 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3174 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3175 }31763177 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3178 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3179 }31803181 async burnTokens(signer: TSigner, amount=1n) {3182 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3183 }31843185 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3186 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3187 }31883189 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3190 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3191 }31923193 scheduleAt<T extends UniqueHelper>(3194 scheduledId: string,3195 executionBlockNumber: number,3196 options: ISchedulerOptions = {},3197 ) {3198 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3199 return new UniqueFTCollection(this.collectionId, scheduledHelper);3200 }32013202 scheduleAfter<T extends UniqueHelper>(3203 scheduledId: string,3204 blocksBeforeExecution: number,3205 options: ISchedulerOptions = {},3206 ) {3207 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3208 return new UniqueFTCollection(this.collectionId, scheduledHelper);3209 }32103211 getSudo<T extends UniqueHelper>() {3212 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3213 }3214}321532163217export class UniqueBaseToken {3218 collection: UniqueNFTCollection | UniqueRFTCollection;3219 collectionId: number;3220 tokenId: number;32213222 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3223 this.collection = collection;3224 this.collectionId = collection.collectionId;3225 this.tokenId = tokenId;3226 }32273228 async getNextSponsored(addressObj: ICrossAccountId) {3229 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3230 }32313232 async getProperties(propertyKeys?: string[] | null) {3233 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3234 }32353236 async setProperties(signer: TSigner, properties: IProperty[]) {3237 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3238 }32393240 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3241 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3242 }32433244 async doesExist() {3245 return await this.collection.doesTokenExist(this.tokenId);3246 }32473248 nestingAccount() {3249 return this.collection.helper.util.getTokenAccount(this);3250 }32513252 scheduleAt<T extends UniqueHelper>(3253 scheduledId: string,3254 executionBlockNumber: number,3255 options: ISchedulerOptions = {},3256 ) {3257 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3258 return new UniqueBaseToken(this.tokenId, scheduledCollection);3259 }32603261 scheduleAfter<T extends UniqueHelper>(3262 scheduledId: string,3263 blocksBeforeExecution: number,3264 options: ISchedulerOptions = {},3265 ) {3266 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3267 return new UniqueBaseToken(this.tokenId, scheduledCollection);3268 }32693270 getSudo<T extends UniqueHelper>() {3271 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3272 }3273}327432753276export class UniqueNFToken extends UniqueBaseToken {3277 collection: UniqueNFTCollection;32783279 constructor(tokenId: number, collection: UniqueNFTCollection) {3280 super(tokenId, collection);3281 this.collection = collection;3282 }32833284 async getData(blockHashAt?: string) {3285 return await this.collection.getToken(this.tokenId, blockHashAt);3286 }32873288 async getOwner(blockHashAt?: string) {3289 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3290 }32913292 async getTopmostOwner(blockHashAt?: string) {3293 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3294 }32953296 async getChildren(blockHashAt?: string) {3297 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3298 }32993300 async nest(signer: TSigner, toTokenObj: IToken) {3301 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3302 }33033304 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3305 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3306 }33073308 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3309 return await this.collection.transferToken(signer, this.tokenId, addressObj);3310 }33113312 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3313 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3314 }33153316 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3317 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3318 }33193320 async isApproved(toAddressObj: ICrossAccountId) {3321 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3322 }33233324 async burn(signer: TSigner) {3325 return await this.collection.burnToken(signer, this.tokenId);3326 }33273328 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3329 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3330 }33313332 scheduleAt<T extends UniqueHelper>(3333 scheduledId: string,3334 executionBlockNumber: number,3335 options: ISchedulerOptions = {},3336 ) {3337 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3338 return new UniqueNFToken(this.tokenId, scheduledCollection);3339 }33403341 scheduleAfter<T extends UniqueHelper>(3342 scheduledId: string,3343 blocksBeforeExecution: number,3344 options: ISchedulerOptions = {},3345 ) {3346 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3347 return new UniqueNFToken(this.tokenId, scheduledCollection);3348 }33493350 getSudo<T extends UniqueHelper>() {3351 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3352 }3353}33543355export class UniqueRFToken extends UniqueBaseToken {3356 collection: UniqueRFTCollection;33573358 constructor(tokenId: number, collection: UniqueRFTCollection) {3359 super(tokenId, collection);3360 this.collection = collection;3361 }33623363 async getData(blockHashAt?: string) {3364 return await this.collection.getToken(this.tokenId, blockHashAt);3365 }33663367 async getTop10Owners() {3368 return await this.collection.getTop10TokenOwners(this.tokenId);3369 }33703371 async getBalance(addressObj: ICrossAccountId) {3372 return await this.collection.getTokenBalance(this.tokenId, addressObj);3373 }33743375 async getTotalPieces() {3376 return await this.collection.getTokenTotalPieces(this.tokenId);3377 }33783379 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3380 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3381 }33823383 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3384 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3385 }33863387 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3388 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3389 }33903391 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3392 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3393 }33943395 async repartition(signer: TSigner, amount: bigint) {3396 return await this.collection.repartitionToken(signer, this.tokenId, amount);3397 }33983399 async burn(signer: TSigner, amount=1n) {3400 return await this.collection.burnToken(signer, this.tokenId, amount);3401 }34023403 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3404 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3405 }34063407 scheduleAt<T extends UniqueHelper>(3408 scheduledId: string,3409 executionBlockNumber: number,3410 options: ISchedulerOptions = {},3411 ) {3412 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3413 return new UniqueRFToken(this.tokenId, scheduledCollection);3414 }34153416 scheduleAfter<T extends UniqueHelper>(3417 scheduledId: string,3418 blocksBeforeExecution: number,3419 options: ISchedulerOptions = {},3420 ) {3421 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3422 return new UniqueRFToken(this.tokenId, scheduledCollection);3423 }34243425 getSudo<T extends UniqueHelper>() {3426 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3427 }3428}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata, IEthCrossAccountId} from './types';13import {hexToU8a} from '@polkadot/util/hex';14import {u8aConcat} from '@polkadot/util/u8a';1516export class CrossAccountId implements ICrossAccountId {17 Substrate?: TSubstrateAccount;18 Ethereum?: TEthereumAccount;1920 constructor(account: ICrossAccountId) {21 if (account.Substrate) this.Substrate = account.Substrate;22 if (account.Ethereum) this.Ethereum = account.Ethereum;23 }2425 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {26 switch (domain) {27 case 'Substrate': return new CrossAccountId({Substrate: account.address});28 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();29 }30 }3132 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {33 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});34 }3536 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {37 return encodeAddress(decodeAddress(address), ss58Format);38 }3940 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {41 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});42 }43 44 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {45 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);46 return this;47 }4849 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {50 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));51 }5253 toEthereum(): CrossAccountId {54 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});55 return this;56 }5758 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {59 return evmToAddress(address, ss58Format);60 }6162 toSubstrate(ss58Format?: number): CrossAccountId {63 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});64 return this;65 }66 67 toLowerCase(): CrossAccountId {68 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();69 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();70 return this;71 }72}7374const nesting = {75 toChecksumAddress(address: string): string {76 if (typeof address === 'undefined') return '';7778 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7980 address = address.toLowerCase().replace(/^0x/i,'');81 const addressHash = keccakAsHex(address).replace(/^0x/i,'');82 const checksumAddress = ['0x'];8384 for (let i = 0; i < address.length; i++) {85 // If ith character is 8 to f then make it uppercase86 if (parseInt(addressHash[i], 16) > 7) {87 checksumAddress.push(address[i].toUpperCase());88 } else {89 checksumAddress.push(address[i]);90 }91 }92 return checksumAddress.join('');93 },94 tokenIdToAddress(collectionId: number, tokenId: number) {95 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);96 },97};9899class UniqueUtil {100 static transactionStatus = {101 NOT_READY: 'NotReady',102 FAIL: 'Fail',103 SUCCESS: 'Success',104 };105106 static chainLogType = {107 EXTRINSIC: 'extrinsic',108 RPC: 'rpc',109 };110111 static getTokenAccount(token: IToken): CrossAccountId {112 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});113 }114115 static getTokenAddress(token: IToken): string {116 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);117 }118119 static getDefaultLogger(): ILogger {120 return {121 log(msg: any, level = 'INFO') {122 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));123 },124 level: {125 ERROR: 'ERROR',126 WARNING: 'WARNING',127 INFO: 'INFO',128 },129 };130 }131132 static vec2str(arr: string[] | number[]) {133 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');134 }135136 static str2vec(string: string) {137 if (typeof string !== 'string') return string;138 return Array.from(string).map(x => x.charCodeAt(0));139 }140141 static fromSeed(seed: string, ss58Format = 42) {142 const keyring = new Keyring({type: 'sr25519', ss58Format});143 return keyring.addFromUri(seed);144 }145146 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {147 if (creationResult.status !== this.transactionStatus.SUCCESS) {148 throw Error('Unable to create collection!');149 }150151 let collectionId = null;152 creationResult.result.events.forEach(({event: {data, method, section}}) => {153 if ((section === 'common') && (method === 'CollectionCreated')) {154 collectionId = parseInt(data[0].toString(), 10);155 }156 });157158 if (collectionId === null) {159 throw Error('No CollectionCreated event was found!');160 }161162 return collectionId;163 }164165 static extractTokensFromCreationResult(creationResult: ITransactionResult): {166 success: boolean, 167 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],168 } {169 if (creationResult.status !== this.transactionStatus.SUCCESS) {170 throw Error('Unable to create tokens!');171 }172 let success = false;173 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];174 creationResult.result.events.forEach(({event: {data, method, section}}) => {175 if (method === 'ExtrinsicSuccess') {176 success = true;177 } else if ((section === 'common') && (method === 'ItemCreated')) {178 tokens.push({179 collectionId: parseInt(data[0].toString(), 10),180 tokenId: parseInt(data[1].toString(), 10),181 owner: data[2].toHuman(),182 amount: data[3].toBigInt(),183 });184 }185 });186 return {success, tokens};187 }188189 static extractTokensFromBurnResult(burnResult: ITransactionResult): {190 success: boolean, 191 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],192 } {193 if (burnResult.status !== this.transactionStatus.SUCCESS) {194 throw Error('Unable to burn tokens!');195 }196 let success = false;197 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];198 burnResult.result.events.forEach(({event: {data, method, section}}) => {199 if (method === 'ExtrinsicSuccess') {200 success = true;201 } else if ((section === 'common') && (method === 'ItemDestroyed')) {202 tokens.push({203 collectionId: parseInt(data[0].toString(), 10),204 tokenId: parseInt(data[1].toString(), 10),205 owner: data[2].toHuman(),206 amount: data[3].toBigInt(),207 });208 }209 });210 return {success, tokens};211 }212213 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {214 let eventId = null;215 events.forEach(({event: {data, method, section}}) => {216 if ((section === expectedSection) && (method === expectedMethod)) {217 eventId = parseInt(data[0].toString(), 10);218 }219 });220221 if (eventId === null) {222 throw Error(`No ${expectedMethod} event was found!`);223 }224 return eventId === collectionId;225 }226227 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {228 const normalizeAddress = (address: string | ICrossAccountId) => {229 if(typeof address === 'string') return address;230 const obj = {} as any;231 Object.keys(address).forEach(k => {232 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];233 });234 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);235 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();236 return address;237 };238 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;239 events.forEach(({event: {data, method, section}}) => {240 if ((section === 'common') && (method === 'Transfer')) {241 const hData = (data as any).toJSON();242 transfer = {243 collectionId: hData[0],244 tokenId: hData[1],245 from: normalizeAddress(hData[2]),246 to: normalizeAddress(hData[3]),247 amount: BigInt(hData[4]),248 };249 }250 });251 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;252 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);253 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);254 isSuccess = isSuccess && amount === transfer.amount;255 return isSuccess;256 }257258 static bigIntToDecimals(number: bigint, decimals = 18) {259 const numberStr = number.toString();260 const dotPos = numberStr.length - decimals;261 262 if (dotPos <= 0) {263 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;264 } else {265 const intPart = numberStr.substring(0, dotPos);266 const fractPart = numberStr.substring(dotPos);267 return intPart + '.' + fractPart;268 }269 }270}271272class UniqueEventHelper {273 private static extractIndex(index: any): [number, number] | string {274 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];275 return index.toJSON();276 }277278 private static extractSub(data: any, subTypes: any): {[key: string]: any} {279 let obj: any = {};280 let index = 0;281282 if (data.entries) {283 for(const [key, value] of data.entries()) {284 obj[key] = this.extractData(value, subTypes[index]);285 index++;286 }287 } else obj = data.toJSON();288289 return obj;290 }291 292 private static extractData(data: any, type: any): any {293 if(!type) return data.toHuman();294 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();295 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();296 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);297 return data.toHuman();298 }299300 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {301 const parsedEvents: IEvent[] = [];302303 events.forEach((record) => {304 const {event, phase} = record;305 const types = event.typeDef;306307 const eventData: IEvent = {308 section: event.section.toString(),309 method: event.method.toString(),310 index: this.extractIndex(event.index),311 data: [],312 phase: phase.toJSON(),313 };314315 event.data.forEach((val: any, index: number) => {316 eventData.data.push(this.extractData(val, types[index]));317 });318319 parsedEvents.push(eventData);320 });321322 return parsedEvents;323 }324}325326export class ChainHelperBase {327 helperBase: any;328329 transactionStatus = UniqueUtil.transactionStatus;330 chainLogType = UniqueUtil.chainLogType;331 util: typeof UniqueUtil;332 eventHelper: typeof UniqueEventHelper;333 logger: ILogger;334 api: ApiPromise | null;335 forcedNetwork: TNetworks | null;336 network: TNetworks | null;337 chainLog: IUniqueHelperLog[];338 children: ChainHelperBase[];339 address: AddressGroup;340 chain: ChainGroup;341342 constructor(logger?: ILogger, helperBase?: any) {343 this.helperBase = helperBase;344345 this.util = UniqueUtil;346 this.eventHelper = UniqueEventHelper;347 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();348 this.logger = logger;349 this.api = null;350 this.forcedNetwork = null;351 this.network = null;352 this.chainLog = [];353 this.children = [];354 this.address = new AddressGroup(this);355 this.chain = new ChainGroup(this);356 }357358 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {359 Object.setPrototypeOf(helperCls.prototype, this);360 const newHelper = new helperCls(this.logger, options);361362 newHelper.api = this.api;363 newHelper.network = this.network;364 newHelper.forceNetwork = this.forceNetwork;365366 this.children.push(newHelper);367368 return newHelper;369 }370371 getApi(): ApiPromise {372 if(this.api === null) throw Error('API not initialized');373 return this.api;374 }375376 clearChainLog(): void {377 this.chainLog = [];378 }379380 forceNetwork(value: TNetworks): void {381 this.forcedNetwork = value;382 }383384 async connect(wsEndpoint: string, listeners?: IApiListeners) {385 if (this.api !== null) throw Error('Already connected');386 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);387 this.api = api;388 this.network = network;389 }390391 async disconnect() {392 for (const child of this.children) {393 child.clearApi();394 }395396 if (this.api === null) return;397 await this.api.disconnect();398 this.clearApi();399 }400401 clearApi() {402 this.api = null;403 this.network = null;404 }405406 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {407 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;408 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];409410 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;411412 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;413 return 'opal';414 }415416 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {417 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});418 await api.isReady;419420 const network = await this.detectNetwork(api);421422 await api.disconnect();423424 return network;425 }426427 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{428 api: ApiPromise;429 network: TNetworks;430 }> {431 if(typeof network === 'undefined' || network === null) network = 'opal';432 const supportedRPC = {433 opal: {434 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,435 },436 quartz: {437 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,438 },439 unique: {440 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,441 },442 rococo: {},443 westend: {},444 moonbeam: {},445 moonriver: {},446 acala: {},447 karura: {},448 westmint: {},449 };450 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);451 const rpc = supportedRPC[network];452453 // TODO: investigate how to replace rpc in runtime454 // api._rpcCore.addUserInterfaces(rpc);455456 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});457458 await api.isReadyOrError;459460 if (typeof listeners === 'undefined') listeners = {};461 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {462 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;463 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);464 }465466 return {api, network};467 }468469 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {470 const {events, status} = data;471 if (status.isReady) {472 return this.transactionStatus.NOT_READY;473 }474 if (status.isBroadcast) {475 return this.transactionStatus.NOT_READY;476 }477 if (status.isInBlock || status.isFinalized) {478 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');479 if (errors.length > 0) {480 return this.transactionStatus.FAIL;481 }482 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {483 return this.transactionStatus.SUCCESS;484 }485 }486487 return this.transactionStatus.FAIL;488 }489490 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {491 const sign = (callback: any) => {492 if(options !== null) return transaction.signAndSend(sender, options, callback);493 return transaction.signAndSend(sender, callback);494 };495 // eslint-disable-next-line no-async-promise-executor496 return new Promise(async (resolve, reject) => {497 try {498 const unsub = await sign((result: any) => {499 const status = this.getTransactionStatus(result);500501 if (status === this.transactionStatus.SUCCESS) {502 this.logger.log(`${label} successful`);503 unsub();504 resolve({result, status});505 } else if (status === this.transactionStatus.FAIL) {506 let moduleError = null;507508 if (result.hasOwnProperty('dispatchError')) {509 const dispatchError = result['dispatchError'];510511 if (dispatchError) {512 if (dispatchError.isModule) {513 const modErr = dispatchError.asModule;514 const errorMeta = dispatchError.registry.findMetaError(modErr);515516 moduleError = `${errorMeta.section}.${errorMeta.name}`;517 } else {518 moduleError = dispatchError.toHuman();519 }520 } else {521 this.logger.log(result, this.logger.level.ERROR);522 }523 }524525 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);526 unsub();527 reject({status, moduleError, result});528 }529 });530 } catch (e) {531 this.logger.log(e, this.logger.level.ERROR);532 reject(e);533 }534 });535 }536537 constructApiCall(apiCall: string, params: any[]) {538 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);539 let call = this.getApi() as any;540 for(const part of apiCall.slice(4).split('.')) {541 call = call[part];542 }543 return call(...params);544 }545546 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {547 if(this.api === null) throw Error('API not initialized');548 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);549550 const startTime = (new Date()).getTime();551 let result: ITransactionResult;552 let events: IEvent[] = [];553 try {554 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;555 events = this.eventHelper.extractEvents(result.result.events);556 }557 catch(e) {558 if(!(e as object).hasOwnProperty('status')) throw e;559 result = e as ITransactionResult;560 }561562 const endTime = (new Date()).getTime();563564 const log = {565 executedAt: endTime,566 executionTime: endTime - startTime,567 type: this.chainLogType.EXTRINSIC,568 status: result.status,569 call: extrinsic,570 signer: this.getSignerAddress(sender),571 params,572 } as IUniqueHelperLog;573574 if(result.status !== this.transactionStatus.SUCCESS) {575 if (result.moduleError) log.moduleError = result.moduleError;576 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;577 }578 if(events.length > 0) log.events = events;579580 this.chainLog.push(log);581582 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {583 if (result.moduleError) throw Error(`${result.moduleError}`);584 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));585 }586 return result;587 }588589 async callRpc(rpc: string, params?: any[]) {590 if(typeof params === 'undefined') params = [];591 if(this.api === null) throw Error('API not initialized');592 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);593594 const startTime = (new Date()).getTime();595 let result;596 let error = null;597 const log = {598 type: this.chainLogType.RPC,599 call: rpc,600 params,601 } as IUniqueHelperLog;602603 try {604 result = await this.constructApiCall(rpc, params);605 }606 catch(e) {607 error = e;608 }609610 const endTime = (new Date()).getTime();611612 log.executedAt = endTime;613 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';614 log.executionTime = endTime - startTime;615616 this.chainLog.push(log);617618 if(error !== null) throw error;619620 return result;621 }622623 getSignerAddress(signer: IKeyringPair | string): string {624 if(typeof signer === 'string') return signer;625 return signer.address;626 }627628 fetchAllPalletNames(): string[] {629 if(this.api === null) throw Error('API not initialized');630 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());631 }632633 fetchMissingPalletNames(requiredPallets: string[]): string[] {634 const palletNames = this.fetchAllPalletNames();635 return requiredPallets.filter(p => !palletNames.includes(p));636 }637}638639640class HelperGroup<T extends ChainHelperBase> {641 helper: T;642643 constructor(uniqueHelper: T) {644 this.helper = uniqueHelper;645 }646}647648649class CollectionGroup extends HelperGroup<UniqueHelper> {650 /**651 * Get number of blocks when sponsored transaction is available.652 *653 * @param collectionId ID of collection654 * @param tokenId ID of token655 * @param addressObj address for which the sponsorship is checked656 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});657 * @returns number of blocks or null if sponsorship hasn't been set658 */659 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {660 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();661 }662663 /**664 * Get the number of created collections.665 *666 * @returns number of created collections667 */668 async getTotalCount(): Promise<number> {669 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();670 }671672 /**673 * Get information about the collection with additional data,674 * including the number of tokens it contains, its administrators,675 * the normalized address of the collection's owner, and decoded name and description.676 *677 * @param collectionId ID of collection678 * @example await getData(2)679 * @returns collection information object680 */681 async getData(collectionId: number): Promise<{682 id: number;683 name: string;684 description: string;685 tokensCount: number;686 admins: CrossAccountId[];687 normalizedOwner: TSubstrateAccount;688 raw: any689 } | null> {690 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);691 const humanCollection = collection.toHuman(), collectionData = {692 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],693 raw: humanCollection,694 } as any, jsonCollection = collection.toJSON();695 if (humanCollection === null) return null;696 collectionData.raw.limits = jsonCollection.limits;697 collectionData.raw.permissions = jsonCollection.permissions;698 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);699 for (const key of ['name', 'description']) {700 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);701 }702703 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))704 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)705 : 0;706 collectionData.admins = await this.getAdmins(collectionId);707708 return collectionData;709 }710711 /**712 * Get the addresses of the collection's administrators, optionally normalized.713 *714 * @param collectionId ID of collection715 * @param normalize whether to normalize the addresses to the default ss58 format716 * @example await getAdmins(1)717 * @returns array of administrators718 */719 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {720 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();721722 return normalize723 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())724 : admins;725 }726727 /**728 * Get the addresses added to the collection allow-list, optionally normalized.729 * @param collectionId ID of collection730 * @param normalize whether to normalize the addresses to the default ss58 format731 * @example await getAllowList(1)732 * @returns array of allow-listed addresses733 */734 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {735 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();736 return normalize737 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())738 : allowListed;739 }740741 /**742 * Get the effective limits of the collection instead of null for default values743 *744 * @param collectionId ID of collection745 * @example await getEffectiveLimits(2)746 * @returns object of collection limits747 */748 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {749 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();750 }751752 /**753 * Burns the collection if the signer has sufficient permissions and collection is empty.754 *755 * @param signer keyring of signer756 * @param collectionId ID of collection757 * @example await helper.collection.burn(aliceKeyring, 3);758 * @returns ```true``` if extrinsic success, otherwise ```false```759 */760 async burn(signer: TSigner, collectionId: number): Promise<boolean> {761 const result = await this.helper.executeExtrinsic(762 signer,763 'api.tx.unique.destroyCollection', [collectionId],764 true,765 );766767 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');768 }769770 /**771 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.772 *773 * @param signer keyring of signer774 * @param collectionId ID of collection775 * @param sponsorAddress Sponsor substrate address776 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")777 * @returns ```true``` if extrinsic success, otherwise ```false```778 */779 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {780 const result = await this.helper.executeExtrinsic(781 signer,782 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],783 true,784 );785786 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');787 }788789 /**790 * Confirms consent to sponsor the collection on behalf of the signer.791 *792 * @param signer keyring of signer793 * @param collectionId ID of collection794 * @example confirmSponsorship(aliceKeyring, 10)795 * @returns ```true``` if extrinsic success, otherwise ```false```796 */797 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {798 const result = await this.helper.executeExtrinsic(799 signer,800 'api.tx.unique.confirmSponsorship', [collectionId],801 true,802 );803804 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');805 }806807 /**808 * Removes the sponsor of a collection, regardless if it consented or not.809 *810 * @param signer keyring of signer811 * @param collectionId ID of collection812 * @example removeSponsor(aliceKeyring, 10)813 * @returns ```true``` if extrinsic success, otherwise ```false```814 */815 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {816 const result = await this.helper.executeExtrinsic(817 signer,818 'api.tx.unique.removeCollectionSponsor', [collectionId],819 true,820 );821822 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');823 }824825 /**826 * Sets the limits of the collection. At least one limit must be specified for a correct call.827 *828 * @param signer keyring of signer829 * @param collectionId ID of collection830 * @param limits collection limits object831 * @example832 * await setLimits(833 * aliceKeyring,834 * 10,835 * {836 * sponsorTransferTimeout: 0,837 * ownerCanDestroy: false838 * }839 * )840 * @returns ```true``` if extrinsic success, otherwise ```false```841 */842 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {843 const result = await this.helper.executeExtrinsic(844 signer,845 'api.tx.unique.setCollectionLimits', [collectionId, limits],846 true,847 );848849 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');850 }851852 /**853 * Changes the owner of the collection to the new Substrate address.854 *855 * @param signer keyring of signer856 * @param collectionId ID of collection857 * @param ownerAddress substrate address of new owner858 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")859 * @returns ```true``` if extrinsic success, otherwise ```false```860 */861 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {862 const result = await this.helper.executeExtrinsic(863 signer,864 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],865 true,866 );867868 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');869 }870871 /**872 * Adds a collection administrator.873 *874 * @param signer keyring of signer875 * @param collectionId ID of collection876 * @param adminAddressObj Administrator address (substrate or ethereum)877 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})878 * @returns ```true``` if extrinsic success, otherwise ```false```879 */880 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {881 const result = await this.helper.executeExtrinsic(882 signer,883 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],884 true,885 );886887 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');888 }889890 /**891 * Removes a collection administrator.892 *893 * @param signer keyring of signer894 * @param collectionId ID of collection895 * @param adminAddressObj Administrator address (substrate or ethereum)896 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})897 * @returns ```true``` if extrinsic success, otherwise ```false```898 */899 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {900 const result = await this.helper.executeExtrinsic(901 signer,902 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],903 true,904 );905906 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');907 }908909 /**910 * Check if user is in allow list.911 * 912 * @param collectionId ID of collection913 * @param user Account to check914 * @example await getAdmins(1)915 * @returns is user in allow list916 */917 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {918 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();919 }920921 /**922 * Adds an address to allow list923 * @param signer keyring of signer924 * @param collectionId ID of collection925 * @param addressObj address to add to the allow list926 * @returns ```true``` if extrinsic success, otherwise ```false```927 */928 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {929 const result = await this.helper.executeExtrinsic(930 signer,931 'api.tx.unique.addToAllowList', [collectionId, addressObj],932 true,933 );934935 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');936 }937938 /**939 * Removes an address from allow list940 *941 * @param signer keyring of signer942 * @param collectionId ID of collection943 * @param addressObj address to remove from the allow list944 * @returns ```true``` if extrinsic success, otherwise ```false```945 */946 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {947 const result = await this.helper.executeExtrinsic(948 signer,949 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],950 true,951 );952953 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');954 }955956 /**957 * Sets onchain permissions for selected collection.958 *959 * @param signer keyring of signer960 * @param collectionId ID of collection961 * @param permissions collection permissions object962 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});963 * @returns ```true``` if extrinsic success, otherwise ```false```964 */965 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {966 const result = await this.helper.executeExtrinsic(967 signer,968 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],969 true,970 );971972 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');973 }974975 /**976 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.977 *978 * @param signer keyring of signer979 * @param collectionId ID of collection980 * @param permissions nesting permissions object981 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});982 * @returns ```true``` if extrinsic success, otherwise ```false```983 */984 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {985 return await this.setPermissions(signer, collectionId, {nesting: permissions});986 }987988 /**989 * Disables nesting for selected collection.990 *991 * @param signer keyring of signer992 * @param collectionId ID of collection993 * @example disableNesting(aliceKeyring, 10);994 * @returns ```true``` if extrinsic success, otherwise ```false```995 */996 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {997 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});998 }9991000 /**1001 * Sets onchain properties to the collection.1002 *1003 * @param signer keyring of signer1004 * @param collectionId ID of collection1005 * @param properties array of property objects1006 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1007 * @returns ```true``` if extrinsic success, otherwise ```false```1008 */1009 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1010 const result = await this.helper.executeExtrinsic(1011 signer,1012 'api.tx.unique.setCollectionProperties', [collectionId, properties],1013 true,1014 );10151016 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1017 }10181019 /**1020 * Get collection properties.1021 * 1022 * @param collectionId ID of collection1023 * @param propertyKeys optionally filter the returned properties to only these keys1024 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1025 * @returns array of key-value pairs1026 */1027 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1028 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1029 }10301031 async getCollectionOptions(collectionId: number) {1032 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1033 }10341035 /**1036 * Deletes onchain properties from the collection.1037 *1038 * @param signer keyring of signer1039 * @param collectionId ID of collection1040 * @param propertyKeys array of property keys to delete1041 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1042 * @returns ```true``` if extrinsic success, otherwise ```false```1043 */1044 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1045 const result = await this.helper.executeExtrinsic(1046 signer,1047 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1048 true,1049 );10501051 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1052 }10531054 /**1055 * Changes the owner of the token.1056 *1057 * @param signer keyring of signer1058 * @param collectionId ID of collection1059 * @param tokenId ID of token1060 * @param addressObj address of a new owner1061 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1062 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1063 * @returns true if the token success, otherwise false1064 */1065 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1066 const result = await this.helper.executeExtrinsic(1067 signer,1068 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1069 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1070 );10711072 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1073 }10741075 /**1076 *1077 * Change ownership of a token(s) on behalf of the owner.1078 *1079 * @param signer keyring of signer1080 * @param collectionId ID of collection1081 * @param tokenId ID of token1082 * @param fromAddressObj address on behalf of which the token will be sent1083 * @param toAddressObj new token owner1084 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1085 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1086 * @returns true if the token success, otherwise false1087 */1088 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1089 const result = await this.helper.executeExtrinsic(1090 signer,1091 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1092 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1093 );1094 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1095 }10961097 /**1098 *1099 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1100 *1101 * @param signer keyring of signer1102 * @param collectionId ID of collection1103 * @param tokenId ID of token1104 * @param amount amount of tokens to be burned. For NFT must be set to 1n1105 * @example burnToken(aliceKeyring, 10, 5);1106 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1107 */1108 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1109 const burnResult = await this.helper.executeExtrinsic(1110 signer,1111 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1112 true, // `Unable to burn token for ${label}`,1113 );1114 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1115 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1116 return burnedTokens.success;1117 }11181119 /**1120 * Destroys a concrete instance of NFT on behalf of the owner1121 *1122 * @param signer keyring of signer1123 * @param collectionId ID of collection1124 * @param tokenId ID of token1125 * @param fromAddressObj address on behalf of which the token will be burnt1126 * @param amount amount of tokens to be burned. For NFT must be set to 1n1127 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1128 * @returns ```true``` if extrinsic success, otherwise ```false```1129 */1130 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1131 const burnResult = await this.helper.executeExtrinsic(1132 signer,1133 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1134 true, // `Unable to burn token from for ${label}`,1135 );1136 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1137 return burnedTokens.success && burnedTokens.tokens.length > 0;1138 }11391140 /**1141 * Set, change, or remove approved address to transfer the ownership of the NFT.1142 *1143 * @param signer keyring of signer1144 * @param collectionId ID of collection1145 * @param tokenId ID of token1146 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1147 * @param amount amount of token to be approved. For NFT must be set to 1n1148 * @returns ```true``` if extrinsic success, otherwise ```false```1149 */1150 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1151 const approveResult = await this.helper.executeExtrinsic(1152 signer,1153 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1154 true, // `Unable to approve token for ${label}`,1155 );11561157 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1158 }11591160 /**1161 * Get the amount of token pieces approved to transfer or burn. Normally 0.1162 *1163 * @param collectionId ID of collection1164 * @param tokenId ID of token1165 * @param toAccountObj address which is approved to use token pieces1166 * @param fromAccountObj address which may have allowed the use of its owned tokens1167 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1168 * @returns number of approved to transfer pieces1169 */1170 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1171 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1172 }11731174 /**1175 * Get the last created token ID in a collection1176 *1177 * @param collectionId ID of collection1178 * @example getLastTokenId(10);1179 * @returns id of the last created token1180 */1181 async getLastTokenId(collectionId: number): Promise<number> {1182 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1183 }11841185 /**1186 * Check if token exists1187 *1188 * @param collectionId ID of collection1189 * @param tokenId ID of token1190 * @example doesTokenExist(10, 20);1191 * @returns true if the token exists, otherwise false1192 */1193 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1194 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1195 }1196}11971198class NFTnRFT extends CollectionGroup {1199 /**1200 * Get tokens owned by account1201 *1202 * @param collectionId ID of collection1203 * @param addressObj tokens owner1204 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1205 * @returns array of token ids owned by account1206 */1207 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1208 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1209 }12101211 /**1212 * Get token data1213 *1214 * @param collectionId ID of collection1215 * @param tokenId ID of token1216 * @param propertyKeys optionally filter the token properties to only these keys1217 * @param blockHashAt optionally query the data at some block with this hash1218 * @example getToken(10, 5);1219 * @returns human readable token data1220 */1221 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1222 properties: IProperty[];1223 owner: CrossAccountId;1224 normalizedOwner: CrossAccountId;1225 }| null> {1226 let tokenData;1227 if(typeof blockHashAt === 'undefined') {1228 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1229 }1230 else {1231 if(propertyKeys.length == 0) {1232 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1233 if(!collection) return null;1234 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1235 }1236 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1237 }1238 tokenData = tokenData.toHuman();1239 if (tokenData === null || tokenData.owner === null) return null;1240 const owner = {} as any;1241 for (const key of Object.keys(tokenData.owner)) {1242 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1243 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1244 : tokenData.owner[key];1245 }1246 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1247 return tokenData;1248 }12491250 /**1251 * Set permissions to change token properties1252 *1253 * @param signer keyring of signer1254 * @param collectionId ID of collection1255 * @param permissions permissions to change a property by the collection admin or token owner1256 * @example setTokenPropertyPermissions(1257 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1258 * )1259 * @returns true if extrinsic success otherwise false1260 */1261 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1262 const result = await this.helper.executeExtrinsic(1263 signer,1264 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1265 true,1266 );12671268 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1269 }12701271 /**1272 * Get token property permissions.1273 * 1274 * @param collectionId ID of collection1275 * @param propertyKeys optionally filter the returned property permissions to only these keys1276 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1277 * @returns array of key-permission pairs1278 */1279 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1280 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1281 }12821283 /**1284 * Set token properties1285 *1286 * @param signer keyring of signer1287 * @param collectionId ID of collection1288 * @param tokenId ID of token1289 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1290 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1291 * @returns ```true``` if extrinsic success, otherwise ```false```1292 */1293 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1294 const result = await this.helper.executeExtrinsic(1295 signer,1296 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1297 true,1298 );12991300 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1301 }13021303 /**1304 * Get properties, metadata assigned to a token.1305 * 1306 * @param collectionId ID of collection1307 * @param tokenId ID of token1308 * @param propertyKeys optionally filter the returned properties to only these keys1309 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1310 * @returns array of key-value pairs1311 */1312 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1313 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1314 }13151316 /**1317 * Delete the provided properties of a token1318 * @param signer keyring of signer1319 * @param collectionId ID of collection1320 * @param tokenId ID of token1321 * @param propertyKeys property keys to be deleted1322 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1323 * @returns ```true``` if extrinsic success, otherwise ```false```1324 */1325 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1326 const result = await this.helper.executeExtrinsic(1327 signer,1328 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1329 true,1330 );13311332 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1333 }13341335 /**1336 * Mint new collection1337 *1338 * @param signer keyring of signer1339 * @param collectionOptions basic collection options and properties1340 * @param mode NFT or RFT type of a collection1341 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1342 * @returns object of the created collection1343 */1344 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1345 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1346 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1347 for (const key of ['name', 'description', 'tokenPrefix']) {1348 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1349 }1350 const creationResult = await this.helper.executeExtrinsic(1351 signer,1352 'api.tx.unique.createCollectionEx', [collectionOptions],1353 true, // errorLabel,1354 );1355 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1356 }13571358 getCollectionObject(_collectionId: number): any {1359 return null;1360 }13611362 getTokenObject(_collectionId: number, _tokenId: number): any {1363 return null;1364 }1365}136613671368class NFTGroup extends NFTnRFT {1369 /**1370 * Get collection object1371 * @param collectionId ID of collection1372 * @example getCollectionObject(2);1373 * @returns instance of UniqueNFTCollection1374 */1375 getCollectionObject(collectionId: number): UniqueNFTCollection {1376 return new UniqueNFTCollection(collectionId, this.helper);1377 }13781379 /**1380 * Get token object1381 * @param collectionId ID of collection1382 * @param tokenId ID of token1383 * @example getTokenObject(10, 5);1384 * @returns instance of UniqueNFTToken1385 */1386 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1387 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1388 }13891390 /**1391 * Get token's owner1392 * @param collectionId ID of collection1393 * @param tokenId ID of token1394 * @param blockHashAt optionally query the data at the block with this hash1395 * @example getTokenOwner(10, 5);1396 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1397 */1398 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1399 let owner;1400 if (typeof blockHashAt === 'undefined') {1401 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1402 } else {1403 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1404 }1405 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1406 }14071408 /**1409 * Is token approved to transfer1410 * @param collectionId ID of collection1411 * @param tokenId ID of token1412 * @param toAccountObj address to be approved1413 * @returns ```true``` if extrinsic success, otherwise ```false```1414 */1415 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1416 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1417 }14181419 /**1420 * Changes the owner of the token.1421 *1422 * @param signer keyring of signer1423 * @param collectionId ID of collection1424 * @param tokenId ID of token1425 * @param addressObj address of a new owner1426 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1427 * @returns ```true``` if extrinsic success, otherwise ```false```1428 */1429 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1430 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1431 }14321433 /**1434 *1435 * Change ownership of a NFT on behalf of the owner.1436 *1437 * @param signer keyring of signer1438 * @param collectionId ID of collection1439 * @param tokenId ID of token1440 * @param fromAddressObj address on behalf of which the token will be sent1441 * @param toAddressObj new token owner1442 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1443 * @returns ```true``` if extrinsic success, otherwise ```false```1444 */1445 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1446 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1447 }14481449 /**1450 * Recursively find the address that owns the token1451 * @param collectionId ID of collection1452 * @param tokenId ID of token1453 * @param blockHashAt1454 * @example getTokenTopmostOwner(10, 5);1455 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1456 */1457 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1458 let owner;1459 if (typeof blockHashAt === 'undefined') {1460 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1461 } else {1462 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1463 }14641465 if (owner === null) return null;14661467 return owner.toHuman();1468 }14691470 /**1471 * Get tokens nested in the provided token1472 * @param collectionId ID of collection1473 * @param tokenId ID of token1474 * @param blockHashAt optionally query the data at the block with this hash1475 * @example getTokenChildren(10, 5);1476 * @returns tokens whose depth of nesting is <= 51477 */1478 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1479 let children;1480 if(typeof blockHashAt === 'undefined') {1481 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1482 } else {1483 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1484 }14851486 return children.toJSON().map((x: any) => {1487 return {collectionId: x.collection, tokenId: x.token};1488 });1489 }14901491 /**1492 * Nest one token into another1493 * @param signer keyring of signer1494 * @param tokenObj token to be nested1495 * @param rootTokenObj token to be parent1496 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1497 * @returns ```true``` if extrinsic success, otherwise ```false```1498 */1499 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1500 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1501 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1502 if(!result) {1503 throw Error('Unable to nest token!');1504 }1505 return result;1506 }15071508 /**1509 * Remove token from nested state1510 * @param signer keyring of signer1511 * @param tokenObj token to unnest1512 * @param rootTokenObj parent of a token1513 * @param toAddressObj address of a new token owner1514 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1515 * @returns ```true``` if extrinsic success, otherwise ```false```1516 */1517 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1518 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1519 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1520 if(!result) {1521 throw Error('Unable to unnest token!');1522 }1523 return result;1524 }15251526 /**1527 * Mint new collection1528 * @param signer keyring of signer1529 * @param collectionOptions Collection options1530 * @example1531 * mintCollection(aliceKeyring, {1532 * name: 'New',1533 * description: 'New collection',1534 * tokenPrefix: 'NEW',1535 * })1536 * @returns object of the created collection1537 */1538 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1539 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1540 }15411542 /**1543 * Mint new token1544 * @param signer keyring of signer1545 * @param data token data1546 * @returns created token object1547 */1548 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1549 const creationResult = await this.helper.executeExtrinsic(1550 signer,1551 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1552 nft: {1553 properties: data.properties,1554 },1555 }],1556 true,1557 );1558 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1559 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1560 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1561 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1562 }15631564 /**1565 * Mint multiple NFT tokens1566 * @param signer keyring of signer1567 * @param collectionId ID of collection1568 * @param tokens array of tokens with owner and properties1569 * @example1570 * mintMultipleTokens(aliceKeyring, 10, [{1571 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1572 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1573 * },{1574 * owner: {Ethereum: "0x9F0583DbB855d..."},1575 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1576 * }]);1577 * @returns ```true``` if extrinsic success, otherwise ```false```1578 */1579 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1580 const creationResult = await this.helper.executeExtrinsic(1581 signer,1582 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1583 true,1584 );1585 const collection = this.getCollectionObject(collectionId);1586 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1587 }15881589 /**1590 * Mint multiple NFT tokens with one owner1591 * @param signer keyring of signer1592 * @param collectionId ID of collection1593 * @param owner tokens owner1594 * @param tokens array of tokens with owner and properties1595 * @example1596 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1597 * properties: [{1598 * key: "gender",1599 * value: "female",1600 * },{1601 * key: "age",1602 * value: "33",1603 * }],1604 * }]);1605 * @returns array of newly created tokens1606 */1607 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1608 const rawTokens = [];1609 for (const token of tokens) {1610 const raw = {NFT: {properties: token.properties}};1611 rawTokens.push(raw);1612 }1613 const creationResult = await this.helper.executeExtrinsic(1614 signer,1615 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1616 true,1617 );1618 const collection = this.getCollectionObject(collectionId);1619 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1620 }16211622 /**1623 * Set, change, or remove approved address to transfer the ownership of the NFT.1624 *1625 * @param signer keyring of signer1626 * @param collectionId ID of collection1627 * @param tokenId ID of token1628 * @param toAddressObj address to approve1629 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1630 * @returns ```true``` if extrinsic success, otherwise ```false```1631 */1632 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1633 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1634 }1635}163616371638class RFTGroup extends NFTnRFT {1639 /**1640 * Get collection object1641 * @param collectionId ID of collection1642 * @example getCollectionObject(2);1643 * @returns instance of UniqueRFTCollection1644 */1645 getCollectionObject(collectionId: number): UniqueRFTCollection {1646 return new UniqueRFTCollection(collectionId, this.helper);1647 }16481649 /**1650 * Get token object1651 * @param collectionId ID of collection1652 * @param tokenId ID of token1653 * @example getTokenObject(10, 5);1654 * @returns instance of UniqueNFTToken1655 */1656 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1657 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1658 }16591660 /**1661 * Get top 10 token owners with the largest number of pieces1662 * @param collectionId ID of collection1663 * @param tokenId ID of token1664 * @example getTokenTop10Owners(10, 5);1665 * @returns array of top 10 owners1666 */1667 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1668 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1669 }16701671 /**1672 * Get number of pieces owned by address1673 * @param collectionId ID of collection1674 * @param tokenId ID of token1675 * @param addressObj address token owner1676 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1677 * @returns number of pieces ownerd by address1678 */1679 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1680 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1681 }16821683 /**1684 * Transfer pieces of token to another address1685 * @param signer keyring of signer1686 * @param collectionId ID of collection1687 * @param tokenId ID of token1688 * @param addressObj address of a new owner1689 * @param amount number of pieces to be transfered1690 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1691 * @returns ```true``` if extrinsic success, otherwise ```false```1692 */1693 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1694 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1695 }16961697 /**1698 * Change ownership of some pieces of RFT on behalf of the owner.1699 * @param signer keyring of signer1700 * @param collectionId ID of collection1701 * @param tokenId ID of token1702 * @param fromAddressObj address on behalf of which the token will be sent1703 * @param toAddressObj new token owner1704 * @param amount number of pieces to be transfered1705 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1706 * @returns ```true``` if extrinsic success, otherwise ```false```1707 */1708 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1709 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1710 }17111712 /**1713 * Mint new collection1714 * @param signer keyring of signer1715 * @param collectionOptions Collection options1716 * @example1717 * mintCollection(aliceKeyring, {1718 * name: 'New',1719 * description: 'New collection',1720 * tokenPrefix: 'NEW',1721 * })1722 * @returns object of the created collection1723 */1724 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1725 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1726 }17271728 /**1729 * Mint new token1730 * @param signer keyring of signer1731 * @param data token data1732 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1733 * @returns created token object1734 */1735 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1736 const creationResult = await this.helper.executeExtrinsic(1737 signer,1738 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1739 refungible: {1740 pieces: data.pieces,1741 properties: data.properties,1742 },1743 }],1744 true,1745 );1746 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1747 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1748 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1749 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1750 }17511752 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1753 throw Error('Not implemented');1754 const creationResult = await this.helper.executeExtrinsic(1755 signer,1756 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1757 true, // `Unable to mint RFT tokens for ${label}`,1758 );1759 const collection = this.getCollectionObject(collectionId);1760 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1761 }17621763 /**1764 * Mint multiple RFT tokens with one owner1765 * @param signer keyring of signer1766 * @param collectionId ID of collection1767 * @param owner tokens owner1768 * @param tokens array of tokens with properties and pieces1769 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1770 * @returns array of newly created RFT tokens1771 */1772 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1773 const rawTokens = [];1774 for (const token of tokens) {1775 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1776 rawTokens.push(raw);1777 }1778 const creationResult = await this.helper.executeExtrinsic(1779 signer,1780 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1781 true,1782 );1783 const collection = this.getCollectionObject(collectionId);1784 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1785 }17861787 /**1788 * Destroys a concrete instance of RFT.1789 * @param signer keyring of signer1790 * @param collectionId ID of collection1791 * @param tokenId ID of token1792 * @param amount number of pieces to be burnt1793 * @example burnToken(aliceKeyring, 10, 5);1794 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1795 */1796 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1797 return await super.burnToken(signer, collectionId, tokenId, amount);1798 }17991800 /**1801 * Destroys a concrete instance of RFT on behalf of the owner.1802 * @param signer keyring of signer1803 * @param collectionId ID of collection1804 * @param tokenId ID of token1805 * @param fromAddressObj address on behalf of which the token will be burnt1806 * @param amount number of pieces to be burnt1807 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1808 * @returns ```true``` if extrinsic success, otherwise ```false```1809 */1810 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1811 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1812 }18131814 /**1815 * Set, change, or remove approved address to transfer the ownership of the RFT.1816 *1817 * @param signer keyring of signer1818 * @param collectionId ID of collection1819 * @param tokenId ID of token1820 * @param toAddressObj address to approve1821 * @param amount number of pieces to be approved1822 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1823 * @returns true if the token success, otherwise false1824 */1825 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1826 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1827 }18281829 /**1830 * Get total number of pieces1831 * @param collectionId ID of collection1832 * @param tokenId ID of token1833 * @example getTokenTotalPieces(10, 5);1834 * @returns number of pieces1835 */1836 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1837 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1838 }18391840 /**1841 * Change number of token pieces. Signer must be the owner of all token pieces.1842 * @param signer keyring of signer1843 * @param collectionId ID of collection1844 * @param tokenId ID of token1845 * @param amount new number of pieces1846 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1847 * @returns true if the repartion was success, otherwise false1848 */1849 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1850 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1851 const repartitionResult = await this.helper.executeExtrinsic(1852 signer,1853 'api.tx.unique.repartition', [collectionId, tokenId, amount],1854 true,1855 );1856 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1857 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1858 }1859}186018611862class FTGroup extends CollectionGroup {1863 /**1864 * Get collection object1865 * @param collectionId ID of collection1866 * @example getCollectionObject(2);1867 * @returns instance of UniqueFTCollection1868 */1869 getCollectionObject(collectionId: number): UniqueFTCollection {1870 return new UniqueFTCollection(collectionId, this.helper);1871 }18721873 /**1874 * Mint new fungible collection1875 * @param signer keyring of signer1876 * @param collectionOptions Collection options1877 * @param decimalPoints number of token decimals1878 * @example1879 * mintCollection(aliceKeyring, {1880 * name: 'New',1881 * description: 'New collection',1882 * tokenPrefix: 'NEW',1883 * }, 18)1884 * @returns newly created fungible collection1885 */1886 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1887 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1888 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1889 collectionOptions.mode = {fungible: decimalPoints};1890 for (const key of ['name', 'description', 'tokenPrefix']) {1891 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1892 }1893 const creationResult = await this.helper.executeExtrinsic(1894 signer,1895 'api.tx.unique.createCollectionEx', [collectionOptions],1896 true,1897 );1898 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1899 }19001901 /**1902 * Mint tokens1903 * @param signer keyring of signer1904 * @param collectionId ID of collection1905 * @param owner address owner of new tokens1906 * @param amount amount of tokens to be meanted1907 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1908 * @returns ```true``` if extrinsic success, otherwise ```false```1909 */1910 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1911 const creationResult = await this.helper.executeExtrinsic(1912 signer,1913 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1914 fungible: {1915 value: amount,1916 },1917 }],1918 true, // `Unable to mint fungible tokens for ${label}`,1919 );1920 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1921 }19221923 /**1924 * Mint multiple Fungible tokens with one owner1925 * @param signer keyring of signer1926 * @param collectionId ID of collection1927 * @param owner tokens owner1928 * @param tokens array of tokens with properties and pieces1929 * @returns ```true``` if extrinsic success, otherwise ```false```1930 */1931 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1932 const rawTokens = [];1933 for (const token of tokens) {1934 const raw = {Fungible: {Value: token.value}};1935 rawTokens.push(raw);1936 }1937 const creationResult = await this.helper.executeExtrinsic(1938 signer,1939 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1940 true,1941 );1942 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1943 }19441945 /**1946 * Get the top 10 owners with the largest balance for the Fungible collection1947 * @param collectionId ID of collection1948 * @example getTop10Owners(10);1949 * @returns array of ```ICrossAccountId```1950 */1951 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1952 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1953 }19541955 /**1956 * Get account balance1957 * @param collectionId ID of collection1958 * @param addressObj address of owner1959 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1960 * @returns amount of fungible tokens owned by address1961 */1962 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1963 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1964 }19651966 /**1967 * Transfer tokens to address1968 * @param signer keyring of signer1969 * @param collectionId ID of collection1970 * @param toAddressObj address recipient1971 * @param amount amount of tokens to be sent1972 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1973 * @returns ```true``` if extrinsic success, otherwise ```false```1974 */1975 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1976 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1977 }19781979 /**1980 * Transfer some tokens on behalf of the owner.1981 * @param signer keyring of signer1982 * @param collectionId ID of collection1983 * @param fromAddressObj address on behalf of which tokens will be sent1984 * @param toAddressObj address where token to be sent1985 * @param amount number of tokens to be sent1986 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1987 * @returns ```true``` if extrinsic success, otherwise ```false```1988 */1989 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1990 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1991 }19921993 /**1994 * Destroy some amount of tokens1995 * @param signer keyring of signer1996 * @param collectionId ID of collection1997 * @param amount amount of tokens to be destroyed1998 * @example burnTokens(aliceKeyring, 10, 1000n);1999 * @returns ```true``` if extrinsic success, otherwise ```false```2000 */2001 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2002 return await super.burnToken(signer, collectionId, 0, amount);2003 }20042005 /**2006 * Burn some tokens on behalf of the owner.2007 * @param signer keyring of signer2008 * @param collectionId ID of collection2009 * @param fromAddressObj address on behalf of which tokens will be burnt2010 * @param amount amount of tokens to be burnt2011 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2012 * @returns ```true``` if extrinsic success, otherwise ```false```2013 */2014 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2015 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2016 }20172018 /**2019 * Get total collection supply2020 * @param collectionId2021 * @returns2022 */2023 async getTotalPieces(collectionId: number): Promise<bigint> {2024 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2025 }20262027 /**2028 * Set, change, or remove approved address to transfer tokens.2029 *2030 * @param signer keyring of signer2031 * @param collectionId ID of collection2032 * @param toAddressObj address to be approved2033 * @param amount amount of tokens to be approved2034 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2035 * @returns ```true``` if extrinsic success, otherwise ```false```2036 */2037 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2038 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2039 }20402041 /**2042 * Get amount of fungible tokens approved to transfer2043 * @param collectionId ID of collection2044 * @param fromAddressObj owner of tokens2045 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2046 * @returns number of tokens approved for the transfer2047 */2048 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2049 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2050 }2051}205220532054class ChainGroup extends HelperGroup<ChainHelperBase> {2055 /**2056 * Get system properties of a chain2057 * @example getChainProperties();2058 * @returns ss58Format, token decimals, and token symbol2059 */2060 getChainProperties(): IChainProperties {2061 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2062 return {2063 ss58Format: properties.ss58Format.toJSON(),2064 tokenDecimals: properties.tokenDecimals.toJSON(),2065 tokenSymbol: properties.tokenSymbol.toJSON(),2066 };2067 }20682069 /**2070 * Get chain header2071 * @example getLatestBlockNumber();2072 * @returns the number of the last block2073 */2074 async getLatestBlockNumber(): Promise<number> {2075 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2076 }20772078 /**2079 * Get block hash by block number2080 * @param blockNumber number of block2081 * @example getBlockHashByNumber(12345);2082 * @returns hash of a block2083 */2084 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2085 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2086 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2087 return blockHash;2088 }20892090 // TODO add docs2091 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2092 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2093 if (!blockHash) return null;2094 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2095 }20962097 /**2098 * Get account nonce2099 * @param address substrate address2100 * @example getNonce("5GrwvaEF5zXb26Fz...");2101 * @returns number, account's nonce2102 */2103 async getNonce(address: TSubstrateAccount): Promise<number> {2104 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2105 }2106}21072108class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2109 /**2110 * Get substrate address balance2111 * @param address substrate address2112 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2113 * @returns amount of tokens on address2114 */2115 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2116 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2117 }21182119 /**2120 * Transfer tokens to substrate address2121 * @param signer keyring of signer2122 * @param address substrate address of a recipient2123 * @param amount amount of tokens to be transfered2124 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2125 * @returns ```true``` if extrinsic success, otherwise ```false```2126 */2127 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2128 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);21292130 let transfer = {from: null, to: null, amount: 0n} as any;2131 result.result.events.forEach(({event: {data, method, section}}) => {2132 if ((section === 'balances') && (method === 'Transfer')) {2133 transfer = {2134 from: this.helper.address.normalizeSubstrate(data[0]),2135 to: this.helper.address.normalizeSubstrate(data[1]),2136 amount: BigInt(data[2]),2137 };2138 }2139 });2140 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2141 && this.helper.address.normalizeSubstrate(address) === transfer.to 2142 && BigInt(amount) === transfer.amount;2143 return isSuccess;2144 }21452146 /**2147 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2148 * @param address substrate address2149 * @returns2150 */2151 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2152 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2153 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2154 }2155}21562157class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2158 /**2159 * Get ethereum address balance2160 * @param address ethereum address2161 * @example getEthereum("0x9F0583DbB855d...")2162 * @returns amount of tokens on address2163 */2164 async getEthereum(address: TEthereumAccount): Promise<bigint> {2165 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2166 }21672168 /**2169 * Transfer tokens to address2170 * @param signer keyring of signer2171 * @param address Ethereum address of a recipient2172 * @param amount amount of tokens to be transfered2173 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2174 * @returns ```true``` if extrinsic success, otherwise ```false```2175 */2176 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2177 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21782179 let transfer = {from: null, to: null, amount: 0n} as any;2180 result.result.events.forEach(({event: {data, method, section}}) => {2181 if ((section === 'balances') && (method === 'Transfer')) {2182 transfer = {2183 from: data[0].toString(),2184 to: data[1].toString(),2185 amount: BigInt(data[2]),2186 };2187 }2188 });2189 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2190 && address === transfer.to 2191 && BigInt(amount) === transfer.amount;2192 return isSuccess;2193 }2194}21952196class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2197 subBalanceGroup: SubstrateBalanceGroup<T>;2198 ethBalanceGroup: EthereumBalanceGroup<T>;21992200 constructor(helper: T) {2201 super(helper);2202 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2203 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2204 }22052206 getCollectionCreationPrice(): bigint {2207 return 2n * this.getOneTokenNominal();2208 }2209 /**2210 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2211 * @example getOneTokenNominal()2212 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2213 */2214 getOneTokenNominal(): bigint {2215 const chainProperties = this.helper.chain.getChainProperties();2216 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2217 }22182219 /**2220 * Get substrate address balance2221 * @param address substrate address2222 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2223 * @returns amount of tokens on address2224 */2225 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2226 return this.subBalanceGroup.getSubstrate(address);2227 }22282229 /**2230 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2231 * @param address substrate address2232 * @returns2233 */2234 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2235 return this.subBalanceGroup.getSubstrateFull(address);2236 }22372238 /**2239 * Get ethereum address balance2240 * @param address ethereum address2241 * @example getEthereum("0x9F0583DbB855d...")2242 * @returns amount of tokens on address2243 */2244 async getEthereum(address: TEthereumAccount): Promise<bigint> {2245 return this.ethBalanceGroup.getEthereum(address);2246 }22472248 /**2249 * Transfer tokens to substrate address2250 * @param signer keyring of signer2251 * @param address substrate address of a recipient2252 * @param amount amount of tokens to be transfered2253 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2254 * @returns ```true``` if extrinsic success, otherwise ```false```2255 */2256 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2257 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2258 }2259}22602261class AddressGroup extends HelperGroup<ChainHelperBase> {2262 /**2263 * Normalizes the address to the specified ss58 format, by default ```42```.2264 * @param address substrate address2265 * @param ss58Format format for address conversion, by default ```42```2266 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2267 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2268 */2269 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2270 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2271 }22722273 /**2274 * Get address in the connected chain format2275 * @param address substrate address2276 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2277 * @returns address in chain format2278 */2279 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2280 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2281 }22822283 /**2284 * Get substrate mirror of an ethereum address2285 * @param ethAddress ethereum address2286 * @param toChainFormat false for normalized account2287 * @example ethToSubstrate('0x9F0583DbB855d...')2288 * @returns substrate mirror of a provided ethereum address2289 */2290 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2291 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2292 }22932294 /**2295 * Get ethereum mirror of a substrate address2296 * @param subAddress substrate account2297 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2298 * @returns ethereum mirror of a provided substrate address2299 */2300 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2301 return CrossAccountId.translateSubToEth(subAddress);2302 }23032304 paraSiblingSovereignAccount(paraid: number) {2305 // We are getting a *sibling* parachain sovereign account,2306 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2307 const siblingPrefix = '0x7369626c';23082309 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2310 const suffix = '000000000000000000000000000000000000000000000000';23112312 return siblingPrefix + encodedParaId + suffix;2313 }23142315 /**2316 * Encode key to substrate address2317 * @param key key for encoding address2318 * @param ss58Format prefix for encoding to the address of the corresponding network2319 * @returns encoded substrate address2320 */2321 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2322 const u8a :Uint8Array = typeof key === 'string'2323 ? hexToU8a(key)2324 : typeof key === 'bigint'2325 ? hexToU8a(key.toString(16))2326 : key;2327 2328 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2329 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2330 }2331 2332 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2333 if (!allowedDecodedLengths.includes(u8a.length)) {2334 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2335 }2336 2337 const u8aPrefix = ss58Format < 642338 ? new Uint8Array([ss58Format])2339 : new Uint8Array([2340 ((ss58Format & 0xfc) >> 2) | 0x40,2341 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2342 ]);23432344 const input = u8aConcat(u8aPrefix, u8a);2345 2346 return base58Encode(u8aConcat(2347 input,2348 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2349 ));2350 }23512352 /**2353 * Restore substrate address from bigint representation2354 * @param number decimal representation of substrate address2355 * @returns substrate address2356 */2357 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2358 if (this.helper.api === null) {2359 throw 'Not connected';2360 }2361 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2362 if (res === undefined || res === null) {2363 throw 'Restore address error';2364 }2365 return res.toString();2366 }23672368 /**2369 * Convert etherium cross account id to substrate cross account id2370 * @param ethCrossAccount etherium cross account2371 * @returns substrate cross account id2372 */2373 convertCrossAccountFromEthCrossAcoount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2374 if (ethCrossAccount.field_1 === '0') {2375 return {Ethereum: ethCrossAccount.field_0.toLocaleLowerCase()};2376 }2377 2378 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.field_1));2379 return {Substrate: ss58};2380 }2381}23822383class StakingGroup extends HelperGroup<UniqueHelper> {2384 /**2385 * Stake tokens for App Promotion2386 * @param signer keyring of signer2387 * @param amountToStake amount of tokens to stake2388 * @param label extra label for log2389 * @returns2390 */2391 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2392 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2393 const _stakeResult = await this.helper.executeExtrinsic(2394 signer, 'api.tx.appPromotion.stake',2395 [amountToStake], true,2396 );2397 // TODO extract info from stakeResult2398 return true;2399 }24002401 /**2402 * Unstake tokens for App Promotion2403 * @param signer keyring of signer2404 * @param amountToUnstake amount of tokens to unstake2405 * @param label extra label for log2406 * @returns block number where balances will be unlocked2407 */2408 async unstake(signer: TSigner, label?: string): Promise<number> {2409 if(typeof label === 'undefined') label = `${signer.address}`;2410 const _unstakeResult = await this.helper.executeExtrinsic(2411 signer, 'api.tx.appPromotion.unstake',2412 [], true,2413 );2414 // TODO extract block number fron events2415 return 1;2416 }24172418 /**2419 * Get total staked amount for address2420 * @param address substrate or ethereum address2421 * @returns total staked amount2422 */2423 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2424 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2425 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2426 }24272428 /**2429 * Get total staked per block2430 * @param address substrate or ethereum address2431 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2432 */2433 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2434 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2435 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2436 return { 2437 block: block.toBigInt(),2438 amount: amount.toBigInt(),2439 };2440 });2441 }24422443 /**2444 * Get total pending unstake amount for address2445 * @param address substrate or ethereum address2446 * @returns total pending unstake amount2447 */2448 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2449 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2450 }24512452 /**2453 * Get pending unstake amount per block for address2454 * @param address substrate or ethereum address2455 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2456 */2457 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2458 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2459 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2460 return {2461 block: block.toBigInt(),2462 amount: amount.toBigInt(),2463 };2464 });2465 return result;2466 }2467}24682469class SchedulerGroup extends HelperGroup<UniqueHelper> {2470 constructor(helper: UniqueHelper) {2471 super(helper);2472 }24732474 async cancelScheduled(signer: TSigner, scheduledId: string) {2475 return this.helper.executeExtrinsic(2476 signer,2477 'api.tx.scheduler.cancelNamed',2478 [scheduledId],2479 true,2480 );2481 }24822483 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2484 return this.helper.executeExtrinsic(2485 signer,2486 'api.tx.scheduler.changeNamedPriority',2487 [scheduledId, priority],2488 true,2489 );2490 }24912492 scheduleAt<T extends UniqueHelper>(2493 scheduledId: string,2494 executionBlockNumber: number,2495 options: ISchedulerOptions = {},2496 ) {2497 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2498 }24992500 scheduleAfter<T extends UniqueHelper>(2501 scheduledId: string,2502 blocksBeforeExecution: number,2503 options: ISchedulerOptions = {},2504 ) {2505 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2506 }25072508 schedule<T extends UniqueHelper>(2509 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2510 scheduledId: string,2511 blocksNum: number,2512 options: ISchedulerOptions = {},2513 ) {2514 // eslint-disable-next-line @typescript-eslint/naming-convention2515 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2516 return this.helper.clone(ScheduledHelperType, {2517 scheduleFn,2518 scheduledId,2519 blocksNum,2520 options,2521 }) as T;2522 }2523}25242525class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2526 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2527 await this.helper.executeExtrinsic(2528 signer,2529 'api.tx.foreignAssets.registerForeignAsset',2530 [ownerAddress, location, metadata],2531 true,2532 );2533 }25342535 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2536 await this.helper.executeExtrinsic(2537 signer,2538 'api.tx.foreignAssets.updateForeignAsset',2539 [foreignAssetId, location, metadata],2540 true,2541 );2542 }2543}25442545class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2546 palletName: string;25472548 constructor(helper: T, palletName: string) {2549 super(helper);25502551 this.palletName = palletName;2552 }25532554 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2555 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2556 }2557}25582559class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2560 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2561 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2562 }25632564 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2565 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2566 }25672568 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2569 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2570 }2571}25722573class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2574 async accounts(address: string, currencyId: any) {2575 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2576 return BigInt(free);2577 }2578}25792580class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2581 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2582 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2583 }25842585 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2586 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2587 }25882589 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2590 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2591 }25922593 async account(assetId: string | number, address: string) {2594 const accountAsset = (2595 await this.helper.callRpc('api.query.assets.account', [assetId, address])2596 ).toJSON()! as any;25972598 if (accountAsset !== null) {2599 return BigInt(accountAsset['balance']);2600 } else {2601 return null;2602 }2603 }2604}26052606class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2607 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2608 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2609 }2610}26112612class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2613 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2614 const apiPrefix = 'api.tx.assetManager.';26152616 const registerTx = this.helper.constructApiCall(2617 apiPrefix + 'registerForeignAsset',2618 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2619 );26202621 const setUnitsTx = this.helper.constructApiCall(2622 apiPrefix + 'setAssetUnitsPerSecond',2623 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2624 );26252626 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2627 const encodedProposal = batchCall?.method.toHex() || '';2628 return encodedProposal;2629 }26302631 async assetTypeId(location: any) {2632 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2633 }2634}26352636class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2637 async notePreimage(signer: TSigner, encodedProposal: string) {2638 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2639 }26402641 externalProposeMajority(proposalHash: string) {2642 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2643 }26442645 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2646 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2647 }26482649 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2650 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2651 }2652}26532654class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2655 collective: string;26562657 constructor(helper: MoonbeamHelper, collective: string) {2658 super(helper);26592660 this.collective = collective;2661 }26622663 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2664 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2665 }26662667 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2668 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2669 }26702671 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2672 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2673 }26742675 async proposalCount() {2676 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2677 }2678}26792680export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2681export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26822683export class UniqueHelper extends ChainHelperBase {2684 balance: BalanceGroup<UniqueHelper>;2685 collection: CollectionGroup;2686 nft: NFTGroup;2687 rft: RFTGroup;2688 ft: FTGroup;2689 staking: StakingGroup;2690 scheduler: SchedulerGroup;2691 foreignAssets: ForeignAssetsGroup;2692 xcm: XcmGroup<UniqueHelper>;2693 xTokens: XTokensGroup<UniqueHelper>;2694 tokens: TokensGroup<UniqueHelper>;26952696 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2697 super(logger, options.helperBase ?? UniqueHelper);26982699 this.balance = new BalanceGroup(this);2700 this.collection = new CollectionGroup(this);2701 this.nft = new NFTGroup(this);2702 this.rft = new RFTGroup(this);2703 this.ft = new FTGroup(this);2704 this.staking = new StakingGroup(this);2705 this.scheduler = new SchedulerGroup(this);2706 this.foreignAssets = new ForeignAssetsGroup(this);2707 this.xcm = new XcmGroup(this, 'polkadotXcm');2708 this.xTokens = new XTokensGroup(this);2709 this.tokens = new TokensGroup(this);2710 }27112712 getSudo<T extends UniqueHelper>() {2713 // eslint-disable-next-line @typescript-eslint/naming-convention2714 const SudoHelperType = SudoHelper(this.helperBase);2715 return this.clone(SudoHelperType) as T;2716 }2717}27182719export class XcmChainHelper extends ChainHelperBase {2720 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2721 const wsProvider = new WsProvider(wsEndpoint);2722 this.api = new ApiPromise({2723 provider: wsProvider,2724 });2725 await this.api.isReadyOrError;2726 this.network = await UniqueHelper.detectNetwork(this.api);2727 }2728}27292730export class RelayHelper extends XcmChainHelper {2731 xcm: XcmGroup<RelayHelper>;27322733 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2734 super(logger, options.helperBase ?? RelayHelper);27352736 this.xcm = new XcmGroup(this, 'xcmPallet');2737 }2738}27392740export class WestmintHelper extends XcmChainHelper {2741 balance: SubstrateBalanceGroup<WestmintHelper>;2742 xcm: XcmGroup<WestmintHelper>;2743 assets: AssetsGroup<WestmintHelper>;2744 xTokens: XTokensGroup<WestmintHelper>;27452746 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2747 super(logger, options.helperBase ?? WestmintHelper);27482749 this.balance = new SubstrateBalanceGroup(this);2750 this.xcm = new XcmGroup(this, 'polkadotXcm');2751 this.assets = new AssetsGroup(this);2752 this.xTokens = new XTokensGroup(this);2753 }2754}27552756export class MoonbeamHelper extends XcmChainHelper {2757 balance: EthereumBalanceGroup<MoonbeamHelper>;2758 assetManager: MoonbeamAssetManagerGroup;2759 assets: AssetsGroup<MoonbeamHelper>;2760 xTokens: XTokensGroup<MoonbeamHelper>;2761 democracy: MoonbeamDemocracyGroup;2762 collective: {2763 council: MoonbeamCollectiveGroup,2764 techCommittee: MoonbeamCollectiveGroup,2765 };27662767 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2768 super(logger, options.helperBase ?? MoonbeamHelper);27692770 this.balance = new EthereumBalanceGroup(this);2771 this.assetManager = new MoonbeamAssetManagerGroup(this);2772 this.assets = new AssetsGroup(this);2773 this.xTokens = new XTokensGroup(this);2774 this.democracy = new MoonbeamDemocracyGroup(this);2775 this.collective = {2776 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2777 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2778 };2779 }2780}27812782export class AcalaHelper extends XcmChainHelper {2783 balance: SubstrateBalanceGroup<AcalaHelper>;2784 assetRegistry: AcalaAssetRegistryGroup;2785 xTokens: XTokensGroup<AcalaHelper>;2786 tokens: TokensGroup<AcalaHelper>;27872788 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2789 super(logger, options.helperBase ?? AcalaHelper);27902791 this.balance = new SubstrateBalanceGroup(this);2792 this.assetRegistry = new AcalaAssetRegistryGroup(this);2793 this.xTokens = new XTokensGroup(this);2794 this.tokens = new TokensGroup(this);2795 }27962797 getSudo<T extends AcalaHelper>() {2798 // eslint-disable-next-line @typescript-eslint/naming-convention2799 const SudoHelperType = SudoHelper(this.helperBase);2800 return this.clone(SudoHelperType) as T;2801 }2802}28032804// eslint-disable-next-line @typescript-eslint/naming-convention2805function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2806 return class extends Base {2807 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2808 scheduledId: string;2809 blocksNum: number;2810 options: ISchedulerOptions;28112812 constructor(...args: any[]) {2813 const logger = args[0] as ILogger;2814 const options = args[1] as {2815 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2816 scheduledId: string,2817 blocksNum: number,2818 options: ISchedulerOptions2819 };28202821 super(logger);28222823 this.scheduleFn = options.scheduleFn;2824 this.scheduledId = options.scheduledId;2825 this.blocksNum = options.blocksNum;2826 this.options = options.options;2827 }28282829 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2830 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2831 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;28322833 return super.executeExtrinsic(2834 sender,2835 extrinsic,2836 [2837 this.scheduledId,2838 this.blocksNum,2839 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2840 this.options.priority ?? null,2841 {Value: scheduledTx},2842 ],2843 expectSuccess,2844 );2845 }2846 };2847}28482849// eslint-disable-next-line @typescript-eslint/naming-convention2850function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2851 return class extends Base {2852 constructor(...args: any[]) {2853 super(...args);2854 }28552856 executeExtrinsic (2857 sender: IKeyringPair,2858 extrinsic: string,2859 params: any[],2860 expectSuccess?: boolean,2861 ): Promise<ITransactionResult> {2862 const call = this.constructApiCall(extrinsic, params);28632864 return super.executeExtrinsic(2865 sender,2866 'api.tx.sudo.sudo',2867 [call],2868 expectSuccess,2869 );2870 }2871 };2872}28732874export class UniqueBaseCollection {2875 helper: UniqueHelper;2876 collectionId: number;28772878 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2879 this.collectionId = collectionId;2880 this.helper = uniqueHelper;2881 }28822883 async getData() {2884 return await this.helper.collection.getData(this.collectionId);2885 }28862887 async getLastTokenId() {2888 return await this.helper.collection.getLastTokenId(this.collectionId);2889 }28902891 async doesTokenExist(tokenId: number) {2892 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2893 }28942895 async getAdmins() {2896 return await this.helper.collection.getAdmins(this.collectionId);2897 }28982899 async getAllowList() {2900 return await this.helper.collection.getAllowList(this.collectionId);2901 }29022903 async getEffectiveLimits() {2904 return await this.helper.collection.getEffectiveLimits(this.collectionId);2905 }29062907 async getProperties(propertyKeys?: string[] | null) {2908 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2909 }29102911 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2912 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2913 }29142915 async getOptions() {2916 return await this.helper.collection.getCollectionOptions(this.collectionId);2917 }29182919 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2920 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2921 }29222923 async confirmSponsorship(signer: TSigner) {2924 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2925 }29262927 async removeSponsor(signer: TSigner) {2928 return await this.helper.collection.removeSponsor(signer, this.collectionId);2929 }29302931 async setLimits(signer: TSigner, limits: ICollectionLimits) {2932 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2933 }29342935 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2936 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2937 }29382939 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2940 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2941 }29422943 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2944 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2945 }29462947 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2948 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2949 }29502951 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2952 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2953 }29542955 async setProperties(signer: TSigner, properties: IProperty[]) {2956 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2957 }29582959 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2960 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2961 }29622963 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2964 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2965 }29662967 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2968 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2969 }29702971 async disableNesting(signer: TSigner) {2972 return await this.helper.collection.disableNesting(signer, this.collectionId);2973 }29742975 async burn(signer: TSigner) {2976 return await this.helper.collection.burn(signer, this.collectionId);2977 }29782979 scheduleAt<T extends UniqueHelper>(2980 scheduledId: string,2981 executionBlockNumber: number,2982 options: ISchedulerOptions = {},2983 ) {2984 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2985 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2986 }29872988 scheduleAfter<T extends UniqueHelper>(2989 scheduledId: string,2990 blocksBeforeExecution: number,2991 options: ISchedulerOptions = {},2992 ) {2993 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2994 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2995 }29962997 getSudo<T extends UniqueHelper>() {2998 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2999 }3000}300130023003export class UniqueNFTCollection extends UniqueBaseCollection {3004 getTokenObject(tokenId: number) {3005 return new UniqueNFToken(tokenId, this);3006 }30073008 async getTokensByAddress(addressObj: ICrossAccountId) {3009 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3010 }30113012 async getToken(tokenId: number, blockHashAt?: string) {3013 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3014 }30153016 async getTokenOwner(tokenId: number, blockHashAt?: string) {3017 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3018 }30193020 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3021 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3022 }30233024 async getTokenChildren(tokenId: number, blockHashAt?: string) {3025 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3026 }30273028 async getPropertyPermissions(propertyKeys: string[] | null = null) {3029 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3030 }30313032 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3033 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3034 }30353036 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3037 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3038 }30393040 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3041 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3042 }30433044 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3045 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3046 }30473048 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3049 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3050 }30513052 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3053 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3054 }30553056 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3057 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3058 }30593060 async burnToken(signer: TSigner, tokenId: number) {3061 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3062 }30633064 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3065 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3066 }30673068 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3069 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3070 }30713072 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3073 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3074 }30753076 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3077 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3078 }30793080 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3081 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3082 }30833084 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3085 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3086 }30873088 scheduleAt<T extends UniqueHelper>(3089 scheduledId: string,3090 executionBlockNumber: number,3091 options: ISchedulerOptions = {},3092 ) {3093 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3094 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3095 }30963097 scheduleAfter<T extends UniqueHelper>(3098 scheduledId: string,3099 blocksBeforeExecution: number,3100 options: ISchedulerOptions = {},3101 ) {3102 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3103 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3104 }31053106 getSudo<T extends UniqueHelper>() {3107 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3108 }3109}311031113112export class UniqueRFTCollection extends UniqueBaseCollection {3113 getTokenObject(tokenId: number) {3114 return new UniqueRFToken(tokenId, this);3115 }31163117 async getToken(tokenId: number, blockHashAt?: string) {3118 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3119 }31203121 async getTokensByAddress(addressObj: ICrossAccountId) {3122 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3123 }31243125 async getTop10TokenOwners(tokenId: number) {3126 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3127 }31283129 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3130 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3131 }31323133 async getTokenTotalPieces(tokenId: number) {3134 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3135 }31363137 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3138 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3139 }31403141 async getPropertyPermissions(propertyKeys: string[] | null = null) {3142 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3143 }31443145 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3146 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3147 }31483149 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3150 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3151 }31523153 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3154 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3155 }31563157 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3158 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3159 }31603161 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3162 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3163 }31643165 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3166 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3167 }31683169 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3170 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3171 }31723173 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3174 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3175 }31763177 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3178 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3179 }31803181 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3182 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3183 }31843185 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3186 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3187 }31883189 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3190 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3191 }31923193 scheduleAt<T extends UniqueHelper>(3194 scheduledId: string,3195 executionBlockNumber: number,3196 options: ISchedulerOptions = {},3197 ) {3198 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3199 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3200 }32013202 scheduleAfter<T extends UniqueHelper>(3203 scheduledId: string,3204 blocksBeforeExecution: number,3205 options: ISchedulerOptions = {},3206 ) {3207 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3208 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3209 }32103211 getSudo<T extends UniqueHelper>() {3212 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3213 }3214}321532163217export class UniqueFTCollection extends UniqueBaseCollection {3218 async getBalance(addressObj: ICrossAccountId) {3219 return await this.helper.ft.getBalance(this.collectionId, addressObj);3220 }32213222 async getTotalPieces() {3223 return await this.helper.ft.getTotalPieces(this.collectionId);3224 }32253226 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3227 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3228 }32293230 async getTop10Owners() {3231 return await this.helper.ft.getTop10Owners(this.collectionId);3232 }32333234 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3235 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3236 }32373238 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3239 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3240 }32413242 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3243 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3244 }32453246 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3247 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3248 }32493250 async burnTokens(signer: TSigner, amount=1n) {3251 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3252 }32533254 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3255 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3256 }32573258 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3259 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3260 }32613262 scheduleAt<T extends UniqueHelper>(3263 scheduledId: string,3264 executionBlockNumber: number,3265 options: ISchedulerOptions = {},3266 ) {3267 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3268 return new UniqueFTCollection(this.collectionId, scheduledHelper);3269 }32703271 scheduleAfter<T extends UniqueHelper>(3272 scheduledId: string,3273 blocksBeforeExecution: number,3274 options: ISchedulerOptions = {},3275 ) {3276 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3277 return new UniqueFTCollection(this.collectionId, scheduledHelper);3278 }32793280 getSudo<T extends UniqueHelper>() {3281 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3282 }3283}328432853286export class UniqueBaseToken {3287 collection: UniqueNFTCollection | UniqueRFTCollection;3288 collectionId: number;3289 tokenId: number;32903291 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3292 this.collection = collection;3293 this.collectionId = collection.collectionId;3294 this.tokenId = tokenId;3295 }32963297 async getNextSponsored(addressObj: ICrossAccountId) {3298 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3299 }33003301 async getProperties(propertyKeys?: string[] | null) {3302 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3303 }33043305 async setProperties(signer: TSigner, properties: IProperty[]) {3306 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3307 }33083309 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3310 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3311 }33123313 async doesExist() {3314 return await this.collection.doesTokenExist(this.tokenId);3315 }33163317 nestingAccount() {3318 return this.collection.helper.util.getTokenAccount(this);3319 }33203321 scheduleAt<T extends UniqueHelper>(3322 scheduledId: string,3323 executionBlockNumber: number,3324 options: ISchedulerOptions = {},3325 ) {3326 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3327 return new UniqueBaseToken(this.tokenId, scheduledCollection);3328 }33293330 scheduleAfter<T extends UniqueHelper>(3331 scheduledId: string,3332 blocksBeforeExecution: number,3333 options: ISchedulerOptions = {},3334 ) {3335 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3336 return new UniqueBaseToken(this.tokenId, scheduledCollection);3337 }33383339 getSudo<T extends UniqueHelper>() {3340 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3341 }3342}334333443345export class UniqueNFToken extends UniqueBaseToken {3346 collection: UniqueNFTCollection;33473348 constructor(tokenId: number, collection: UniqueNFTCollection) {3349 super(tokenId, collection);3350 this.collection = collection;3351 }33523353 async getData(blockHashAt?: string) {3354 return await this.collection.getToken(this.tokenId, blockHashAt);3355 }33563357 async getOwner(blockHashAt?: string) {3358 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3359 }33603361 async getTopmostOwner(blockHashAt?: string) {3362 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3363 }33643365 async getChildren(blockHashAt?: string) {3366 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3367 }33683369 async nest(signer: TSigner, toTokenObj: IToken) {3370 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3371 }33723373 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3374 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3375 }33763377 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3378 return await this.collection.transferToken(signer, this.tokenId, addressObj);3379 }33803381 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3382 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3383 }33843385 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3386 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3387 }33883389 async isApproved(toAddressObj: ICrossAccountId) {3390 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3391 }33923393 async burn(signer: TSigner) {3394 return await this.collection.burnToken(signer, this.tokenId);3395 }33963397 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3398 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3399 }34003401 scheduleAt<T extends UniqueHelper>(3402 scheduledId: string,3403 executionBlockNumber: number,3404 options: ISchedulerOptions = {},3405 ) {3406 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3407 return new UniqueNFToken(this.tokenId, scheduledCollection);3408 }34093410 scheduleAfter<T extends UniqueHelper>(3411 scheduledId: string,3412 blocksBeforeExecution: number,3413 options: ISchedulerOptions = {},3414 ) {3415 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3416 return new UniqueNFToken(this.tokenId, scheduledCollection);3417 }34183419 getSudo<T extends UniqueHelper>() {3420 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3421 }3422}34233424export class UniqueRFToken extends UniqueBaseToken {3425 collection: UniqueRFTCollection;34263427 constructor(tokenId: number, collection: UniqueRFTCollection) {3428 super(tokenId, collection);3429 this.collection = collection;3430 }34313432 async getData(blockHashAt?: string) {3433 return await this.collection.getToken(this.tokenId, blockHashAt);3434 }34353436 async getTop10Owners() {3437 return await this.collection.getTop10TokenOwners(this.tokenId);3438 }34393440 async getBalance(addressObj: ICrossAccountId) {3441 return await this.collection.getTokenBalance(this.tokenId, addressObj);3442 }34433444 async getTotalPieces() {3445 return await this.collection.getTokenTotalPieces(this.tokenId);3446 }34473448 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3449 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3450 }34513452 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3453 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3454 }34553456 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3457 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3458 }34593460 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3461 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3462 }34633464 async repartition(signer: TSigner, amount: bigint) {3465 return await this.collection.repartitionToken(signer, this.tokenId, amount);3466 }34673468 async burn(signer: TSigner, amount=1n) {3469 return await this.collection.burnToken(signer, this.tokenId, amount);3470 }34713472 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3473 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3474 }34753476 scheduleAt<T extends UniqueHelper>(3477 scheduledId: string,3478 executionBlockNumber: number,3479 options: ISchedulerOptions = {},3480 ) {3481 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3482 return new UniqueRFToken(this.tokenId, scheduledCollection);3483 }34843485 scheduleAfter<T extends UniqueHelper>(3486 scheduledId: string,3487 blocksBeforeExecution: number,3488 options: ISchedulerOptions = {},3489 ) {3490 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3491 return new UniqueRFToken(this.tokenId, scheduledCollection);3492 }34933494 getSudo<T extends UniqueHelper>() {3495 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3496 }3497}