difftreelog
Merge pull request #996 from UniqueNetwork/tests/playgrounds-refactor
in: master
refactor(playgorunds): rearranging the code structure
10 files changed
.envrcdiffbeforeafterboth--- a/.envrc
+++ b/.envrc
@@ -30,7 +30,7 @@
fi
echo -e "${GREEN}Baedeker env updated${RESET}"
- nginx_id=$(docker compose -f .baedeker/.bdk-env/docker-compose.yml ps --format=json | jq -r '.[] | select(.Service == "nginx") | .ID' -e)
+ nginx_id=$(docker compose -f .baedeker/.bdk-env/docker-compose.yml ps --format=json | jq -s 'flatten' | jq -r '.[] | select(.Service == "nginx") | .ID' -e)
if ! [ $? -eq 0 ]; then
echo -e "${RED}Nginx container not found${RESET}"
exit 0
tests/src/governance/util.tsdiffbeforeafterboth--- a/tests/src/governance/util.ts
+++ b/tests/src/governance/util.ts
@@ -2,6 +2,7 @@
import {xxhashAsHex} from '@polkadot/util-crypto';
import {usingPlaygrounds, expect} from '../util';
import {UniqueHelper} from '../util/playgrounds/unique';
+import {DevUniqueHelper} from '../util/playgrounds/unique.dev';
export const democracyLaunchPeriod = 35;
export const democracyVotingPeriod = 35;
@@ -203,7 +204,7 @@
});
}
-export async function voteUnanimouslyInFellowship(helper: UniqueHelper, fellows: IKeyringPair[][], minRank: number, referendumIndex: number) {
+export async function voteUnanimouslyInFellowship(helper: DevUniqueHelper, fellows: IKeyringPair[][], minRank: number, referendumIndex: number) {
for(let rank = minRank; rank < fellowshipRankLimit; rank++) {
for(const member of fellows[rank]) {
await helper.fellowship.collective.vote(member, referendumIndex, true);
tests/src/maintenance.seqtest.tsdiffbeforeafterboth--- a/tests/src/maintenance.seqtest.ts
+++ b/tests/src/maintenance.seqtest.ts
@@ -192,19 +192,22 @@
const blocksToWait = 6;
// Scheduling works before the maintenance
- await nftBeforeMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdBeforeMM})
- .transfer(bob, {Substrate: superuser.address});
+ await helper.scheduler.scheduleAfter(blocksToWait, {scheduledId: scheduledIdBeforeMM})
+ .nft.transferToken(bob, collection.collectionId, nftBeforeMM.tokenId, {Substrate: superuser.address});
+
await helper.wait.newBlocks(blocksToWait + 1);
expect(await nftBeforeMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});
// Schedule a transaction that should occur *during* the maintenance
- await nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdDuringMM})
- .transfer(bob, {Substrate: superuser.address});
+ await helper.scheduler.scheduleAfter(blocksToWait, {scheduledId: scheduledIdDuringMM})
+ .nft.transferToken(bob, collection.collectionId, nftDuringMM.tokenId, {Substrate: superuser.address});
+
// Schedule a transaction that should occur *after* the maintenance
- await nftDuringMM.scheduleAfter(blocksToWait * 2, {scheduledId: scheduledIdBunkerThroughMM})
- .transfer(bob, {Substrate: superuser.address});
+ await helper.scheduler.scheduleAfter(blocksToWait * 2, {scheduledId: scheduledIdBunkerThroughMM})
+ .nft.transferToken(bob, collection.collectionId, nftDuringMM.tokenId, {Substrate: superuser.address});
+
await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);
expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;
@@ -214,16 +217,16 @@
expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: bob.address});
// Any attempts to schedule a tx during the MM should be rejected
- await expect(nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAttemptDuringMM})
- .transfer(bob, {Substrate: superuser.address}))
+ await expect(helper.scheduler.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAttemptDuringMM})
+ .nft.transferToken(bob, collection.collectionId, nftDuringMM.tokenId, {Substrate: superuser.address}))
.to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);
await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);
expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;
// Scheduling works after the maintenance
- await nftAfterMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAfterMM})
- .transfer(bob, {Substrate: superuser.address});
+ await helper.scheduler.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAfterMM})
+ .nft.transferToken(bob, collection.collectionId, nftAfterMM.tokenId, {Substrate: superuser.address});
await helper.wait.newBlocks(blocksToWait + 1);
tests/src/scheduler.seqtest.tsdiffbeforeafterboth--- a/tests/src/scheduler.seqtest.ts
+++ b/tests/src/scheduler.seqtest.ts
@@ -47,9 +47,8 @@
const token = await collection.mintToken(alice);
const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
const blocksBeforeExecution = 4;
-
- await token.scheduleAfter(blocksBeforeExecution, {scheduledId})
- .transfer(alice, {Substrate: bob.address});
+ await helper.scheduler.scheduleAfter(blocksBeforeExecution, {scheduledId})
+ .nft.transferToken(alice, collection.collectionId, token.tokenId, {Substrate: bob.address});
const executionBlock = await helper.chain.getLatestBlockNumber() + blocksBeforeExecution + 1;
expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
@@ -103,8 +102,8 @@
expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
- await token.scheduleAfter(waitForBlocks, {scheduledId})
- .transfer(alice, {Substrate: bob.address});
+ await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId})
+ .nft.transferToken(alice, collection.collectionId, token.tokenId, {Substrate: bob.address});
const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
await helper.scheduler.cancelScheduled(alice, scheduledId);
@@ -363,8 +362,8 @@
const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 4;
- await token.scheduleAfter(waitForBlocks, {scheduledId})
- .transfer(bob, {Substrate: alice.address});
+ await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId})
+ .nft.transferToken(bob, collection.collectionId, token.tokenId, {Substrate: alice.address});
const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
await helper.getSudo().scheduler.cancelScheduled(superuser, scheduledId);
@@ -404,8 +403,8 @@
const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 6;
- await token.scheduleAfter(waitForBlocks, {scheduledId})
- .transfer(bob, {Substrate: alice.address});
+ await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId})
+ .nft.transferToken(bob, collection.collectionId, token.tokenId, {Substrate: alice.address});
const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
const priority = 112;
@@ -583,8 +582,8 @@
const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 4;
- await token.scheduleAfter(waitForBlocks, {scheduledId})
- .transfer(alice, {Substrate: bob.address});
+ await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId})
+ .nft.transferToken(alice, collection.collectionId, token.tokenId, {Substrate: bob.address});
const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
const scheduled = helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId});
@@ -614,8 +613,8 @@
const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 4;
- await token.scheduleAfter(waitForBlocks, {scheduledId})
- .transfer(alice, {Substrate: bob.address});
+ await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId})
+ .nft.transferToken(alice, collection.collectionId, token.tokenId, {Substrate: bob.address});
const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
await expect(helper.scheduler.cancelScheduled(bob, scheduledId))
@@ -655,8 +654,8 @@
const scheduledId = helper.arrange.makeScheduledId();
const waitForBlocks = 4;
- await token.scheduleAfter(waitForBlocks, {scheduledId})
- .transfer(bob, {Substrate: alice.address});
+ await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId})
+ .nft.transferToken(bob, collection.collectionId, token.tokenId, {Substrate: alice.address});
const priority = 112;
await expect(helper.scheduler.changePriority(alice, scheduledId, priority))
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -216,43 +216,6 @@
},
}
-export interface IForeignAssetMetadata {
- name?: number | Uint8Array,
- symbol?: string,
- decimals?: number,
- minimalBalance?: bigint,
-}
-
-export interface MoonbeamAssetInfo {
- location: any,
- metadata: {
- name: string,
- symbol: string,
- decimals: number,
- isFrozen: boolean,
- minimalBalance: bigint,
- },
- existentialDeposit: bigint,
- isSufficient: boolean,
- unitsPerSecond: bigint,
- numAssetsWeightHint: number,
-}
-
-export interface AcalaAssetMetadata {
- name: string,
- symbol: string,
- decimals: number,
- minimalBalance: bigint,
-}
-
-export interface DemocracyStandardAccountVote {
- balance: bigint,
- vote: {
- aye: boolean,
- conviction: number,
- },
-}
-
export interface DemocracySplitAccount {
aye: bigint,
nay: bigint,
tests/src/util/playgrounds/types.xcm.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/util/playgrounds/types.xcm.ts
@@ -0,0 +1,36 @@
+export interface AcalaAssetMetadata {
+ name: string,
+ symbol: string,
+ decimals: number,
+ minimalBalance: bigint,
+}
+
+export interface MoonbeamAssetInfo {
+ location: any,
+ metadata: {
+ name: string,
+ symbol: string,
+ decimals: number,
+ isFrozen: boolean,
+ minimalBalance: bigint,
+ },
+ existentialDeposit: bigint,
+ isSufficient: boolean,
+ unitsPerSecond: bigint,
+ numAssetsWeightHint: number,
+}
+
+export interface DemocracyStandardAccountVote {
+ balance: bigint,
+ vote: {
+ aye: boolean,
+ conviction: number,
+ },
+}
+
+export interface IForeignAssetMetadata {
+ name?: number | Uint8Array,
+ symbol?: string,
+ decimals?: number,
+ minimalBalance?: bigint,
+}
\ No newline at end of file
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -3,16 +3,18 @@
import {stringToU8a} from '@polkadot/util';
import {blake2AsHex, encodeAddress, mnemonicGenerate} from '@polkadot/util-crypto';
-import {UniqueHelper, MoonbeamHelper, ChainHelperBase, AcalaHelper, RelayHelper, WestmintHelper, AstarHelper, PolkadexHelper} from './unique';
+import {UniqueHelper, ChainHelperBase, ChainHelperBaseConstructor, HelperGroup, UniqueHelperConstructor} from './unique';
import {ApiPromise, Keyring, WsProvider} from '@polkadot/api';
import * as defs from '../../interfaces/definitions';
import {IKeyringPair} from '@polkadot/types/types';
import {EventRecord} from '@polkadot/types/interfaces';
-import {ICrossAccountId, IPovInfo, ITransactionResult, TSigner} from './types';
+import {ICrossAccountId, ILogger, IPovInfo, ISchedulerOptions, ITransactionResult, TSigner} from './types';
import {FrameSystemEventRecord, XcmV2TraitsError} from '@polkadot/types/lookup';
-import {VoidFn} from '@polkadot/api/types';
+import {SignerOptions, VoidFn} from '@polkadot/api/types';
import {Pallets} from '..';
import {spawnSync} from 'child_process';
+import {AcalaHelper, AstarHelper, MoonbeamHelper, PolkadexHelper, RelayHelper, WestmintHelper, ForeignAssetsGroup, XcmGroup, XTokensGroup, TokensGroup} from './unique.xcm';
+import {CollectiveGroup, CollectiveMembershipGroup, DemocracyGroup, ICollectiveGroup, IFellowshipGroup, RankedCollectiveGroup, ReferendaGroup} from './unique.governance';
export class SilentLogger {
log(_msg: any, _level: any): void { }
@@ -260,6 +262,192 @@
};
}
+// eslint-disable-next-line @typescript-eslint/naming-convention
+export function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {
+ return class extends Base {
+ constructor(...args: any[]) {
+ super(...args);
+ }
+
+ async executeExtrinsic(
+ sender: IKeyringPair,
+ extrinsic: string,
+ params: any[],
+ expectSuccess?: boolean,
+ options: Partial<SignerOptions> | null = null,
+ ): Promise<ITransactionResult> {
+ const call = this.constructApiCall(extrinsic, params);
+ const result = await super.executeExtrinsic(
+ sender,
+ 'api.tx.sudo.sudo',
+ [call],
+ expectSuccess,
+ options,
+ );
+
+ if(result.status === 'Fail') return result;
+
+ const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;
+ if(data.isErr) {
+ if(data.asErr.isModule) {
+ const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;
+ const metaError = super.getApi()?.registry.findMetaError(error);
+ throw new Error(`${metaError.section}.${metaError.name}`);
+ } else if(data.asErr.isToken) {
+ throw new Error(`Token: ${data.asErr.asToken}`);
+ }
+ // May be [object Object] in case of unhandled non-unit enum
+ throw new Error(`Misc: ${data.asErr.toHuman()}`);
+ }
+ return result;
+ }
+ async executeExtrinsicUncheckedWeight(
+ sender: IKeyringPair,
+ extrinsic: string,
+ params: any[],
+ expectSuccess?: boolean,
+ options: Partial<SignerOptions> | null = null,
+ ): Promise<ITransactionResult> {
+ const call = this.constructApiCall(extrinsic, params);
+ const result = await super.executeExtrinsic(
+ sender,
+ 'api.tx.sudo.sudoUncheckedWeight',
+ [call, {refTime: 0, proofSize: 0}],
+ expectSuccess,
+ options,
+ );
+
+ if(result.status === 'Fail') return result;
+
+ const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;
+ if(data.isErr) {
+ if(data.asErr.isModule) {
+ const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;
+ const metaError = super.getApi()?.registry.findMetaError(error);
+ throw new Error(`${metaError.section}.${metaError.name}`);
+ } else if(data.asErr.isToken) {
+ throw new Error(`Token: ${data.asErr.asToken}`);
+ }
+ // May be [object Object] in case of unhandled non-unit enum
+ throw new Error(`Misc: ${data.asErr.toHuman()}`);
+ }
+ return result;
+ }
+ };
+}
+
+class SchedulerGroup extends HelperGroup<UniqueHelper> {
+ constructor(helper: UniqueHelper) {
+ super(helper);
+ }
+
+ cancelScheduled(signer: TSigner, scheduledId: string) {
+ return this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.scheduler.cancelNamed',
+ [scheduledId],
+ true,
+ );
+ }
+
+ changePriority(signer: TSigner, scheduledId: string, priority: number) {
+ return this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.scheduler.changeNamedPriority',
+ [scheduledId, priority],
+ true,
+ );
+ }
+
+ scheduleAt<T extends DevUniqueHelper>(
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ return this.schedule<T>('schedule', executionBlockNumber, options);
+ }
+
+ scheduleAfter<T extends DevUniqueHelper>(
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);
+ }
+
+ schedule<T extends UniqueHelper>(
+ scheduleFn: 'schedule' | 'scheduleAfter',
+ blocksNum: number,
+ options: ISchedulerOptions = {},
+ ) {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);
+ return this.helper.clone(ScheduledHelperType, {
+ scheduleFn,
+ blocksNum,
+ options,
+ }) as T;
+ }
+}
+
+class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {
+ //todo:collator documentation
+ addInvulnerable(signer: TSigner, address: string) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);
+ }
+
+ removeInvulnerable(signer: TSigner, address: string) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);
+ }
+
+ async getInvulnerables(): Promise<string[]> {
+ return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());
+ }
+
+ /** and also total max invulnerables */
+ maxCollators(): number {
+ return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);
+ }
+
+ async getDesiredCollators(): Promise<number> {
+ return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();
+ }
+
+ setLicenseBond(signer: TSigner, amount: bigint) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);
+ }
+
+ async getLicenseBond(): Promise<bigint> {
+ return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();
+ }
+
+ obtainLicense(signer: TSigner) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);
+ }
+
+ releaseLicense(signer: TSigner) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);
+ }
+
+ forceReleaseLicense(signer: TSigner, released: string) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);
+ }
+
+ async hasLicense(address: string): Promise<bigint> {
+ return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();
+ }
+
+ onboard(signer: TSigner) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);
+ }
+
+ offboard(signer: TSigner) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);
+ }
+
+ async getCandidates(): Promise<string[]> {
+ return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());
+ }
+}
+
export class DevUniqueHelper extends UniqueHelper {
/**
* Arrange methods for tests
@@ -269,6 +457,16 @@
admin: AdminGroup;
session: SessionGroup;
testUtils: TestUtilGroup;
+ foreignAssets: ForeignAssetsGroup;
+ xcm: XcmGroup<UniqueHelper>;
+ xTokens: XTokensGroup<UniqueHelper>;
+ tokens: TokensGroup<UniqueHelper>;
+ scheduler: SchedulerGroup;
+ collatorSelection: CollatorSelectionGroup;
+ council: ICollectiveGroup;
+ technicalCommittee: ICollectiveGroup;
+ fellowship: IFellowshipGroup;
+ democracy: DemocracyGroup;
constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
options.helperBase = options.helperBase ?? DevUniqueHelper;
@@ -279,6 +477,25 @@
this.admin = new AdminGroup(this);
this.testUtils = new TestUtilGroup(this);
this.session = new SessionGroup(this);
+ this.foreignAssets = new ForeignAssetsGroup(this);
+ this.xcm = new XcmGroup(this, 'polkadotXcm');
+ this.xTokens = new XTokensGroup(this);
+ this.tokens = new TokensGroup(this);
+ this.scheduler = new SchedulerGroup(this);
+ this.collatorSelection = new CollatorSelectionGroup(this);
+ this.council = {
+ collective: new CollectiveGroup(this, 'council'),
+ membership: new CollectiveMembershipGroup(this, 'councilMembership'),
+ };
+ this.technicalCommittee = {
+ collective: new CollectiveGroup(this, 'technicalCommittee'),
+ membership: new CollectiveMembershipGroup(this, 'technicalCommitteeMembership'),
+ };
+ this.fellowship = {
+ collective: new RankedCollectiveGroup(this, 'fellowshipCollective'),
+ referenda: new ReferendaGroup(this, 'fellowshipReferenda'),
+ };
+ this.democracy = new DemocracyGroup(this);
}
async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
@@ -326,6 +543,11 @@
this.network = await UniqueHelper.detectNetwork(this.api);
this.wsEndpoint = wsEndpoint;
}
+ getSudo<T extends DevUniqueHelper>() {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const SudoHelperType = SudoHelper(this.helperBase);
+ return this.clone(SudoHelperType) as T;
+ }
}
export class DevRelayHelper extends RelayHelper {
@@ -386,19 +608,16 @@
super(logger, options);
this.wait = new WaitGroup(this);
}
-}
-
-export class DevShidenHelper extends AstarHelper {
- wait: WaitGroup;
- constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
- options.helperBase = options.helperBase ?? DevShidenHelper;
-
- super(logger, options);
- this.wait = new WaitGroup(this);
+ getSudo<T extends AstarHelper>() {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const SudoHelperType = SudoHelper(this.helperBase);
+ return this.clone(SudoHelperType) as T;
}
}
+export class DevShidenHelper extends DevAstarHelper { }
+
export class DevAcalaHelper extends AcalaHelper {
wait: WaitGroup;
@@ -408,6 +627,11 @@
super(logger, options);
this.wait = new WaitGroup(this);
}
+ getSudo<T extends AcalaHelper>() {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const SudoHelperType = SudoHelper(this.helperBase);
+ return this.clone(SudoHelperType) as T;
+ }
}
export class DevPolkadexHelper extends PolkadexHelper {
@@ -418,6 +642,12 @@
super(logger, options);
this.wait = new WaitGroup(this);
}
+
+ getSudo<T extends PolkadexHelper>() {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const SudoHelperType = SudoHelper(this.helperBase);
+ return this.clone(SudoHelperType) as T;
+ }
}
export class DevKaruraHelper extends DevAcalaHelper {}
@@ -1211,3 +1441,63 @@
}));
}
}
+
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {
+ return class extends Base {
+ scheduleFn: 'schedule' | 'scheduleAfter';
+ blocksNum: number;
+ options: ISchedulerOptions;
+
+ constructor(...args: any[]) {
+ const logger = args[0] as ILogger;
+ const options = args[1] as {
+ scheduleFn: 'schedule' | 'scheduleAfter',
+ blocksNum: number,
+ options: ISchedulerOptions
+ };
+
+ super(logger);
+
+ this.scheduleFn = options.scheduleFn;
+ this.blocksNum = options.blocksNum;
+ this.options = options.options;
+ }
+
+ executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {
+ const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);
+
+ const mandatorySchedArgs = [
+ this.blocksNum,
+ this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,
+ this.options.priority ?? null,
+ scheduledTx,
+ ];
+
+ let schedArgs;
+ let scheduleFn;
+
+ if(this.options.scheduledId) {
+ schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];
+
+ if(this.scheduleFn == 'schedule') {
+ scheduleFn = 'scheduleNamed';
+ } else if(this.scheduleFn == 'scheduleAfter') {
+ scheduleFn = 'scheduleNamedAfter';
+ }
+ } else {
+ schedArgs = mandatorySchedArgs;
+ scheduleFn = this.scheduleFn;
+ }
+
+ const extrinsic = 'api.tx.scheduler.' + scheduleFn;
+
+ return super.executeExtrinsic(
+ sender,
+ extrinsic as any,
+ schedArgs,
+ expectSuccess,
+ );
+ }
+ };
+}
\ No newline at end of file
tests/src/util/playgrounds/unique.governance.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/util/playgrounds/unique.governance.ts
@@ -0,0 +1,531 @@
+import {blake2AsHex} from '@polkadot/util-crypto';
+import {PalletDemocracyConviction} from '@polkadot/types/lookup';
+import {IPhasicEvent, TSigner} from './types';
+import {HelperGroup, UniqueHelper} from './unique';
+
+export class CollectiveGroup extends HelperGroup<UniqueHelper> {
+ /**
+ * Pallet name to make an API call to. Examples: 'council', 'technicalCommittee'
+ */
+ private collective: string;
+
+ constructor(helper: UniqueHelper, collective: string) {
+ super(helper);
+ this.collective = collective;
+ }
+
+ /**
+ * Check the result of a proposal execution for the success of the underlying proposed extrinsic.
+ * @param events events of the proposal execution
+ * @returns proposal hash
+ */
+ private checkExecutedEvent(events: IPhasicEvent[]): string {
+ const executionEvents = events.filter(x =>
+ x.event.section === this.collective && (x.event.method === 'Executed' || x.event.method === 'MemberExecuted'));
+
+ if(executionEvents.length != 1) {
+ if(events.filter(x => x.event.section === this.collective && x.event.method === 'Disapproved').length > 0)
+ throw new Error(`Disapproved by ${this.collective}`);
+ else
+ throw new Error(`Expected one 'Executed' or 'MemberExecuted' event for ${this.collective}`);
+ }
+
+ const result = (executionEvents[0].event.data as any).result;
+
+ if(result.isErr) {
+ if(result.asErr.isModule) {
+ const error = result.asErr.asModule;
+ const metaError = this.helper.getApi()?.registry.findMetaError(error);
+ throw new Error(`Proposal execution failed with ${metaError.section}.${metaError.name}`);
+ } else {
+ throw new Error('Proposal execution failed with ' + result.asErr.toHuman());
+ }
+ }
+
+ return (executionEvents[0].event.data as any).proposalHash;
+ }
+
+ /**
+ * Returns an array of members' addresses.
+ */
+ async getMembers() {
+ return (await this.helper.callRpc(`api.query.${this.collective}.members`, [])).toHuman();
+ }
+
+ /**
+ * Returns the optional address of the prime member of the collective.
+ */
+ async getPrimeMember() {
+ return (await this.helper.callRpc(`api.query.${this.collective}.prime`, [])).toHuman();
+ }
+
+ /**
+ * Returns an array of proposal hashes that are currently active for this collective.
+ */
+ async getProposals() {
+ return (await this.helper.callRpc(`api.query.${this.collective}.proposals`, [])).toHuman();
+ }
+
+ /**
+ * Returns the call originally encoded under the specified hash.
+ * @param hash h256-encoded proposal
+ * @returns the optional call that the proposal hash stands for.
+ */
+ async getProposalCallOf(hash: string) {
+ return (await this.helper.callRpc(`api.query.${this.collective}.proposalOf`, [hash])).toHuman();
+ }
+
+ /**
+ * Returns the total number of proposals so far.
+ */
+ async getTotalProposalsCount() {
+ return (await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, [])).toNumber();
+ }
+
+ /**
+ * Creates a new proposal up for voting. If the threshold is set to 1, the proposal will be executed immediately.
+ * @param signer keyring of the proposer
+ * @param proposal constructed call to be executed if the proposal is successful
+ * @param voteThreshold minimal number of votes for the proposal to be verified and executed
+ * @param lengthBound byte length of the encoded call
+ * @returns promise of extrinsic execution and its result
+ */
+ async propose(signer: TSigner, proposal: any, voteThreshold: number, lengthBound = 10000) {
+ return await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [voteThreshold, proposal, lengthBound]);
+ }
+
+ /**
+ * Casts a vote to either approve or reject a proposal.
+ * @param signer keyring of the voter
+ * @param proposalHash hash of the proposal to be voted for
+ * @param proposalIndex absolute index of the proposal used for absolutely nothing but throwing pointless errors
+ * @param approve aye or nay
+ * @returns promise of extrinsic execution and its result
+ */
+ vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve]);
+ }
+
+ /**
+ * Executes a call immediately as a member of the collective. Needed for the Member origin.
+ * @param signer keyring of the executor member
+ * @param proposal constructed call to be executed by the member
+ * @param lengthBound byte length of the encoded call
+ * @returns promise of extrinsic execution
+ */
+ async execute(signer: TSigner, proposal: any, lengthBound = 10000) {
+ const result = await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.execute`, [proposal, lengthBound]);
+ this.checkExecutedEvent(result.result.events);
+ return result;
+ }
+
+ /**
+ * Attempt to close and execute a proposal. Note that there must already be enough votes to meet the threshold set when proposing.
+ * @param signer keyring of the executor. Can be absolutely anyone.
+ * @param proposalHash hash of the proposal to close
+ * @param proposalIndex index of the proposal generated on its creation
+ * @param weightBound weight of the proposed call. Can be obtained by calling `paymentInfo()` on the call.
+ * @param lengthBound byte length of the encoded call
+ * @returns promise of extrinsic execution and its result
+ */
+ async close(
+ signer: TSigner,
+ proposalHash: string,
+ proposalIndex: number,
+ weightBound: [number, number] | any = [20_000_000_000, 1000_000],
+ lengthBound = 10_000,
+ ) {
+ const result = await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [
+ proposalHash,
+ proposalIndex,
+ weightBound,
+ lengthBound,
+ ]);
+ this.checkExecutedEvent(result.result.events);
+ return result;
+ }
+
+ /**
+ * Shut down a proposal, regardless of its current state.
+ * @param signer keyring of the disapprover. Must be root
+ * @param proposalHash hash of the proposal to close
+ * @returns promise of extrinsic execution and its result
+ */
+ disapproveProposal(signer: TSigner, proposalHash: string) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.disapproveProposal`, [proposalHash]);
+ }
+}
+
+export class CollectiveMembershipGroup extends HelperGroup<UniqueHelper> {
+ /**
+ * Pallet name to make an API call to. Examples: 'councilMembership', 'technicalCommitteeMembership'
+ */
+ private membership: string;
+
+ constructor(helper: UniqueHelper, membership: string) {
+ super(helper);
+ this.membership = membership;
+ }
+
+ /**
+ * Returns an array of members' addresses according to the membership pallet's perception.
+ * Note that it does not recognize the original pallet's members set with `setMembers()`.
+ */
+ async getMembers() {
+ return (await this.helper.callRpc(`api.query.${this.membership}.members`, [])).toHuman();
+ }
+
+ /**
+ * Returns the optional address of the prime member of the collective.
+ */
+ async getPrimeMember() {
+ return (await this.helper.callRpc(`api.query.${this.membership}.prime`, [])).toHuman();
+ }
+
+ /**
+ * Add a member to the collective.
+ * @param signer keyring of the setter. Must be root
+ * @param member address of the member to add
+ * @returns promise of extrinsic execution and its result
+ */
+ addMember(signer: TSigner, member: string) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.addMember`, [member]);
+ }
+
+ addMemberCall(member: string) {
+ return this.helper.constructApiCall(`api.tx.${this.membership}.addMember`, [member]);
+ }
+
+ /**
+ * Remove a member from the collective.
+ * @param signer keyring of the setter. Must be root
+ * @param member address of the member to remove
+ * @returns promise of extrinsic execution and its result
+ */
+ removeMember(signer: TSigner, member: string) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.removeMember`, [member]);
+ }
+
+ removeMemberCall(member: string) {
+ return this.helper.constructApiCall(`api.tx.${this.membership}.removeMember`, [member]);
+ }
+
+ /**
+ * Set members of the collective to the given list of addresses.
+ * @param signer keyring of the setter. Must be root (for the direct call, bypassing a public motion)
+ * @param members addresses of the members to set
+ * @returns promise of extrinsic execution and its result
+ */
+ resetMembers(signer: TSigner, members: string[]) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.resetMembers`, [members]);
+ }
+
+ /**
+ * Set the collective's prime member to the given address.
+ * @param signer keyring of the setter. Must be root (for the direct call, bypassing a public motion)
+ * @param prime address of the prime member of the collective
+ * @returns promise of extrinsic execution and its result
+ */
+ setPrime(signer: TSigner, prime: string) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.setPrime`, [prime]);
+ }
+
+ setPrimeCall(member: string) {
+ return this.helper.constructApiCall(`api.tx.${this.membership}.setPrime`, [member]);
+ }
+
+ /**
+ * Remove the collective's prime member.
+ * @param signer keyring of the setter. Must be root (for the direct call, bypassing a public motion)
+ * @returns promise of extrinsic execution and its result
+ */
+ clearPrime(signer: TSigner) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.clearPrime`, []);
+ }
+
+ clearPrimeCall() {
+ return this.helper.constructApiCall(`api.tx.${this.membership}.clearPrime`, []);
+ }
+}
+
+export class RankedCollectiveGroup extends HelperGroup<UniqueHelper> {
+ /**
+ * Pallet name to make an API call to. Examples: 'FellowshipCollective'
+ */
+ private collective: string;
+
+ constructor(helper: UniqueHelper, collective: string) {
+ super(helper);
+ this.collective = collective;
+ }
+
+ addMember(signer: TSigner, newMember: string) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.addMember`, [newMember]);
+ }
+
+ addMemberCall(newMember: string) {
+ return this.helper.constructApiCall(`api.tx.${this.collective}.addMember`, [newMember]);
+ }
+
+ removeMember(signer: TSigner, member: string, minRank: number) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.removeMember`, [member, minRank]);
+ }
+
+ removeMemberCall(newMember: string, minRank: number) {
+ return this.helper.constructApiCall(`api.tx.${this.collective}.removeMember`, [newMember, minRank]);
+ }
+
+ promote(signer: TSigner, member: string) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.promoteMember`, [member]);
+ }
+
+ promoteCall(member: string) {
+ return this.helper.constructApiCall(`api.tx.${this.collective}.promoteMember`, [member]);
+ }
+
+ demote(signer: TSigner, member: string) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.demoteMember`, [member]);
+ }
+
+ demoteCall(newMember: string) {
+ return this.helper.constructApiCall(`api.tx.${this.collective}.demoteMember`, [newMember]);
+ }
+
+ vote(signer: TSigner, pollIndex: number, aye: boolean) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [pollIndex, aye]);
+ }
+
+ async getMembers() {
+ return (await this.helper.getApi().query.fellowshipCollective.members.keys())
+ .map((key) => key.args[0].toString());
+ }
+
+ async getMemberRank(member: string) {
+ return (await this.helper.callRpc('api.query.fellowshipCollective.members', [member])).toJSON().rank;
+ }
+}
+
+export class ReferendaGroup extends HelperGroup<UniqueHelper> {
+ /**
+ * Pallet name to make an API call to. Examples: 'FellowshipReferenda'
+ */
+ private referenda: string;
+
+ constructor(helper: UniqueHelper, referenda: string) {
+ super(helper);
+ this.referenda = referenda;
+ }
+
+ submit(
+ signer: TSigner,
+ proposalOrigin: string,
+ proposal: any,
+ enactmentMoment: any,
+ ) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.referenda}.submit`, [
+ {Origins: proposalOrigin},
+ proposal,
+ enactmentMoment,
+ ]);
+ }
+
+ placeDecisionDeposit(signer: TSigner, referendumIndex: number) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.referenda}.placeDecisionDeposit`, [referendumIndex]);
+ }
+
+ cancel(signer: TSigner, referendumIndex: number) {
+ return this.helper.executeExtrinsic(signer, `api.tx.${this.referenda}.cancel`, [referendumIndex]);
+ }
+
+ cancelCall(referendumIndex: number) {
+ return this.helper.constructApiCall(`api.tx.${this.referenda}.cancel`, [referendumIndex]);
+ }
+
+ async referendumInfo(referendumIndex: number) {
+ return (await this.helper.callRpc(`api.query.${this.referenda}.referendumInfoFor`, [referendumIndex])).toJSON();
+ }
+
+ async enactmentEventId(referendumIndex: number) {
+ const api = await this.helper.getApi();
+
+ const bytes = api.createType('([u8;8], Text, u32)', ['assembly', 'enactment', referendumIndex]).toU8a();
+ return blake2AsHex(bytes, 256);
+ }
+}
+
+export interface IFellowshipGroup {
+ collective: RankedCollectiveGroup;
+ referenda: ReferendaGroup;
+}
+
+export interface ICollectiveGroup {
+ collective: CollectiveGroup;
+ membership: CollectiveMembershipGroup;
+}
+
+export class DemocracyGroup extends HelperGroup<UniqueHelper> {
+ // todo displace proposal into types?
+ propose(signer: TSigner, call: any, deposit: bigint) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.propose', [{Inline: call.method.toHex()}, deposit]);
+ }
+
+ proposeWithPreimage(signer: TSigner, preimage: string, deposit: bigint) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.propose', [{Legacy: preimage}, deposit]);
+ }
+
+ proposeCall(call: any, deposit: bigint) {
+ return this.helper.constructApiCall('api.tx.democracy.propose', [{Inline: call.method.toHex()}, deposit]);
+ }
+
+ second(signer: TSigner, proposalIndex: number) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.second', [proposalIndex]);
+ }
+
+ externalPropose(signer: TSigner, proposalCall: any) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalPropose', [{Inline: proposalCall.method.toHex()}]);
+ }
+
+ externalProposeMajority(signer: TSigner, proposalCall: any) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalProposeMajority', [{Inline: proposalCall.method.toHex()}]);
+ }
+
+ externalProposeDefault(signer: TSigner, proposalCall: any) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalProposeDefault', [{Inline: proposalCall.method.toHex()}]);
+ }
+
+ externalProposeDefaultWithPreimage(signer: TSigner, preimage: string) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalProposeDefault', [{Legacy: preimage}]);
+ }
+
+ externalProposeCall(proposalCall: any) {
+ return this.helper.constructApiCall('api.tx.democracy.externalPropose', [{Inline: proposalCall.method.toHex()}]);
+ }
+
+ externalProposeMajorityCall(proposalCall: any) {
+ return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [{Inline: proposalCall.method.toHex()}]);
+ }
+
+ externalProposeDefaultCall(proposalCall: any) {
+ return this.helper.constructApiCall('api.tx.democracy.externalProposeDefault', [{Inline: proposalCall.method.toHex()}]);
+ }
+
+ externalProposeDefaultWithPreimageCall(preimage: string) {
+ return this.helper.constructApiCall('api.tx.democracy.externalProposeDefault', [{Legacy: preimage}]);
+ }
+
+ // ... and blacklist external proposal hash.
+ vetoExternal(signer: TSigner, proposalHash: string) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.vetoExternal', [proposalHash]);
+ }
+
+ vetoExternalCall(proposalHash: string) {
+ return this.helper.constructApiCall('api.tx.democracy.vetoExternal', [proposalHash]);
+ }
+
+ blacklist(signer: TSigner, proposalHash: string, referendumIndex: number | null = null) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.blacklist', [proposalHash, referendumIndex]);
+ }
+
+ blacklistCall(proposalHash: string, referendumIndex: number | null = null) {
+ return this.helper.constructApiCall('api.tx.democracy.blacklist', [proposalHash, referendumIndex]);
+ }
+
+ // proposal. CancelProposalOrigin (root or all techcom)
+ cancelProposal(signer: TSigner, proposalIndex: number) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.cancelProposal', [proposalIndex]);
+ }
+
+ cancelProposalCall(proposalIndex: number) {
+ return this.helper.constructApiCall('api.tx.democracy.cancelProposal', [proposalIndex]);
+ }
+
+ clearPublicProposals(signer: TSigner) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.clearPublicProposals', []);
+ }
+
+ fastTrack(signer: TSigner, proposalHash: string, votingPeriod: number, delayPeriod: number) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);
+ }
+
+ fastTrackCall(proposalHash: string, votingPeriod: number, delayPeriod: number) {
+ return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);
+ }
+
+ // referendum. CancellationOrigin (TechCom member)
+ emergencyCancel(signer: TSigner, referendumIndex: number) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.emergencyCancel', [referendumIndex]);
+ }
+
+ emergencyCancelCall(referendumIndex: number) {
+ return this.helper.constructApiCall('api.tx.democracy.emergencyCancel', [referendumIndex]);
+ }
+
+ vote(signer: TSigner, referendumIndex: number, vote: any) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, vote]);
+ }
+
+ removeVote(signer: TSigner, referendumIndex: number, targetAccount?: string) {
+ if(targetAccount) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.removeOtherVote', [targetAccount, referendumIndex]);
+ } else {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.removeVote', [referendumIndex]);
+ }
+ }
+
+ unlock(signer: TSigner, targetAccount: string) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.unlock', [targetAccount]);
+ }
+
+ delegate(signer: TSigner, toAccount: string, conviction: PalletDemocracyConviction, balance: bigint) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.delegate', [toAccount, conviction, balance]);
+ }
+
+ undelegate(signer: TSigner) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.undelegate', []);
+ }
+
+ async referendumInfo(referendumIndex: number) {
+ return (await this.helper.callRpc('api.query.democracy.referendumInfoOf', [referendumIndex])).toJSON();
+ }
+
+ async publicProposals() {
+ return (await this.helper.callRpc('api.query.democracy.publicProps', [])).toJSON();
+ }
+
+ async findPublicProposal(proposalIndex: number) {
+ const proposalInfo = (await this.publicProposals()).find((proposalInfo: any[]) => proposalInfo[0] == proposalIndex);
+
+ return proposalInfo ? proposalInfo[1] : null;
+ }
+
+ async expectPublicProposal(proposalIndex: number) {
+ const proposal = await this.findPublicProposal(proposalIndex);
+
+ if(proposal) {
+ return proposal;
+ } else {
+ throw Error(`Proposal #${proposalIndex} is expected to exist`);
+ }
+ }
+
+ async getExternalProposal() {
+ return (await this.helper.callRpc('api.query.democracy.nextExternal', []));
+ }
+
+ async expectExternalProposal() {
+ const proposal = await this.getExternalProposal();
+
+ if(proposal) {
+ return proposal;
+ } else {
+ throw Error('An external proposal is expected to exist');
+ }
+ }
+
+ /* setMetadata? */
+
+ /* todo?
+ referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {
+ return this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);
+ }*/
+}
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 {SignerOptions} from '@polkadot/api/types/submittable';10import '../../interfaces/augment-api';11import {AugmentedSubmittables} from '@polkadot/api-base/types/submittable';12import {ApiInterfaceEvents} from '@polkadot/api/types';13import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a, blake2AsHex} from '@polkadot/util-crypto';14import {IKeyringPair} from '@polkadot/types/types';15import {hexToU8a} from '@polkadot/util/hex';16import {u8aConcat} from '@polkadot/util/u8a';17import {18 IApiListeners,19 IBlock,20 IEvent,21 IChainProperties,22 ICollectionCreationOptions,23 ICollectionLimits,24 ICollectionPermissions,25 ICrossAccountId,26 ICrossAccountIdLower,27 ILogger,28 INestingPermissions,29 IProperty,30 IStakingInfo,31 ISchedulerOptions,32 ISubstrateBalance,33 IToken,34 ITokenPropertyPermission,35 ITransactionResult,36 IUniqueHelperLog,37 TApiAllowedListeners,38 TEthereumAccount,39 TSigner,40 TSubstrateAccount,41 TNetworks,42 IForeignAssetMetadata,43 AcalaAssetMetadata,44 MoonbeamAssetInfo,45 DemocracyStandardAccountVote,46 IEthCrossAccountId,47 IPhasicEvent,48} from './types';49import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';50import type {Vec} from '@polkadot/types-codec';51import {FrameSystemEventRecord, PalletDemocracyConviction} from '@polkadot/types/lookup';5253export class CrossAccountId {54 Substrate!: TSubstrateAccount;55 Ethereum!: TEthereumAccount;5657 constructor(account: ICrossAccountId) {58 if('Substrate' in account) this.Substrate = account.Substrate;59 else this.Ethereum = account.Ethereum;60 }6162 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {63 switch (domain) {64 case 'Substrate': return new CrossAccountId({Substrate: account.address});65 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();66 }67 }6869 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {70 if('substrate' in address) return new CrossAccountId({Substrate: address.substrate});71 else return new CrossAccountId({Ethereum: address.ethereum});72 }7374 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {75 return encodeAddress(decodeAddress(address), ss58Format);76 }7778 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {79 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});80 }8182 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {83 if(this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);84 return this;85 }8687 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {88 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));89 }9091 toEthereum(): CrossAccountId {92 if(this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});93 return this;94 }9596 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {97 return evmToAddress(address, ss58Format);98 }99100 toSubstrate(ss58Format?: number): CrossAccountId {101 if(this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});102 return this;103 }104105 toLowerCase(): CrossAccountId {106 if(this.Substrate) this.Substrate = this.Substrate.toLowerCase();107 if(this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();108 return this;109 }110}111112const nesting = {113 toChecksumAddress(address: string): string {114 if(typeof address === 'undefined') return '';115116 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);117118 address = address.toLowerCase().replace(/^0x/i, '');119 const addressHash = keccakAsHex(address).replace(/^0x/i, '');120 const checksumAddress = ['0x'];121122 for(let i = 0; i < address.length; i++) {123 // If ith character is 8 to f then make it uppercase124 if(parseInt(addressHash[i], 16) > 7) {125 checksumAddress.push(address[i].toUpperCase());126 } else {127 checksumAddress.push(address[i]);128 }129 }130 return checksumAddress.join('');131 },132 tokenIdToAddress(collectionId: number, tokenId: number) {133 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);134 },135};136137class UniqueUtil {138 static transactionStatus = {139 NOT_READY: 'NotReady',140 FAIL: 'Fail',141 SUCCESS: 'Success',142 };143144 static chainLogType = {145 EXTRINSIC: 'extrinsic',146 RPC: 'rpc',147 };148149 static getTokenAccount(token: IToken): CrossAccountId {150 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});151 }152153 static getTokenAddress(token: IToken): string {154 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);155 }156157 static getDefaultLogger(): ILogger {158 return {159 log(msg: any, level = 'INFO') {160 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));161 },162 level: {163 ERROR: 'ERROR',164 WARNING: 'WARNING',165 INFO: 'INFO',166 },167 };168 }169170 static vec2str(arr: string[] | number[]) {171 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');172 }173174 static str2vec(string: string) {175 if(typeof string !== 'string') return string;176 return Array.from(string).map(x => x.charCodeAt(0));177 }178179 static fromSeed(seed: string, ss58Format = 42) {180 const keyring = new Keyring({type: 'sr25519', ss58Format});181 return keyring.addFromUri(seed);182 }183184 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {185 if(creationResult.status !== this.transactionStatus.SUCCESS) {186 throw Error('Unable to create collection!');187 }188189 let collectionId = null;190 creationResult.result.events.forEach(({event: {data, method, section}}) => {191 if((section === 'common') && (method === 'CollectionCreated')) {192 collectionId = parseInt(data[0].toString(), 10);193 }194 });195196 if(collectionId === null) {197 throw Error('No CollectionCreated event was found!');198 }199200 return collectionId;201 }202203 static extractTokensFromCreationResult(creationResult: ITransactionResult): {204 success: boolean,205 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],206 } {207 if(creationResult.status !== this.transactionStatus.SUCCESS) {208 throw Error('Unable to create tokens!');209 }210 let success = false;211 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];212 creationResult.result.events.forEach(({event: {data, method, section}}) => {213 if(method === 'ExtrinsicSuccess') {214 success = true;215 } else if((section === 'common') && (method === 'ItemCreated')) {216 tokens.push({217 collectionId: parseInt(data[0].toString(), 10),218 tokenId: parseInt(data[1].toString(), 10),219 owner: data[2].toHuman(),220 amount: data[3].toBigInt(),221 });222 }223 });224 return {success, tokens};225 }226227 static extractTokensFromBurnResult(burnResult: ITransactionResult): {228 success: boolean,229 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],230 } {231 if(burnResult.status !== this.transactionStatus.SUCCESS) {232 throw Error('Unable to burn tokens!');233 }234 let success = false;235 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];236 burnResult.result.events.forEach(({event: {data, method, section}}) => {237 if(method === 'ExtrinsicSuccess') {238 success = true;239 } else if((section === 'common') && (method === 'ItemDestroyed')) {240 tokens.push({241 collectionId: parseInt(data[0].toString(), 10),242 tokenId: parseInt(data[1].toString(), 10),243 owner: data[2].toHuman(),244 amount: data[3].toBigInt(),245 });246 }247 });248 return {success, tokens};249 }250251 static findCollectionInEvents(events: { event: IEvent }[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {252 let eventId = null;253 events.forEach(({event: {data, method, section}}) => {254 if((section === expectedSection) && (method === expectedMethod)) {255 eventId = parseInt(data[0].toString(), 10);256 }257 });258259 if(eventId === null) {260 throw Error(`No ${expectedMethod} event was found!`);261 }262 return eventId === collectionId;263 }264265 static isTokenTransferSuccess(events: { event: IEvent }[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {266 const normalizeAddress = (address: string | ICrossAccountId) => {267 if(typeof address === 'string') return address;268 const obj = {} as any;269 Object.keys(address).forEach(k => {270 obj[k.toLocaleLowerCase()] = (address as any)[k];271 });272 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);273 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();274 return address;275 };276 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;277 events.forEach(({event: {data, method, section}}) => {278 if((section === 'common') && (method === 'Transfer')) {279 const hData = (data as any).toJSON();280 transfer = {281 collectionId: hData[0],282 tokenId: hData[1],283 from: normalizeAddress(hData[2]),284 to: normalizeAddress(hData[3]),285 amount: BigInt(hData[4]),286 };287 }288 });289 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;290 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);291 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);292 isSuccess = isSuccess && amount === transfer.amount;293 return isSuccess;294 }295296 static bigIntToDecimals(number: bigint, decimals = 18) {297 const numberStr = number.toString();298 const dotPos = numberStr.length - decimals;299300 if(dotPos <= 0) {301 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;302 } else {303 const intPart = numberStr.substring(0, dotPos);304 const fractPart = numberStr.substring(dotPos);305 return intPart + '.' + fractPart;306 }307 }308}309310class UniqueEventHelper {311 private static extractIndex(index: any): [number, number] | string {312 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];313 return index.toJSON();314 }315316 private static extractSub(data: any, subTypes: any): { [key: string]: any } {317 let obj: any = {};318 let index = 0;319320 if(data.entries) {321 for(const [key, value] of data.entries()) {322 obj[key] = this.extractData(value, subTypes[index]);323 index++;324 }325 } else obj = data.toJSON();326327 return obj;328 }329330 private static toHuman(data: any) {331 return data && data.toHuman ? data.toHuman() : `${data}`;332 }333334 private static extractData(data: any, type: any): any {335 if(!type) return this.toHuman(data);336 if(['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();337 if(['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();338 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);339 return this.toHuman(data);340 }341342 public static extractEvents(events: { event: any, phase: any }[]): IEvent[] {343 const parsedEvents: IEvent[] = [];344345 events.forEach((record) => {346 const {event, phase} = record;347 const types = event.typeDef;348349 const eventData: IEvent = {350 section: event.section.toString(),351 method: event.method.toString(),352 index: this.extractIndex(event.index),353 data: [],354 phase: phase.toJSON(),355 };356357 event.data.forEach((val: any, index: number) => {358 eventData.data.push(this.extractData(val, types[index]));359 });360361 parsedEvents.push(eventData);362 });363364 return parsedEvents;365 }366}367const InvalidTypeSymbol = Symbol('Invalid type');368// eslint-disable-next-line @typescript-eslint/no-unused-vars369export type Invalid<ErrorMessage> =370 | ((371 invalidType: typeof InvalidTypeSymbol,372 ..._: typeof InvalidTypeSymbol[]373 ) => typeof InvalidTypeSymbol)374 | null375 | undefined;376// Has slightly better error messages than Get377type Get2<T, P extends string, E> =378 P extends `${infer Key}.${infer Key2}` ? Key extends keyof T ? Key2 extends keyof T[Key] ? T[Key][Key2] : E : E : E;379type ForceFunction<T> = T extends (...args: any) => any ? T : (...args: any) => Invalid<'not a function'>;380381export class ChainHelperBase {382 helperBase: any;383384 transactionStatus = UniqueUtil.transactionStatus;385 chainLogType = UniqueUtil.chainLogType;386 util: typeof UniqueUtil;387 eventHelper: typeof UniqueEventHelper;388 logger: ILogger;389 api: ApiPromise | null;390 forcedNetwork: TNetworks | null;391 network: TNetworks | null;392 wsEndpoint: string | null;393 chainLog: IUniqueHelperLog[];394 children: ChainHelperBase[];395 address: AddressGroup;396 chain: ChainGroup;397398 constructor(logger?: ILogger, helperBase?: any) {399 this.helperBase = helperBase;400401 this.util = UniqueUtil;402 this.eventHelper = UniqueEventHelper;403 if(typeof logger == 'undefined') logger = this.util.getDefaultLogger();404 this.logger = logger;405 this.api = null;406 this.forcedNetwork = null;407 this.network = null;408 this.wsEndpoint = null;409 this.chainLog = [];410 this.children = [];411 this.address = new AddressGroup(this);412 this.chain = new ChainGroup(this);413 }414415 clone(helperCls: ChainHelperBaseConstructor, options: { [key: string]: any } = {}) {416 Object.setPrototypeOf(helperCls.prototype, this);417 const newHelper = new helperCls(this.logger, options);418419 newHelper.api = this.api;420 newHelper.network = this.network;421 newHelper.forceNetwork = this.forceNetwork;422423 this.children.push(newHelper);424425 return newHelper;426 }427428 getEndpoint(): string {429 if(this.wsEndpoint === null) throw Error('No connection was established');430 return this.wsEndpoint;431 }432433 getApi(): ApiPromise {434 if(this.api === null) throw Error('API not initialized');435 return this.api;436 }437438 async subscribeEvents(expectedEvents: { section: string, names: string[] }[]) {439 const collectedEvents: IEvent[] = [];440 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {441 const ievents = this.eventHelper.extractEvents(events);442 ievents.forEach((event) => {443 expectedEvents.forEach((e => {444 if(event.section === e.section && e.names.includes(event.method)) {445 collectedEvents.push(event);446 }447 }));448 });449 });450 return {unsubscribe: unsubscribe as any, collectedEvents};451 }452453 clearChainLog(): void {454 this.chainLog = [];455 }456457 forceNetwork(value: TNetworks): void {458 this.forcedNetwork = value;459 }460461 async connect(wsEndpoint: string, listeners?: IApiListeners) {462 if(this.api !== null) throw Error('Already connected');463 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);464 this.wsEndpoint = wsEndpoint;465 this.api = api;466 this.network = network;467 }468469 async disconnect() {470 for(const child of this.children) {471 child.clearApi();472 }473474 if(this.api === null) return;475 await this.api.disconnect();476 this.clearApi();477 }478479 clearApi() {480 this.api = null;481 this.network = null;482 }483484 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {485 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;486 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];487488 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;489490 if(['quartz', 'unique', 'sapphire'].indexOf(spec.specName) > -1) return spec.specName;491 return 'opal';492 }493494 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {495 if(!wsEndpoint) throw new Error('wsEndpoint was not set');496 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});497 await api.isReady;498499 const network = await this.detectNetwork(api);500501 await api.disconnect();502503 return network;504 }505506 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{507 api: ApiPromise;508 network: TNetworks;509 }> {510 if(typeof network === 'undefined' || network === null) network = 'opal';511 if(!wsEndpoint) throw new Error('wsEndpoint was not set');512 const supportedRPC = {513 opal: {514 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,515 },516 quartz: {517 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,518 },519 unique: {520 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,521 },522 rococo: {},523 westend: {},524 moonbeam: {},525 moonriver: {},526 acala: {},527 karura: {},528 westmint: {},529 };530 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);531 const rpc = supportedRPC[network];532533 // TODO: investigate how to replace rpc in runtime534 // api._rpcCore.addUserInterfaces(rpc);535536 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});537538 await api.isReadyOrError;539540 if(typeof listeners === 'undefined') listeners = {};541 for(const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {542 if(!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;543 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);544 }545546 return {api, network};547 }548549 getTransactionStatus(data: { events: { event: IEvent }[], status: any }) {550 const {events, status} = data;551 if(status.isReady) {552 return this.transactionStatus.NOT_READY;553 }554 if(status.isBroadcast) {555 return this.transactionStatus.NOT_READY;556 }557 if(status.isInBlock || status.isFinalized) {558 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');559 if(errors.length > 0) {560 return this.transactionStatus.FAIL;561 }562 if(events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {563 return this.transactionStatus.SUCCESS;564 }565 }566567 return this.transactionStatus.FAIL;568 }569570 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {571 const sign = (callback: any) => {572 if(options !== null) return transaction.signAndSend(sender, options, callback);573 return transaction.signAndSend(sender, callback);574 };575 // eslint-disable-next-line no-async-promise-executor576 return new Promise(async (resolve, reject) => {577 try {578 const unsub = await sign((result: any) => {579 const status = this.getTransactionStatus(result);580581 if(status === this.transactionStatus.SUCCESS) {582 this.logger.log(`${label} successful`);583 unsub();584 resolve({result, status, blockHash: result.status.asInBlock.toHuman()});585 } else if(status === this.transactionStatus.FAIL) {586 let moduleError = null;587588 if(result.hasOwnProperty('dispatchError')) {589 const dispatchError = result['dispatchError'];590591 if(dispatchError) {592 if(dispatchError.isModule) {593 const modErr = dispatchError.asModule;594 const errorMeta = dispatchError.registry.findMetaError(modErr);595596 moduleError = `${errorMeta.section}.${errorMeta.name}`;597 } else if(dispatchError.isToken) {598 moduleError = `Token: ${dispatchError.asToken}`;599 } else {600 // May be [object Object] in case of unhandled non-unit enum601 moduleError = `Misc: ${dispatchError.toHuman()}`;602 }603 } else {604 this.logger.log(result, this.logger.level.ERROR);605 }606 }607608 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);609 unsub();610 reject({status, moduleError, result});611 }612 });613 } catch (e) {614 this.logger.log(e, this.logger.level.ERROR);615 reject(e);616 }617 });618 }619620 async signTransactionWithoutSending(signer: TSigner, tx: any) {621 const api = this.getApi();622 const signingInfo = await api.derive.tx.signingInfo(signer.address);623624 tx.sign(signer, {625 blockHash: api.genesisHash,626 genesisHash: api.genesisHash,627 runtimeVersion: api.runtimeVersion,628 nonce: signingInfo.nonce,629 });630631 return tx.toHex();632 }633634 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {635 const api = this.getApi();636 const signingInfo = await api.derive.tx.signingInfo(signer.address);637638 // We need to sign the tx because639 // unsigned transactions does not have an inclusion fee640 tx.sign(signer, {641 blockHash: api.genesisHash,642 genesisHash: api.genesisHash,643 runtimeVersion: api.runtimeVersion,644 nonce: signingInfo.nonce,645 });646647 if(len === null) {648 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;649 } else {650 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;651 }652 }653654 constructApiCall(apiCall: string, params: any[]) {655 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);656 let call = this.getApi() as any;657 for(const part of apiCall.slice(4).split('.')) {658 call = call[part];659 if(!call) {660 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';661 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);662 }663 }664 return call(...params);665 }666667 encodeApiCall(apiCall: string, params: any[]) {668 return this.constructApiCall(apiCall, params).method.toHex();669 }670671 async executeExtrinsic<672 E extends string,673 V extends (674 ...args: any) => any = ForceFunction<675 Get2<676 AugmentedSubmittables<'promise'>,677 E, (...args: any) => Invalid<'not found'>678 >679 >680 >(681 sender: TSigner,682 extrinsic: `api.tx.${E}`,683 params: Parameters<V>,684 expectSuccess = true,685 options: Partial<SignerOptions> | null = null,/*, failureMessage='expected success'*/686 ): Promise<ITransactionResult> {687 if(this.api === null) throw Error('API not initialized');688689 const startTime = (new Date()).getTime();690 let result: ITransactionResult;691 let events: IEvent[] = [];692 try {693 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;694 events = this.eventHelper.extractEvents(result.result.events);695 const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');696 if(errorEvent)697 throw Error(errorEvent.method + ': ' + extrinsic);698 }699 catch (e) {700 if(!(e as object).hasOwnProperty('status')) throw e;701 result = e as ITransactionResult;702 }703704 const endTime = (new Date()).getTime();705706 const log = {707 executedAt: endTime,708 executionTime: endTime - startTime,709 type: this.chainLogType.EXTRINSIC,710 status: result.status,711 call: extrinsic,712 signer: this.getSignerAddress(sender),713 params,714 } as IUniqueHelperLog;715716 let errorMessage = '';717718 if(result.status !== this.transactionStatus.SUCCESS) {719 if(result.moduleError) {720 errorMessage = typeof result.moduleError === 'string'721 ? result.moduleError722 : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;723 log.moduleError = errorMessage;724 }725 else if(result.result.dispatchError) log.dispatchError = result.result.dispatchError;726 }727 if(events.length > 0) log.events = events;728729 this.chainLog.push(log);730731 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {732 if(result.moduleError) throw Error(`${errorMessage}`);733 else if(result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));734 }735 return result as any;736 }737 executeExtrinsicUncheckedWeight<738 E extends string,739 V extends (740 ...args: any) => any = ForceFunction<741 Get2<742 AugmentedSubmittables<'promise'>,743 E, (...args: any) => Invalid<'not found'>744 >745 >746 >(747 sender: TSigner,748 extrinsic: `api.tx.${E}`,749 params: Parameters<V>,750 expectSuccess = true,751 options: Partial<SignerOptions> | null = null,/*, failureMessage='expected success'*/752 ): Promise<ITransactionResult> {753 throw new Error('executeExtrinsicUncheckedWeight only supported in sudo');754 }755756 async callRpc757 // TODO: make it strongly typed, or use api.query/api.rpc directly758 // <759 // K extends 'rpc' | 'query',760 // E extends string,761 // V extends (...args: any) => any = ForceFunction<762 // Get2<763 // K extends 'rpc' ? DecoratedRpc<'promise', RpcInterface> : QueryableStorage<'promise'>,764 // E, (...args: any) => Invalid<'not found'>765 // >766 // >,767 // P = Parameters<V>,768 // >769 (rpc: string, params?: any[]): Promise<any> {770771 if(typeof params === 'undefined') params = [] as any;772 if(this.api === null) throw Error('API not initialized');773 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);774775 const startTime = (new Date()).getTime();776 let result;777 let error = null;778 const log = {779 type: this.chainLogType.RPC,780 call: rpc,781 params,782 } as any as IUniqueHelperLog;783784 try {785 result = await this.constructApiCall(rpc, params as any);786 }787 catch (e) {788 error = e;789 }790791 const endTime = (new Date()).getTime();792793 log.executedAt = endTime;794 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';795 log.executionTime = endTime - startTime;796797 this.chainLog.push(log);798799 if(error !== null) throw error;800801 return result;802 }803804 getSignerAddress(signer: IKeyringPair | string): string {805 if(typeof signer === 'string') return signer;806 return signer.address;807 }808809 fetchAllPalletNames(): string[] {810 if(this.api === null) throw Error('API not initialized');811 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();812 }813814 fetchMissingPalletNames(requiredPallets: readonly string[]): string[] {815 const palletNames = this.fetchAllPalletNames();816 return requiredPallets.filter(p => !palletNames.includes(p));817 }818}819820821class HelperGroup<T extends ChainHelperBase> {822 helper: T;823824 constructor(uniqueHelper: T) {825 this.helper = uniqueHelper;826 }827}828829830class CollectionGroup extends HelperGroup<UniqueHelper> {831 /**832 * Get number of blocks when sponsored transaction is available.833 *834 * @param collectionId ID of collection835 * @param tokenId ID of token836 * @param addressObj address for which the sponsorship is checked837 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});838 * @returns number of blocks or null if sponsorship hasn't been set839 */840 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {841 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();842 }843844 /**845 * Get the number of created collections.846 *847 * @returns number of created collections848 */849 async getTotalCount(): Promise<number> {850 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();851 }852853 /**854 * Get information about the collection with additional data,855 * including the number of tokens it contains, its administrators,856 * the normalized address of the collection's owner, and decoded name and description.857 *858 * @param collectionId ID of collection859 * @example await getData(2)860 * @returns collection information object861 */862 async getData(collectionId: number): Promise<{863 id: number;864 name: string;865 description: string;866 tokensCount: number;867 admins: CrossAccountId[];868 normalizedOwner: TSubstrateAccount;869 raw: any870 } | null> {871 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);872 const humanCollection = collection.toHuman(), collectionData = {873 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],874 raw: humanCollection,875 } as any, jsonCollection = collection.toJSON();876 if(humanCollection === null) return null;877 collectionData.raw.limits = jsonCollection.limits;878 collectionData.raw.permissions = jsonCollection.permissions;879 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);880 for(const key of ['name', 'description']) {881 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);882 }883884 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))885 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)886 : 0;887 collectionData.admins = await this.getAdmins(collectionId);888889 return collectionData;890 }891892 /**893 * Get the addresses of the collection's administrators, optionally normalized.894 *895 * @param collectionId ID of collection896 * @param normalize whether to normalize the addresses to the default ss58 format897 * @example await getAdmins(1)898 * @returns array of administrators899 */900 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {901 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();902903 return normalize904 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())905 : admins;906 }907908 /**909 * Get the addresses added to the collection allow-list, optionally normalized.910 * @param collectionId ID of collection911 * @param normalize whether to normalize the addresses to the default ss58 format912 * @example await getAllowList(1)913 * @returns array of allow-listed addresses914 */915 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {916 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();917 return normalize918 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())919 : allowListed;920 }921922 /**923 * Get the effective limits of the collection instead of null for default values924 *925 * @param collectionId ID of collection926 * @example await getEffectiveLimits(2)927 * @returns object of collection limits928 */929 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {930 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();931 }932933 /**934 * Burns the collection if the signer has sufficient permissions and collection is empty.935 *936 * @param signer keyring of signer937 * @param collectionId ID of collection938 * @example await helper.collection.burn(aliceKeyring, 3);939 * @returns ```true``` if extrinsic success, otherwise ```false```940 */941 async burn(signer: TSigner, collectionId: number): Promise<boolean> {942 const result = await this.helper.executeExtrinsic(943 signer,944 'api.tx.unique.destroyCollection', [collectionId],945 true,946 );947948 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');949 }950951 /**952 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.953 *954 * @param signer keyring of signer955 * @param collectionId ID of collection956 * @param sponsorAddress Sponsor substrate address957 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")958 * @returns ```true``` if extrinsic success, otherwise ```false```959 */960 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {961 const result = await this.helper.executeExtrinsic(962 signer,963 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],964 true,965 );966967 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');968 }969970 /**971 * Confirms consent to sponsor the collection on behalf of the signer.972 *973 * @param signer keyring of signer974 * @param collectionId ID of collection975 * @example confirmSponsorship(aliceKeyring, 10)976 * @returns ```true``` if extrinsic success, otherwise ```false```977 */978 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {979 const result = await this.helper.executeExtrinsic(980 signer,981 'api.tx.unique.confirmSponsorship', [collectionId],982 true,983 );984985 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');986 }987988 /**989 * Removes the sponsor of a collection, regardless if it consented or not.990 *991 * @param signer keyring of signer992 * @param collectionId ID of collection993 * @example removeSponsor(aliceKeyring, 10)994 * @returns ```true``` if extrinsic success, otherwise ```false```995 */996 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {997 const result = await this.helper.executeExtrinsic(998 signer,999 'api.tx.unique.removeCollectionSponsor', [collectionId],1000 true,1001 );10021003 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');1004 }10051006 /**1007 * Sets the limits of the collection. At least one limit must be specified for a correct call.1008 *1009 * @param signer keyring of signer1010 * @param collectionId ID of collection1011 * @param limits collection limits object1012 * @example1013 * await setLimits(1014 * aliceKeyring,1015 * 10,1016 * {1017 * sponsorTransferTimeout: 0,1018 * ownerCanDestroy: false1019 * }1020 * )1021 * @returns ```true``` if extrinsic success, otherwise ```false```1022 */1023 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {1024 const result = await this.helper.executeExtrinsic(1025 signer,1026 'api.tx.unique.setCollectionLimits', [collectionId, limits],1027 true,1028 );10291030 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');1031 }10321033 /**1034 * Changes the owner of the collection to the new Substrate address.1035 *1036 * @param signer keyring of signer1037 * @param collectionId ID of collection1038 * @param ownerAddress substrate address of new owner1039 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")1040 * @returns ```true``` if extrinsic success, otherwise ```false```1041 */1042 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {1043 const result = await this.helper.executeExtrinsic(1044 signer,1045 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],1046 true,1047 );10481049 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');1050 }10511052 /**1053 * Adds a collection administrator.1054 *1055 * @param signer keyring of signer1056 * @param collectionId ID of collection1057 * @param adminAddressObj Administrator address (substrate or ethereum)1058 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1059 * @returns ```true``` if extrinsic success, otherwise ```false```1060 */1061 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1062 const result = await this.helper.executeExtrinsic(1063 signer,1064 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],1065 true,1066 );10671068 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');1069 }10701071 /**1072 * Removes a collection administrator.1073 *1074 * @param signer keyring of signer1075 * @param collectionId ID of collection1076 * @param adminAddressObj Administrator address (substrate or ethereum)1077 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1078 * @returns ```true``` if extrinsic success, otherwise ```false```1079 */1080 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1081 const result = await this.helper.executeExtrinsic(1082 signer,1083 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1084 true,1085 );10861087 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1088 }10891090 /**1091 * Check if user is in allow list.1092 *1093 * @param collectionId ID of collection1094 * @param user Account to check1095 * @example await getAdmins(1)1096 * @returns is user in allow list1097 */1098 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1099 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1100 }11011102 /**1103 * Adds an address to allow list1104 * @param signer keyring of signer1105 * @param collectionId ID of collection1106 * @param addressObj address to add to the allow list1107 * @returns ```true``` if extrinsic success, otherwise ```false```1108 */1109 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1110 const result = await this.helper.executeExtrinsic(1111 signer,1112 'api.tx.unique.addToAllowList', [collectionId, addressObj],1113 true,1114 );11151116 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1117 }11181119 /**1120 * Removes an address from allow list1121 *1122 * @param signer keyring of signer1123 * @param collectionId ID of collection1124 * @param addressObj address to remove from the allow list1125 * @returns ```true``` if extrinsic success, otherwise ```false```1126 */1127 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1128 const result = await this.helper.executeExtrinsic(1129 signer,1130 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1131 true,1132 );11331134 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1135 }11361137 /**1138 * Sets onchain permissions for selected collection.1139 *1140 * @param signer keyring of signer1141 * @param collectionId ID of collection1142 * @param permissions collection permissions object1143 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1144 * @returns ```true``` if extrinsic success, otherwise ```false```1145 */1146 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1147 const result = await this.helper.executeExtrinsic(1148 signer,1149 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1150 true,1151 );11521153 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1154 }11551156 /**1157 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1158 *1159 * @param signer keyring of signer1160 * @param collectionId ID of collection1161 * @param permissions nesting permissions object1162 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1163 * @returns ```true``` if extrinsic success, otherwise ```false```1164 */1165 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1166 return await this.setPermissions(signer, collectionId, {nesting: permissions});1167 }11681169 /**1170 * Disables nesting for selected collection.1171 *1172 * @param signer keyring of signer1173 * @param collectionId ID of collection1174 * @example disableNesting(aliceKeyring, 10);1175 * @returns ```true``` if extrinsic success, otherwise ```false```1176 */1177 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1178 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1179 }11801181 /**1182 * Sets onchain properties to the collection.1183 *1184 * @param signer keyring of signer1185 * @param collectionId ID of collection1186 * @param properties array of property objects1187 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1188 * @returns ```true``` if extrinsic success, otherwise ```false```1189 */1190 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1191 const result = await this.helper.executeExtrinsic(1192 signer,1193 'api.tx.unique.setCollectionProperties', [collectionId, properties],1194 true,1195 );11961197 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1198 }11991200 /**1201 * Get collection properties.1202 *1203 * @param collectionId ID of collection1204 * @param propertyKeys optionally filter the returned properties to only these keys1205 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1206 * @returns array of key-value pairs1207 */1208 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1209 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1210 }12111212 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1213 const api = this.helper.getApi();1214 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();12151216 return (props! as any).consumedSpace;1217 }12181219 async getCollectionOptions(collectionId: number) {1220 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1221 }12221223 /**1224 * Deletes onchain properties from the collection.1225 *1226 * @param signer keyring of signer1227 * @param collectionId ID of collection1228 * @param propertyKeys array of property keys to delete1229 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1230 * @returns ```true``` if extrinsic success, otherwise ```false```1231 */1232 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1233 const result = await this.helper.executeExtrinsic(1234 signer,1235 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1236 true,1237 );12381239 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1240 }12411242 /**1243 * Changes the owner of the token.1244 *1245 * @param signer keyring of signer1246 * @param collectionId ID of collection1247 * @param tokenId ID of token1248 * @param addressObj address of a new owner1249 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1250 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1251 * @returns true if the token success, otherwise false1252 */1253 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1254 const result = await this.helper.executeExtrinsic(1255 signer,1256 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1257 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1258 );12591260 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1261 }12621263 /**1264 *1265 * Change ownership of a token(s) on behalf of the owner.1266 *1267 * @param signer keyring of signer1268 * @param collectionId ID of collection1269 * @param tokenId ID of token1270 * @param fromAddressObj address on behalf of which the token will be sent1271 * @param toAddressObj new token owner1272 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1273 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1274 * @returns true if the token success, otherwise false1275 */1276 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1277 const result = await this.helper.executeExtrinsic(1278 signer,1279 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1280 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1281 );1282 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1283 }12841285 /**1286 *1287 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1288 *1289 * @param signer keyring of signer1290 * @param collectionId ID of collection1291 * @param tokenId ID of token1292 * @param amount amount of tokens to be burned. For NFT must be set to 1n1293 * @example burnToken(aliceKeyring, 10, 5);1294 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1295 */1296 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {1297 const burnResult = await this.helper.executeExtrinsic(1298 signer,1299 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1300 true, // `Unable to burn token for ${label}`,1301 );1302 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1303 if(burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1304 return burnedTokens.success;1305 }13061307 /**1308 * Destroys a concrete instance of NFT on behalf of the owner1309 *1310 * @param signer keyring of signer1311 * @param collectionId ID of collection1312 * @param tokenId ID of token1313 * @param fromAddressObj address on behalf of which the token will be burnt1314 * @param amount amount of tokens to be burned. For NFT must be set to 1n1315 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1316 * @returns ```true``` if extrinsic success, otherwise ```false```1317 */1318 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1319 const burnResult = await this.helper.executeExtrinsic(1320 signer,1321 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1322 true, // `Unable to burn token from for ${label}`,1323 );1324 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1325 return burnedTokens.success && burnedTokens.tokens.length > 0;1326 }13271328 /**1329 * Set, change, or remove approved address to transfer the ownership of the NFT.1330 *1331 * @param signer keyring of signer1332 * @param collectionId ID of collection1333 * @param tokenId ID of token1334 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1335 * @param amount amount of token to be approved. For NFT must be set to 1n1336 * @returns ```true``` if extrinsic success, otherwise ```false```1337 */1338 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1339 const approveResult = await this.helper.executeExtrinsic(1340 signer,1341 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1342 true, // `Unable to approve token for ${label}`,1343 );13441345 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1346 }13471348 /**1349 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1350 *1351 * @param signer keyring of signer1352 * @param collectionId ID of collection1353 * @param tokenId ID of token1354 * @param fromAddressObj Signer's Ethereum address containing her tokens1355 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1356 * @param amount amount of token to be approved. For NFT must be set to 1n1357 * @returns ```true``` if extrinsic success, otherwise ```false```1358 */1359 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {1360 const approveResult = await this.helper.executeExtrinsic(1361 signer,1362 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1363 true, // `Unable to approve token for ${label}`,1364 );13651366 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1367 }13681369 /**1370 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1371 *1372 * @param signer keyring of signer1373 * @param collectionId ID of collection1374 * @param tokenId ID of token1375 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1376 * @param amount amount of token to be approved. For NFT must be set to 1n1377 * @returns ```true``` if extrinsic success, otherwise ```false```1378 */1379 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1380 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1381 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1382 }13831384 /**1385 * Get the amount of token pieces approved to transfer or burn. Normally 0.1386 *1387 * @param collectionId ID of collection1388 * @param tokenId ID of token1389 * @param toAccountObj address which is approved to use token pieces1390 * @param fromAccountObj address which may have allowed the use of its owned tokens1391 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1392 * @returns number of approved to transfer pieces1393 */1394 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1395 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1396 }13971398 /**1399 * Get the last created token ID in a collection1400 *1401 * @param collectionId ID of collection1402 * @example getLastTokenId(10);1403 * @returns id of the last created token1404 */1405 async getLastTokenId(collectionId: number): Promise<number> {1406 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1407 }14081409 /**1410 * Check if token exists1411 *1412 * @param collectionId ID of collection1413 * @param tokenId ID of token1414 * @example doesTokenExist(10, 20);1415 * @returns true if the token exists, otherwise false1416 */1417 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1418 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1419 }1420}14211422class NFTnRFT extends CollectionGroup {1423 /**1424 * Get tokens owned by account1425 *1426 * @param collectionId ID of collection1427 * @param addressObj tokens owner1428 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1429 * @returns array of token ids owned by account1430 */1431 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1432 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1433 }14341435 /**1436 * Get token data1437 *1438 * @param collectionId ID of collection1439 * @param tokenId ID of token1440 * @param propertyKeys optionally filter the token properties to only these keys1441 * @param blockHashAt optionally query the data at some block with this hash1442 * @example getToken(10, 5);1443 * @returns human readable token data1444 */1445 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1446 properties: IProperty[];1447 owner: CrossAccountId;1448 normalizedOwner: CrossAccountId;1449 } | null> {1450 let tokenData;1451 if(typeof blockHashAt === 'undefined') {1452 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1453 }1454 else {1455 if(propertyKeys.length == 0) {1456 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1457 if(!collection) return null;1458 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1459 }1460 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1461 }1462 tokenData = tokenData.toHuman();1463 if(tokenData === null || tokenData.owner === null) return null;1464 const owner = {} as any;1465 for(const key of Object.keys(tokenData.owner)) {1466 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1467 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1468 : tokenData.owner[key];1469 }1470 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1471 return tokenData;1472 }14731474 /**1475 * Get token's owner1476 * @param collectionId ID of collection1477 * @param tokenId ID of token1478 * @param blockHashAt optionally query the data at the block with this hash1479 * @example getTokenOwner(10, 5);1480 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1481 */1482 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1483 let owner;1484 if(typeof blockHashAt === 'undefined') {1485 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1486 } else {1487 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1488 }1489 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1490 }14911492 /**1493 * Recursively find the address that owns the token1494 * @param collectionId ID of collection1495 * @param tokenId ID of token1496 * @param blockHashAt1497 * @example getTokenTopmostOwner(10, 5);1498 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1499 */1500 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1501 let owner;1502 if(typeof blockHashAt === 'undefined') {1503 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1504 } else {1505 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1506 }15071508 if(owner === null) return null;15091510 return owner.toHuman();1511 }15121513 /**1514 * Nest one token into another1515 * @param signer keyring of signer1516 * @param tokenObj token to be nested1517 * @param rootTokenObj token to be parent1518 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1519 * @returns ```true``` if extrinsic success, otherwise ```false```1520 */1521 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1522 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1523 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1524 if(!result) {1525 throw Error('Unable to nest token!');1526 }1527 return result;1528 }15291530 /**1531 * Remove token from nested state1532 * @param signer keyring of signer1533 * @param tokenObj token to unnest1534 * @param rootTokenObj parent of a token1535 * @param toAddressObj address of a new token owner1536 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1537 * @returns ```true``` if extrinsic success, otherwise ```false```1538 */1539 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1540 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1541 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1542 if(!result) {1543 throw Error('Unable to unnest token!');1544 }1545 return result;1546 }15471548 /**1549 * Set permissions to change token properties1550 *1551 * @param signer keyring of signer1552 * @param collectionId ID of collection1553 * @param permissions permissions to change a property by the collection admin or token owner1554 * @example setTokenPropertyPermissions(1555 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1556 * )1557 * @returns true if extrinsic success otherwise false1558 */1559 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1560 const result = await this.helper.executeExtrinsic(1561 signer,1562 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1563 true,1564 );15651566 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1567 }15681569 /**1570 * Get token property permissions.1571 *1572 * @param collectionId ID of collection1573 * @param propertyKeys optionally filter the returned property permissions to only these keys1574 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1575 * @returns array of key-permission pairs1576 */1577 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1578 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1579 }15801581 /**1582 * Set token properties1583 *1584 * @param signer keyring of signer1585 * @param collectionId ID of collection1586 * @param tokenId ID of token1587 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1588 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1589 * @returns ```true``` if extrinsic success, otherwise ```false```1590 */1591 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1592 const result = await this.helper.executeExtrinsic(1593 signer,1594 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1595 true,1596 );15971598 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1599 }16001601 /**1602 * Get properties, metadata assigned to a token.1603 *1604 * @param collectionId ID of collection1605 * @param tokenId ID of token1606 * @param propertyKeys optionally filter the returned properties to only these keys1607 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1608 * @returns array of key-value pairs1609 */1610 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1611 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1612 }16131614 /**1615 * Delete the provided properties of a token1616 * @param signer keyring of signer1617 * @param collectionId ID of collection1618 * @param tokenId ID of token1619 * @param propertyKeys property keys to be deleted1620 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1621 * @returns ```true``` if extrinsic success, otherwise ```false```1622 */1623 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1624 const result = await this.helper.executeExtrinsic(1625 signer,1626 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1627 true,1628 );16291630 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1631 }16321633 /**1634 * Mint new collection1635 *1636 * @param signer keyring of signer1637 * @param collectionOptions basic collection options and properties1638 * @param mode NFT or RFT type of a collection1639 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1640 * @returns object of the created collection1641 */1642 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1643 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1644 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1645 for(const key of ['name', 'description', 'tokenPrefix']) {1646 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);1647 }16481649 let flags = 0;1650 // convert CollectionFlags to number and join them in one number1651 if(collectionOptions.flags) {1652 for(let i = 0; i < collectionOptions.flags.length; i++){1653 const flag = collectionOptions.flags[i];1654 flags = flags | flag;1655 }1656 }1657 collectionOptions.flags = [flags];16581659 const creationResult = await this.helper.executeExtrinsic(1660 signer,1661 'api.tx.unique.createCollectionEx', [collectionOptions],1662 true, // errorLabel,1663 );1664 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1665 }16661667 getCollectionObject(_collectionId: number): any {1668 return null;1669 }16701671 getTokenObject(_collectionId: number, _tokenId: number): any {1672 return null;1673 }16741675 /**1676 * Tells whether the given `owner` approves the `operator`.1677 * @param collectionId ID of collection1678 * @param owner owner address1679 * @param operator operator addrees1680 * @returns true if operator is enabled1681 */1682 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1683 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1684 }16851686 /** Sets or unsets the approval of a given operator.1687 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1688 * @param operator Operator1689 * @param approved Should operator status be granted or revoked?1690 * @returns ```true``` if extrinsic success, otherwise ```false```1691 */1692 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1693 const result = await this.helper.executeExtrinsic(1694 signer,1695 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1696 true,1697 );1698 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1699 }1700}170117021703class NFTGroup extends NFTnRFT {1704 /**1705 * Get collection object1706 * @param collectionId ID of collection1707 * @example getCollectionObject(2);1708 * @returns instance of UniqueNFTCollection1709 */1710 getCollectionObject(collectionId: number): UniqueNFTCollection {1711 return new UniqueNFTCollection(collectionId, this.helper);1712 }17131714 /**1715 * Get token object1716 * @param collectionId ID of collection1717 * @param tokenId ID of token1718 * @example getTokenObject(10, 5);1719 * @returns instance of UniqueNFTToken1720 */1721 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1722 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1723 }17241725 /**1726 * Is token approved to transfer1727 * @param collectionId ID of collection1728 * @param tokenId ID of token1729 * @param toAccountObj address to be approved1730 * @returns ```true``` if extrinsic success, otherwise ```false```1731 */1732 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1733 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1734 }17351736 /**1737 * Changes the owner of the token.1738 *1739 * @param signer keyring of signer1740 * @param collectionId ID of collection1741 * @param tokenId ID of token1742 * @param addressObj address of a new owner1743 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1744 * @returns ```true``` if extrinsic success, otherwise ```false```1745 */1746 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1747 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1748 }17491750 /**1751 *1752 * Change ownership of a NFT on behalf of the owner.1753 *1754 * @param signer keyring of signer1755 * @param collectionId ID of collection1756 * @param tokenId ID of token1757 * @param fromAddressObj address on behalf of which the token will be sent1758 * @param toAddressObj new token owner1759 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1760 * @returns ```true``` if extrinsic success, otherwise ```false```1761 */1762 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1763 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1764 }17651766 /**1767 * Get tokens nested in the provided token1768 * @param collectionId ID of collection1769 * @param tokenId ID of token1770 * @param blockHashAt optionally query the data at the block with this hash1771 * @example getTokenChildren(10, 5);1772 * @returns tokens whose depth of nesting is <= 51773 */1774 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1775 let children;1776 if(typeof blockHashAt === 'undefined') {1777 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1778 } else {1779 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1780 }17811782 return children.toJSON().map((x: any) => ({collectionId: x.collection, tokenId: x.token}));1783 }17841785 /**1786 * Mint new collection1787 * @param signer keyring of signer1788 * @param collectionOptions Collection options1789 * @example1790 * mintCollection(aliceKeyring, {1791 * name: 'New',1792 * description: 'New collection',1793 * tokenPrefix: 'NEW',1794 * })1795 * @returns object of the created collection1796 */1797 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1798 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1799 }18001801 /**1802 * Mint new token1803 * @param signer keyring of signer1804 * @param data token data1805 * @returns created token object1806 */1807 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1808 const creationResult = await this.helper.executeExtrinsic(1809 signer,1810 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1811 NFT: {1812 properties: data.properties,1813 },1814 }],1815 true,1816 );1817 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1818 if(createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1819 if(createdTokens.tokens.length < 1) throw Error('No tokens minted');1820 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1821 }18221823 /**1824 * Mint multiple NFT tokens1825 * @param signer keyring of signer1826 * @param collectionId ID of collection1827 * @param tokens array of tokens with owner and properties1828 * @example1829 * mintMultipleTokens(aliceKeyring, 10, [{1830 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1831 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1832 * },{1833 * owner: {Ethereum: "0x9F0583DbB855d..."},1834 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1835 * }]);1836 * @returns ```true``` if extrinsic success, otherwise ```false```1837 */1838 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1839 const creationResult = await this.helper.executeExtrinsic(1840 signer,1841 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1842 true,1843 );1844 const collection = this.getCollectionObject(collectionId);1845 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1846 }18471848 /**1849 * Mint multiple NFT tokens with one owner1850 * @param signer keyring of signer1851 * @param collectionId ID of collection1852 * @param owner tokens owner1853 * @param tokens array of tokens with owner and properties1854 * @example1855 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1856 * properties: [{1857 * key: "gender",1858 * value: "female",1859 * },{1860 * key: "age",1861 * value: "33",1862 * }],1863 * }]);1864 * @returns array of newly created tokens1865 */1866 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1867 const rawTokens = [];1868 for(const token of tokens) {1869 const raw = {NFT: {properties: token.properties}};1870 rawTokens.push(raw);1871 }1872 const creationResult = await this.helper.executeExtrinsic(1873 signer,1874 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1875 true,1876 );1877 const collection = this.getCollectionObject(collectionId);1878 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1879 }18801881 /**1882 * Set, change, or remove approved address to transfer the ownership of the NFT.1883 *1884 * @param signer keyring of signer1885 * @param collectionId ID of collection1886 * @param tokenId ID of token1887 * @param toAddressObj address to approve1888 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1889 * @returns ```true``` if extrinsic success, otherwise ```false```1890 */1891 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1892 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1893 }1894}189518961897class RFTGroup extends NFTnRFT {1898 /**1899 * Get collection object1900 * @param collectionId ID of collection1901 * @example getCollectionObject(2);1902 * @returns instance of UniqueRFTCollection1903 */1904 getCollectionObject(collectionId: number): UniqueRFTCollection {1905 return new UniqueRFTCollection(collectionId, this.helper);1906 }19071908 /**1909 * Get token object1910 * @param collectionId ID of collection1911 * @param tokenId ID of token1912 * @example getTokenObject(10, 5);1913 * @returns instance of UniqueNFTToken1914 */1915 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1916 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1917 }19181919 /**1920 * Get top 10 token owners with the largest number of pieces1921 * @param collectionId ID of collection1922 * @param tokenId ID of token1923 * @example getTokenTop10Owners(10, 5);1924 * @returns array of top 10 owners1925 */1926 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1927 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1928 }19291930 /**1931 * Get number of pieces owned by address1932 * @param collectionId ID of collection1933 * @param tokenId ID of token1934 * @param addressObj address token owner1935 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1936 * @returns number of pieces ownerd by address1937 */1938 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1939 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1940 }19411942 /**1943 * Transfer pieces of token to another address1944 * @param signer keyring of signer1945 * @param collectionId ID of collection1946 * @param tokenId ID of token1947 * @param addressObj address of a new owner1948 * @param amount number of pieces to be transfered1949 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1950 * @returns ```true``` if extrinsic success, otherwise ```false```1951 */1952 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1953 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1954 }19551956 /**1957 * Change ownership of some pieces of RFT on behalf of the owner.1958 * @param signer keyring of signer1959 * @param collectionId ID of collection1960 * @param tokenId ID of token1961 * @param fromAddressObj address on behalf of which the token will be sent1962 * @param toAddressObj new token owner1963 * @param amount number of pieces to be transfered1964 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1965 * @returns ```true``` if extrinsic success, otherwise ```false```1966 */1967 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1968 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1969 }19701971 /**1972 * Mint new collection1973 * @param signer keyring of signer1974 * @param collectionOptions Collection options1975 * @example1976 * mintCollection(aliceKeyring, {1977 * name: 'New',1978 * description: 'New collection',1979 * tokenPrefix: 'NEW',1980 * })1981 * @returns object of the created collection1982 */1983 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1984 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1985 }19861987 /**1988 * Mint new token1989 * @param signer keyring of signer1990 * @param data token data1991 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1992 * @returns created token object1993 */1994 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1995 const creationResult = await this.helper.executeExtrinsic(1996 signer,1997 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1998 ReFungible: {1999 pieces: data.pieces,2000 properties: data.properties,2001 },2002 }],2003 true,2004 );2005 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);2006 if(createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');2007 if(createdTokens.tokens.length < 1) throw Error('No tokens minted');2008 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);2009 }20102011 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {2012 throw Error('Not implemented');2013 const creationResult = await this.helper.executeExtrinsic(2014 signer,2015 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],2016 true, // `Unable to mint RFT tokens for ${label}`,2017 );2018 const collection = this.getCollectionObject(collectionId);2019 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2020 }20212022 /**2023 * Mint multiple RFT tokens with one owner2024 * @param signer keyring of signer2025 * @param collectionId ID of collection2026 * @param owner tokens owner2027 * @param tokens array of tokens with properties and pieces2028 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);2029 * @returns array of newly created RFT tokens2030 */2031 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {2032 const rawTokens = [];2033 for(const token of tokens) {2034 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};2035 rawTokens.push(raw);2036 }2037 const creationResult = await this.helper.executeExtrinsic(2038 signer,2039 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2040 true,2041 );2042 const collection = this.getCollectionObject(collectionId);2043 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2044 }20452046 /**2047 * Destroys a concrete instance of RFT.2048 * @param signer keyring of signer2049 * @param collectionId ID of collection2050 * @param tokenId ID of token2051 * @param amount number of pieces to be burnt2052 * @example burnToken(aliceKeyring, 10, 5);2053 * @returns ```true``` if the extrinsic is successful, otherwise ```false```2054 */2055 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {2056 return await super.burnToken(signer, collectionId, tokenId, amount);2057 }20582059 /**2060 * Destroys a concrete instance of RFT on behalf of the owner.2061 * @param signer keyring of signer2062 * @param collectionId ID of collection2063 * @param tokenId ID of token2064 * @param fromAddressObj address on behalf of which the token will be burnt2065 * @param amount number of pieces to be burnt2066 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)2067 * @returns ```true``` if extrinsic success, otherwise ```false```2068 */2069 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2070 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);2071 }20722073 /**2074 * Set, change, or remove approved address to transfer the ownership of the RFT.2075 *2076 * @param signer keyring of signer2077 * @param collectionId ID of collection2078 * @param tokenId ID of token2079 * @param toAddressObj address to approve2080 * @param amount number of pieces to be approved2081 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);2082 * @returns true if the token success, otherwise false2083 */2084 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {2085 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2086 }20872088 /**2089 * Get total number of pieces2090 * @param collectionId ID of collection2091 * @param tokenId ID of token2092 * @example getTokenTotalPieces(10, 5);2093 * @returns number of pieces2094 */2095 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2096 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2097 }20982099 /**2100 * Change number of token pieces. Signer must be the owner of all token pieces.2101 * @param signer keyring of signer2102 * @param collectionId ID of collection2103 * @param tokenId ID of token2104 * @param amount new number of pieces2105 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2106 * @returns true if the repartion was success, otherwise false2107 */2108 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2109 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2110 const repartitionResult = await this.helper.executeExtrinsic(2111 signer,2112 'api.tx.unique.repartition', [collectionId, tokenId, amount],2113 true,2114 );2115 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2116 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2117 }2118}211921202121class FTGroup extends CollectionGroup {2122 /**2123 * Get collection object2124 * @param collectionId ID of collection2125 * @example getCollectionObject(2);2126 * @returns instance of UniqueFTCollection2127 */2128 getCollectionObject(collectionId: number): UniqueFTCollection {2129 return new UniqueFTCollection(collectionId, this.helper);2130 }21312132 /**2133 * Mint new fungible collection2134 * @param signer keyring of signer2135 * @param collectionOptions Collection options2136 * @param decimalPoints number of token decimals2137 * @example2138 * mintCollection(aliceKeyring, {2139 * name: 'New',2140 * description: 'New collection',2141 * tokenPrefix: 'NEW',2142 * }, 18)2143 * @returns newly created fungible collection2144 */2145 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2146 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2147 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2148 collectionOptions.mode = {fungible: decimalPoints};2149 for(const key of ['name', 'description', 'tokenPrefix']) {2150 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);2151 }2152 const creationResult = await this.helper.executeExtrinsic(2153 signer,2154 'api.tx.unique.createCollectionEx', [collectionOptions],2155 true,2156 );2157 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2158 }21592160 /**2161 * Mint tokens2162 * @param signer keyring of signer2163 * @param collectionId ID of collection2164 * @param owner address owner of new tokens2165 * @param amount amount of tokens to be meanted2166 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2167 * @returns ```true``` if extrinsic success, otherwise ```false```2168 */2169 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2170 const creationResult = await this.helper.executeExtrinsic(2171 signer,2172 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2173 Fungible: {2174 value: amount,2175 },2176 }],2177 true, // `Unable to mint fungible tokens for ${label}`,2178 );2179 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2180 }21812182 /**2183 * Mint multiple Fungible tokens with one owner2184 * @param signer keyring of signer2185 * @param collectionId ID of collection2186 * @param owner tokens owner2187 * @param tokens array of tokens with properties and pieces2188 * @returns ```true``` if extrinsic success, otherwise ```false```2189 */2190 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: { value: bigint }[], owner: ICrossAccountId): Promise<boolean> {2191 const rawTokens = [];2192 for(const token of tokens) {2193 const raw = {Fungible: {Value: token.value}};2194 rawTokens.push(raw);2195 }2196 const creationResult = await this.helper.executeExtrinsic(2197 signer,2198 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2199 true,2200 );2201 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2202 }22032204 /**2205 * Get the top 10 owners with the largest balance for the Fungible collection2206 * @param collectionId ID of collection2207 * @example getTop10Owners(10);2208 * @returns array of ```ICrossAccountId```2209 */2210 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2211 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2212 }22132214 /**2215 * Get account balance2216 * @param collectionId ID of collection2217 * @param addressObj address of owner2218 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2219 * @returns amount of fungible tokens owned by address2220 */2221 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2222 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2223 }22242225 /**2226 * Transfer tokens to address2227 * @param signer keyring of signer2228 * @param collectionId ID of collection2229 * @param toAddressObj address recipient2230 * @param amount amount of tokens to be sent2231 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2232 * @returns ```true``` if extrinsic success, otherwise ```false```2233 */2234 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2235 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2236 }22372238 /**2239 * Transfer some tokens on behalf of the owner.2240 * @param signer keyring of signer2241 * @param collectionId ID of collection2242 * @param fromAddressObj address on behalf of which tokens will be sent2243 * @param toAddressObj address where token to be sent2244 * @param amount number of tokens to be sent2245 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2246 * @returns ```true``` if extrinsic success, otherwise ```false```2247 */2248 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {2249 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2250 }22512252 /**2253 * Destroy some amount of tokens2254 * @param signer keyring of signer2255 * @param collectionId ID of collection2256 * @param amount amount of tokens to be destroyed2257 * @example burnTokens(aliceKeyring, 10, 1000n);2258 * @returns ```true``` if extrinsic success, otherwise ```false```2259 */2260 async burnTokens(signer: IKeyringPair, collectionId: number, amount = 1n): Promise<boolean> {2261 return await super.burnToken(signer, collectionId, 0, amount);2262 }22632264 /**2265 * Burn some tokens on behalf of the owner.2266 * @param signer keyring of signer2267 * @param collectionId ID of collection2268 * @param fromAddressObj address on behalf of which tokens will be burnt2269 * @param amount amount of tokens to be burnt2270 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2271 * @returns ```true``` if extrinsic success, otherwise ```false```2272 */2273 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2274 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2275 }22762277 /**2278 * Get total collection supply2279 * @param collectionId2280 * @returns2281 */2282 async getTotalPieces(collectionId: number): Promise<bigint> {2283 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2284 }22852286 /**2287 * Set, change, or remove approved address to transfer tokens.2288 *2289 * @param signer keyring of signer2290 * @param collectionId ID of collection2291 * @param toAddressObj address to be approved2292 * @param amount amount of tokens to be approved2293 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2294 * @returns ```true``` if extrinsic success, otherwise ```false```2295 */2296 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2297 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2298 }22992300 /**2301 * Get amount of fungible tokens approved to transfer2302 * @param collectionId ID of collection2303 * @param fromAddressObj owner of tokens2304 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2305 * @returns number of tokens approved for the transfer2306 */2307 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2308 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2309 }2310}231123122313class ChainGroup extends HelperGroup<ChainHelperBase> {2314 /**2315 * Get system properties of a chain2316 * @example getChainProperties();2317 * @returns ss58Format, token decimals, and token symbol2318 */2319 getChainProperties(): IChainProperties {2320 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2321 return {2322 ss58Format: properties.ss58Format.toJSON(),2323 tokenDecimals: properties.tokenDecimals.toJSON(),2324 tokenSymbol: properties.tokenSymbol.toJSON(),2325 };2326 }23272328 /**2329 * Get chain header2330 * @example getLatestBlockNumber();2331 * @returns the number of the last block2332 */2333 async getLatestBlockNumber(): Promise<number> {2334 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2335 }23362337 /**2338 * Get block hash by block number2339 * @param blockNumber number of block2340 * @example getBlockHashByNumber(12345);2341 * @returns hash of a block2342 */2343 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2344 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2345 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2346 return blockHash;2347 }23482349 // TODO add docs2350 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2351 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2352 if(!blockHash) return null;2353 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2354 }23552356 /**2357 * Get latest relay block2358 * @returns {number} relay block2359 */2360 async getRelayBlockNumber(): Promise<bigint> {2361 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2362 return BigInt(blockNumber);2363 }23642365 /**2366 * Get account nonce2367 * @param address substrate address2368 * @example getNonce("5GrwvaEF5zXb26Fz...");2369 * @returns number, account's nonce2370 */2371 async getNonce(address: TSubstrateAccount): Promise<number> {2372 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2373 }2374}23752376class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2377 /**2378 * Get substrate address balance2379 * @param address substrate address2380 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2381 * @returns amount of tokens on address2382 */2383 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2384 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2385 }23862387 /**2388 * Transfer tokens to substrate address2389 * @param signer keyring of signer2390 * @param address substrate address of a recipient2391 * @param amount amount of tokens to be transfered2392 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2393 * @returns ```true``` if extrinsic success, otherwise ```false```2394 */2395 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2396 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}`*/);23972398 let transfer = {from: null, to: null, amount: 0n} as any;2399 result.result.events.forEach(({event: {data, method, section}}) => {2400 if((section === 'balances') && (method === 'Transfer')) {2401 transfer = {2402 from: this.helper.address.normalizeSubstrate(data[0]),2403 to: this.helper.address.normalizeSubstrate(data[1]),2404 amount: BigInt(data[2]),2405 };2406 }2407 });2408 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2409 && this.helper.address.normalizeSubstrate(address) === transfer.to2410 && BigInt(amount) === transfer.amount;2411 return isSuccess;2412 }24132414 /**2415 * Get full substrate balance including free, frozen, and reserved2416 * @param address substrate address2417 * @returns2418 */2419 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2420 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2421 return {free: accountInfo.free.toBigInt(), frozen: accountInfo.frozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2422 }24232424 /**2425 * Get total issuance2426 * @returns2427 */2428 async getTotalIssuance(): Promise<bigint> {2429 const total = (await this.helper.callRpc('api.query.balances.totalIssuance', []));2430 return total.toBigInt();2431 }24322433 async getLocked(address: TSubstrateAccount): Promise<{ id: string, amount: bigint, reason: string }[]> {2434 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2435 return locks.map((lock: any) => ({id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}));2436 }2437 async getFrozen(address: TSubstrateAccount): Promise<{ id: string, amount: bigint }[]> {2438 const locks = (await this.helper.api!.query.balances.freezes(address)) as unknown as Array<any>;2439 return locks.map(lock => ({id: lock.id.toUtf8(), amount: lock.amount.toBigInt()}));2440 }2441}24422443class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2444 /**2445 * Get ethereum address balance2446 * @param address ethereum address2447 * @example getEthereum("0x9F0583DbB855d...")2448 * @returns amount of tokens on address2449 */2450 async getEthereum(address: TEthereumAccount): Promise<bigint> {2451 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2452 }24532454 /**2455 * Transfer tokens to address2456 * @param signer keyring of signer2457 * @param address Ethereum address of a recipient2458 * @param amount amount of tokens to be transfered2459 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2460 * @returns ```true``` if extrinsic success, otherwise ```false```2461 */2462 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2463 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);24642465 let transfer = {from: null, to: null, amount: 0n} as any;2466 result.result.events.forEach(({event: {data, method, section}}) => {2467 if((section === 'balances') && (method === 'Transfer')) {2468 transfer = {2469 from: data[0].toString(),2470 to: data[1].toString(),2471 amount: BigInt(data[2]),2472 };2473 }2474 });2475 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2476 && address === transfer.to2477 && BigInt(amount) === transfer.amount;2478 return isSuccess;2479 }2480}24812482class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2483 subBalanceGroup: SubstrateBalanceGroup<T>;2484 ethBalanceGroup: EthereumBalanceGroup<T>;24852486 constructor(helper: T) {2487 super(helper);2488 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2489 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2490 }24912492 getCollectionCreationPrice(): bigint {2493 return 2n * this.getOneTokenNominal();2494 }2495 /**2496 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2497 * @example getOneTokenNominal()2498 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2499 */2500 getOneTokenNominal(): bigint {2501 const chainProperties = this.helper.chain.getChainProperties();2502 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2503 }25042505 /**2506 * Get substrate address balance2507 * @param address substrate address2508 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2509 * @returns amount of tokens on address2510 */2511 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2512 return this.subBalanceGroup.getSubstrate(address);2513 }25142515 /**2516 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2517 * @param address substrate address2518 * @returns2519 */2520 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2521 return this.subBalanceGroup.getSubstrateFull(address);2522 }25232524 /**2525 * Get total issuance2526 * @returns2527 */2528 getTotalIssuance(): Promise<bigint> {2529 return this.subBalanceGroup.getTotalIssuance();2530 }25312532 /**2533 * Get locked balances2534 * @param address substrate address2535 * @returns locked balances with reason via api.query.balances.locks2536 * @deprecated all the methods should switch to getFrozen2537 */2538 getLocked(address: TSubstrateAccount) {2539 return this.subBalanceGroup.getLocked(address);2540 }25412542 /**2543 * Get frozen balances2544 * @param address substrate address2545 * @returns frozen balances with id via api.query.balances.freezes2546 */2547 getFrozen(address: TSubstrateAccount) {2548 return this.subBalanceGroup.getFrozen(address);2549 }25502551 /**2552 * Get ethereum address balance2553 * @param address ethereum address2554 * @example getEthereum("0x9F0583DbB855d...")2555 * @returns amount of tokens on address2556 */2557 getEthereum(address: TEthereumAccount): Promise<bigint> {2558 return this.ethBalanceGroup.getEthereum(address);2559 }25602561 async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint) {2562 await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceSetBalance', [address, amount], true);2563 }25642565 /**2566 * Transfer tokens to substrate address2567 * @param signer keyring of signer2568 * @param address substrate address of a recipient2569 * @param amount amount of tokens to be transfered2570 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2571 * @returns ```true``` if extrinsic success, otherwise ```false```2572 */2573 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2574 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2575 }25762577 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2578 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);25792580 let transfer = {from: null, to: null, amount: 0n} as any;2581 result.result.events.forEach(({event: {data, method, section}}) => {2582 if((section === 'balances') && (method === 'Transfer')) {2583 transfer = {2584 from: this.helper.address.normalizeSubstrate(data[0]),2585 to: this.helper.address.normalizeSubstrate(data[1]),2586 amount: BigInt(data[2]),2587 };2588 }2589 });2590 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2591 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2592 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2593 return isSuccess;2594 }25952596 /**2597 * Transfer tokens with the unlock period2598 * @param signer signers Keyring2599 * @param address Substrate address of recipient2600 * @param schedule Schedule params2601 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002602 */2603 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: { start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }): Promise<void> {2604 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2605 const event = result.result.events2606 .find(e => e.event.section === 'vesting' &&2607 e.event.method === 'VestingScheduleAdded' &&2608 e.event.data[0].toHuman() === signer.address);2609 if(!event) throw Error('Cannot find transfer in events');2610 }26112612 /**2613 * Get schedule for recepient of vested transfer2614 * @param address Substrate address of recipient2615 * @returns2616 */2617 async getVestingSchedules(address: TSubstrateAccount): Promise<{ start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }[]> {2618 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2619 return schedule.map((schedule: any) => ({2620 start: BigInt(schedule.start),2621 period: BigInt(schedule.period),2622 periodCount: BigInt(schedule.periodCount),2623 perPeriod: BigInt(schedule.perPeriod),2624 }));2625 }26262627 /**2628 * Claim vested tokens2629 * @param signer signers Keyring2630 */2631 async claim(signer: TSigner) {2632 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2633 const event = result.result.events2634 .find(e => e.event.section === 'vesting' &&2635 e.event.method === 'Claimed' &&2636 e.event.data[0].toHuman() === signer.address);2637 if(!event) throw Error('Cannot find claim in events');2638 }2639}26402641class AddressGroup extends HelperGroup<ChainHelperBase> {2642 /**2643 * Normalizes the address to the specified ss58 format, by default ```42```.2644 * @param address substrate address2645 * @param ss58Format format for address conversion, by default ```42```2646 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2647 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2648 */2649 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2650 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2651 }26522653 /**2654 * Get address in the connected chain format2655 * @param address substrate address2656 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2657 * @returns address in chain format2658 */2659 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2660 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2661 }26622663 /**2664 * Get substrate mirror of an ethereum address2665 * @param ethAddress ethereum address2666 * @param toChainFormat false for normalized account2667 * @example ethToSubstrate('0x9F0583DbB855d...')2668 * @returns substrate mirror of a provided ethereum address2669 */2670 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat = false): TSubstrateAccount {2671 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2672 }26732674 /**2675 * Get ethereum mirror of a substrate address2676 * @param subAddress substrate account2677 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2678 * @returns ethereum mirror of a provided substrate address2679 */2680 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2681 return CrossAccountId.translateSubToEth(subAddress);2682 }26832684 /**2685 * Encode key to substrate address2686 * @param key key for encoding address2687 * @param ss58Format prefix for encoding to the address of the corresponding network2688 * @returns encoded substrate address2689 */2690 encodeSubstrateAddress(key: Uint8Array | string | bigint, ss58Format = 42): string {2691 const u8a: Uint8Array = typeof key === 'string'2692 ? hexToU8a(key)2693 : typeof key === 'bigint'2694 ? hexToU8a(key.toString(16))2695 : key;26962697 if(ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2698 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2699 }27002701 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2702 if(!allowedDecodedLengths.includes(u8a.length)) {2703 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2704 }27052706 const u8aPrefix = ss58Format < 642707 ? new Uint8Array([ss58Format])2708 : new Uint8Array([2709 ((ss58Format & 0xfc) >> 2) | 0x40,2710 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2711 ]);27122713 const input = u8aConcat(u8aPrefix, u8a);27142715 return base58Encode(u8aConcat(2716 input,2717 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2718 ));2719 }27202721 /**2722 * Restore substrate address from bigint representation2723 * @param number decimal representation of substrate address2724 * @returns substrate address2725 */2726 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2727 if(this.helper.api === null) {2728 throw 'Not connected';2729 }2730 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2731 if(res === undefined || res === null) {2732 throw 'Restore address error';2733 }2734 return res.toString();2735 }27362737 /**2738 * Convert etherium cross account id to substrate cross account id2739 * @param ethCrossAccount etherium cross account2740 * @returns substrate cross account id2741 */2742 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2743 if(ethCrossAccount.sub === '0') {2744 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2745 }27462747 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2748 return {Substrate: ss58};2749 }27502751 paraSiblingSovereignAccount(paraid: number) {2752 // We are getting a *sibling* parachain sovereign account,2753 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2754 const siblingPrefix = '0x7369626c';27552756 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2757 const suffix = '000000000000000000000000000000000000000000000000';27582759 return siblingPrefix + encodedParaId + suffix;2760 }2761}27622763class StakingGroup extends HelperGroup<UniqueHelper> {2764 /**2765 * Stake tokens for App Promotion2766 * @param signer keyring of signer2767 * @param amountToStake amount of tokens to stake2768 * @param label extra label for log2769 * @returns2770 */2771 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2772 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2773 const _stakeResult = await this.helper.executeExtrinsic(2774 signer, 'api.tx.appPromotion.stake',2775 [amountToStake], true,2776 );2777 // TODO extract info from stakeResult2778 return true;2779 }27802781 /**2782 * Unstake all staked tokens2783 * @param signer keyring of signer2784 * @param amountToUnstake amount of tokens to unstake2785 * @param label extra label for log2786 * @returns block hash where unstake happened2787 */2788 async unstakeAll(signer: TSigner, label?: string): Promise<string> {2789 if(typeof label === 'undefined') label = `${signer.address}`;2790 const unstakeResult = await this.helper.executeExtrinsic(2791 signer, 'api.tx.appPromotion.unstakeAll',2792 [], true,2793 );2794 return unstakeResult.blockHash;2795 }27962797 /**2798 * Unstake the part of a staked tokens2799 * @param signer keyring of signer2800 * @param amount amount of tokens to unstake2801 * @param label extra label for log2802 * @returns block hash where unstake happened2803 */2804 async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2805 if(typeof label === 'undefined') label = `${signer.address}`;2806 const unstakeResult = await this.helper.executeExtrinsic(2807 signer, 'api.tx.appPromotion.unstakePartial',2808 [amount], true,2809 );2810 return unstakeResult.blockHash;2811 }28122813 /**2814 * Get total number of active stakes2815 * @param address substrate address2816 * @returns {number}2817 */2818 async getStakesNumber(address: ICrossAccountId): Promise<number> {2819 if('Ethereum' in address) throw Error('only substrate address');2820 return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2821 }28222823 /**2824 * Get total staked amount for address2825 * @param address substrate or ethereum address2826 * @returns total staked amount2827 */2828 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2829 if(address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2830 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2831 }28322833 /**2834 * Get total staked per block2835 * @param address substrate or ethereum address2836 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2837 */2838 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2839 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2840 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => ({2841 block: block.toBigInt(),2842 amount: amount.toBigInt(),2843 }));2844 }28452846 /**2847 * Get total pending unstake amount for address2848 * @param address substrate or ethereum address2849 * @returns total pending unstake amount2850 */2851 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2852 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2853 }28542855 /**2856 * Get pending unstake amount per block for address2857 * @param address substrate or ethereum address2858 * @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 block2859 */2860 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2861 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2862 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => ({2863 block: block.toBigInt(),2864 amount: amount.toBigInt(),2865 }));2866 return result;2867 }2868}28692870class SchedulerGroup extends HelperGroup<UniqueHelper> {2871 constructor(helper: UniqueHelper) {2872 super(helper);2873 }28742875 cancelScheduled(signer: TSigner, scheduledId: string) {2876 return this.helper.executeExtrinsic(2877 signer,2878 'api.tx.scheduler.cancelNamed',2879 [scheduledId],2880 true,2881 );2882 }28832884 changePriority(signer: TSigner, scheduledId: string, priority: number) {2885 return this.helper.executeExtrinsic(2886 signer,2887 'api.tx.scheduler.changeNamedPriority',2888 [scheduledId, priority],2889 true,2890 );2891 }28922893 scheduleAt<T extends UniqueHelper>(2894 executionBlockNumber: number,2895 options: ISchedulerOptions = {},2896 ) {2897 return this.schedule<T>('schedule', executionBlockNumber, options);2898 }28992900 scheduleAfter<T extends UniqueHelper>(2901 blocksBeforeExecution: number,2902 options: ISchedulerOptions = {},2903 ) {2904 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2905 }29062907 schedule<T extends UniqueHelper>(2908 scheduleFn: 'schedule' | 'scheduleAfter',2909 blocksNum: number,2910 options: ISchedulerOptions = {},2911 ) {2912 // eslint-disable-next-line @typescript-eslint/naming-convention2913 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2914 return this.helper.clone(ScheduledHelperType, {2915 scheduleFn,2916 blocksNum,2917 options,2918 }) as T;2919 }2920}29212922class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2923 //todo:collator documentation2924 addInvulnerable(signer: TSigner, address: string) {2925 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2926 }29272928 removeInvulnerable(signer: TSigner, address: string) {2929 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2930 }29312932 async getInvulnerables(): Promise<string[]> {2933 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2934 }29352936 /** and also total max invulnerables */2937 maxCollators(): number {2938 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2939 }29402941 async getDesiredCollators(): Promise<number> {2942 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2943 }29442945 setLicenseBond(signer: TSigner, amount: bigint) {2946 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2947 }29482949 async getLicenseBond(): Promise<bigint> {2950 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2951 }29522953 obtainLicense(signer: TSigner) {2954 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2955 }29562957 releaseLicense(signer: TSigner) {2958 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2959 }29602961 forceReleaseLicense(signer: TSigner, released: string) {2962 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2963 }29642965 async hasLicense(address: string): Promise<bigint> {2966 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2967 }29682969 onboard(signer: TSigner) {2970 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2971 }29722973 offboard(signer: TSigner) {2974 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2975 }29762977 async getCandidates(): Promise<string[]> {2978 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2979 }2980}29812982class CollectiveGroup extends HelperGroup<UniqueHelper> {2983 /**2984 * Pallet name to make an API call to. Examples: 'council', 'technicalCommittee'2985 */2986 private collective: string;29872988 constructor(helper: UniqueHelper, collective: string) {2989 super(helper);2990 this.collective = collective;2991 }29922993 /**2994 * Check the result of a proposal execution for the success of the underlying proposed extrinsic.2995 * @param events events of the proposal execution2996 * @returns proposal hash2997 */2998 private checkExecutedEvent(events: IPhasicEvent[]): string {2999 const executionEvents = events.filter(x =>3000 x.event.section === this.collective && (x.event.method === 'Executed' || x.event.method === 'MemberExecuted'));30013002 if(executionEvents.length != 1) {3003 if(events.filter(x => x.event.section === this.collective && x.event.method === 'Disapproved').length > 0)3004 throw new Error(`Disapproved by ${this.collective}`);3005 else3006 throw new Error(`Expected one 'Executed' or 'MemberExecuted' event for ${this.collective}`);3007 }30083009 const result = (executionEvents[0].event.data as any).result;30103011 if(result.isErr) {3012 if(result.asErr.isModule) {3013 const error = result.asErr.asModule;3014 const metaError = this.helper.getApi()?.registry.findMetaError(error);3015 throw new Error(`Proposal execution failed with ${metaError.section}.${metaError.name}`);3016 } else {3017 throw new Error('Proposal execution failed with ' + result.asErr.toHuman());3018 }3019 }30203021 return (executionEvents[0].event.data as any).proposalHash;3022 }30233024 /**3025 * Returns an array of members' addresses.3026 */3027 async getMembers() {3028 return (await this.helper.callRpc(`api.query.${this.collective}.members`, [])).toHuman();3029 }30303031 /**3032 * Returns the optional address of the prime member of the collective.3033 */3034 async getPrimeMember() {3035 return (await this.helper.callRpc(`api.query.${this.collective}.prime`, [])).toHuman();3036 }30373038 /**3039 * Returns an array of proposal hashes that are currently active for this collective.3040 */3041 async getProposals() {3042 return (await this.helper.callRpc(`api.query.${this.collective}.proposals`, [])).toHuman();3043 }30443045 /**3046 * Returns the call originally encoded under the specified hash.3047 * @param hash h256-encoded proposal3048 * @returns the optional call that the proposal hash stands for.3049 */3050 async getProposalCallOf(hash: string) {3051 return (await this.helper.callRpc(`api.query.${this.collective}.proposalOf`, [hash])).toHuman();3052 }30533054 /**3055 * Returns the total number of proposals so far.3056 */3057 async getTotalProposalsCount() {3058 return (await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, [])).toNumber();3059 }30603061 /**3062 * Creates a new proposal up for voting. If the threshold is set to 1, the proposal will be executed immediately.3063 * @param signer keyring of the proposer3064 * @param proposal constructed call to be executed if the proposal is successful3065 * @param voteThreshold minimal number of votes for the proposal to be verified and executed3066 * @param lengthBound byte length of the encoded call3067 * @returns promise of extrinsic execution and its result3068 */3069 async propose(signer: TSigner, proposal: any, voteThreshold: number, lengthBound = 10000) {3070 return await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [voteThreshold, proposal, lengthBound]);3071 }30723073 /**3074 * Casts a vote to either approve or reject a proposal.3075 * @param signer keyring of the voter3076 * @param proposalHash hash of the proposal to be voted for3077 * @param proposalIndex absolute index of the proposal used for absolutely nothing but throwing pointless errors3078 * @param approve aye or nay3079 * @returns promise of extrinsic execution and its result3080 */3081 vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3082 return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve]);3083 }30843085 /**3086 * Executes a call immediately as a member of the collective. Needed for the Member origin.3087 * @param signer keyring of the executor member3088 * @param proposal constructed call to be executed by the member3089 * @param lengthBound byte length of the encoded call3090 * @returns promise of extrinsic execution3091 */3092 async execute(signer: TSigner, proposal: any, lengthBound = 10000) {3093 const result = await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.execute`, [proposal, lengthBound]);3094 this.checkExecutedEvent(result.result.events);3095 return result;3096 }30973098 /**3099 * Attempt to close and execute a proposal. Note that there must already be enough votes to meet the threshold set when proposing.3100 * @param signer keyring of the executor. Can be absolutely anyone.3101 * @param proposalHash hash of the proposal to close3102 * @param proposalIndex index of the proposal generated on its creation3103 * @param weightBound weight of the proposed call. Can be obtained by calling `paymentInfo()` on the call.3104 * @param lengthBound byte length of the encoded call3105 * @returns promise of extrinsic execution and its result3106 */3107 async close(3108 signer: TSigner,3109 proposalHash: string,3110 proposalIndex: number,3111 weightBound: [number, number] | any = [20_000_000_000, 1000_000],3112 lengthBound = 10_000,3113 ) {3114 const result = await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [3115 proposalHash,3116 proposalIndex,3117 weightBound,3118 lengthBound,3119 ]);3120 this.checkExecutedEvent(result.result.events);3121 return result;3122 }31233124 /**3125 * Shut down a proposal, regardless of its current state.3126 * @param signer keyring of the disapprover. Must be root3127 * @param proposalHash hash of the proposal to close3128 * @returns promise of extrinsic execution and its result3129 */3130 disapproveProposal(signer: TSigner, proposalHash: string) {3131 return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.disapproveProposal`, [proposalHash]);3132 }3133}31343135class CollectiveMembershipGroup extends HelperGroup<UniqueHelper> {3136 /**3137 * Pallet name to make an API call to. Examples: 'councilMembership', 'technicalCommitteeMembership'3138 */3139 private membership: string;31403141 constructor(helper: UniqueHelper, membership: string) {3142 super(helper);3143 this.membership = membership;3144 }31453146 /**3147 * Returns an array of members' addresses according to the membership pallet's perception.3148 * Note that it does not recognize the original pallet's members set with `setMembers()`.3149 */3150 async getMembers() {3151 return (await this.helper.callRpc(`api.query.${this.membership}.members`, [])).toHuman();3152 }31533154 /**3155 * Returns the optional address of the prime member of the collective.3156 */3157 async getPrimeMember() {3158 return (await this.helper.callRpc(`api.query.${this.membership}.prime`, [])).toHuman();3159 }31603161 /**3162 * Add a member to the collective.3163 * @param signer keyring of the setter. Must be root3164 * @param member address of the member to add3165 * @returns promise of extrinsic execution and its result3166 */3167 addMember(signer: TSigner, member: string) {3168 return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.addMember`, [member]);3169 }31703171 addMemberCall(member: string) {3172 return this.helper.constructApiCall(`api.tx.${this.membership}.addMember`, [member]);3173 }31743175 /**3176 * Remove a member from the collective.3177 * @param signer keyring of the setter. Must be root3178 * @param member address of the member to remove3179 * @returns promise of extrinsic execution and its result3180 */3181 removeMember(signer: TSigner, member: string) {3182 return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.removeMember`, [member]);3183 }31843185 removeMemberCall(member: string) {3186 return this.helper.constructApiCall(`api.tx.${this.membership}.removeMember`, [member]);3187 }31883189 /**3190 * Set members of the collective to the given list of addresses.3191 * @param signer keyring of the setter. Must be root (for the direct call, bypassing a public motion)3192 * @param members addresses of the members to set3193 * @returns promise of extrinsic execution and its result3194 */3195 resetMembers(signer: TSigner, members: string[]) {3196 return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.resetMembers`, [members]);3197 }31983199 /**3200 * Set the collective's prime member to the given address.3201 * @param signer keyring of the setter. Must be root (for the direct call, bypassing a public motion)3202 * @param prime address of the prime member of the collective3203 * @returns promise of extrinsic execution and its result3204 */3205 setPrime(signer: TSigner, prime: string) {3206 return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.setPrime`, [prime]);3207 }32083209 setPrimeCall(member: string) {3210 return this.helper.constructApiCall(`api.tx.${this.membership}.setPrime`, [member]);3211 }32123213 /**3214 * Remove the collective's prime member.3215 * @param signer keyring of the setter. Must be root (for the direct call, bypassing a public motion)3216 * @returns promise of extrinsic execution and its result3217 */3218 clearPrime(signer: TSigner) {3219 return this.helper.executeExtrinsic(signer, `api.tx.${this.membership}.clearPrime`, []);3220 }32213222 clearPrimeCall() {3223 return this.helper.constructApiCall(`api.tx.${this.membership}.clearPrime`, []);3224 }3225}32263227class RankedCollectiveGroup extends HelperGroup<UniqueHelper> {3228 /**3229 * Pallet name to make an API call to. Examples: 'FellowshipCollective'3230 */3231 private collective: string;32323233 constructor(helper: UniqueHelper, collective: string) {3234 super(helper);3235 this.collective = collective;3236 }32373238 addMember(signer: TSigner, newMember: string) {3239 return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.addMember`, [newMember]);3240 }32413242 addMemberCall(newMember: string) {3243 return this.helper.constructApiCall(`api.tx.${this.collective}.addMember`, [newMember]);3244 }32453246 removeMember(signer: TSigner, member: string, minRank: number) {3247 return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.removeMember`, [member, minRank]);3248 }32493250 removeMemberCall(newMember: string, minRank: number) {3251 return this.helper.constructApiCall(`api.tx.${this.collective}.removeMember`, [newMember, minRank]);3252 }32533254 promote(signer: TSigner, member: string) {3255 return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.promoteMember`, [member]);3256 }32573258 promoteCall(member: string) {3259 return this.helper.constructApiCall(`api.tx.${this.collective}.promoteMember`, [member]);3260 }32613262 demote(signer: TSigner, member: string) {3263 return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.demoteMember`, [member]);3264 }32653266 demoteCall(newMember: string) {3267 return this.helper.constructApiCall(`api.tx.${this.collective}.demoteMember`, [newMember]);3268 }32693270 vote(signer: TSigner, pollIndex: number, aye: boolean) {3271 return this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [pollIndex, aye]);3272 }32733274 async getMembers() {3275 return (await this.helper.getApi().query.fellowshipCollective.members.keys())3276 .map((key) => key.args[0].toString());3277 }32783279 async getMemberRank(member: string) {3280 return (await this.helper.callRpc('api.query.fellowshipCollective.members', [member])).toJSON().rank;3281 }3282}32833284class ReferendaGroup extends HelperGroup<UniqueHelper> {3285 /**3286 * Pallet name to make an API call to. Examples: 'FellowshipReferenda'3287 */3288 private referenda: string;32893290 constructor(helper: UniqueHelper, referenda: string) {3291 super(helper);3292 this.referenda = referenda;3293 }32943295 submit(3296 signer: TSigner,3297 proposalOrigin: string,3298 proposal: any,3299 enactmentMoment: any,3300 ) {3301 return this.helper.executeExtrinsic(signer, `api.tx.${this.referenda}.submit`, [3302 {Origins: proposalOrigin},3303 proposal,3304 enactmentMoment,3305 ]);3306 }33073308 placeDecisionDeposit(signer: TSigner, referendumIndex: number) {3309 return this.helper.executeExtrinsic(signer, `api.tx.${this.referenda}.placeDecisionDeposit`, [referendumIndex]);3310 }33113312 cancel(signer: TSigner, referendumIndex: number) {3313 return this.helper.executeExtrinsic(signer, `api.tx.${this.referenda}.cancel`, [referendumIndex]);3314 }33153316 cancelCall(referendumIndex: number) {3317 return this.helper.constructApiCall(`api.tx.${this.referenda}.cancel`, [referendumIndex]);3318 }33193320 async referendumInfo(referendumIndex: number) {3321 return (await this.helper.callRpc(`api.query.${this.referenda}.referendumInfoFor`, [referendumIndex])).toJSON();3322 }33233324 async enactmentEventId(referendumIndex: number) {3325 const api = await this.helper.getApi();33263327 const bytes = api.createType('([u8;8], Text, u32)', ['assembly', 'enactment', referendumIndex]).toU8a();3328 return blake2AsHex(bytes, 256);3329 }3330}33313332export interface IFellowshipGroup {3333 collective: RankedCollectiveGroup;3334 referenda: ReferendaGroup;3335}33363337export interface ICollectiveGroup {3338 collective: CollectiveGroup;3339 membership: CollectiveMembershipGroup;3340}33413342class DemocracyGroup extends HelperGroup<UniqueHelper> {3343 // todo displace proposal into types?3344 propose(signer: TSigner, call: any, deposit: bigint) {3345 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.propose', [{Inline: call.method.toHex()}, deposit]);3346 }33473348 proposeWithPreimage(signer: TSigner, preimage: string, deposit: bigint) {3349 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.propose', [{Legacy: preimage}, deposit]);3350 }33513352 proposeCall(call: any, deposit: bigint) {3353 return this.helper.constructApiCall('api.tx.democracy.propose', [{Inline: call.method.toHex()}, deposit]);3354 }33553356 second(signer: TSigner, proposalIndex: number) {3357 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.second', [proposalIndex]);3358 }33593360 externalPropose(signer: TSigner, proposalCall: any) {3361 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalPropose', [{Inline: proposalCall.method.toHex()}]);3362 }33633364 externalProposeMajority(signer: TSigner, proposalCall: any) {3365 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalProposeMajority', [{Inline: proposalCall.method.toHex()}]);3366 }33673368 externalProposeDefault(signer: TSigner, proposalCall: any) {3369 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalProposeDefault', [{Inline: proposalCall.method.toHex()}]);3370 }33713372 externalProposeDefaultWithPreimage(signer: TSigner, preimage: string) {3373 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.externalProposeDefault', [{Legacy: preimage}]);3374 }33753376 externalProposeCall(proposalCall: any) {3377 return this.helper.constructApiCall('api.tx.democracy.externalPropose', [{Inline: proposalCall.method.toHex()}]);3378 }33793380 externalProposeMajorityCall(proposalCall: any) {3381 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [{Inline: proposalCall.method.toHex()}]);3382 }33833384 externalProposeDefaultCall(proposalCall: any) {3385 return this.helper.constructApiCall('api.tx.democracy.externalProposeDefault', [{Inline: proposalCall.method.toHex()}]);3386 }33873388 externalProposeDefaultWithPreimageCall(preimage: string) {3389 return this.helper.constructApiCall('api.tx.democracy.externalProposeDefault', [{Legacy: preimage}]);3390 }33913392 // ... and blacklist external proposal hash.3393 vetoExternal(signer: TSigner, proposalHash: string) {3394 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.vetoExternal', [proposalHash]);3395 }33963397 vetoExternalCall(proposalHash: string) {3398 return this.helper.constructApiCall('api.tx.democracy.vetoExternal', [proposalHash]);3399 }34003401 blacklist(signer: TSigner, proposalHash: string, referendumIndex: number | null = null) {3402 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.blacklist', [proposalHash, referendumIndex]);3403 }34043405 blacklistCall(proposalHash: string, referendumIndex: number | null = null) {3406 return this.helper.constructApiCall('api.tx.democracy.blacklist', [proposalHash, referendumIndex]);3407 }34083409 // proposal. CancelProposalOrigin (root or all techcom)3410 cancelProposal(signer: TSigner, proposalIndex: number) {3411 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.cancelProposal', [proposalIndex]);3412 }34133414 cancelProposalCall(proposalIndex: number) {3415 return this.helper.constructApiCall('api.tx.democracy.cancelProposal', [proposalIndex]);3416 }34173418 clearPublicProposals(signer: TSigner) {3419 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.clearPublicProposals', []);3420 }34213422 fastTrack(signer: TSigner, proposalHash: string, votingPeriod: number, delayPeriod: number) {3423 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3424 }34253426 fastTrackCall(proposalHash: string, votingPeriod: number, delayPeriod: number) {3427 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3428 }34293430 // referendum. CancellationOrigin (TechCom member)3431 emergencyCancel(signer: TSigner, referendumIndex: number) {3432 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.emergencyCancel', [referendumIndex]);3433 }34343435 emergencyCancelCall(referendumIndex: number) {3436 return this.helper.constructApiCall('api.tx.democracy.emergencyCancel', [referendumIndex]);3437 }34383439 vote(signer: TSigner, referendumIndex: number, vote: any) {3440 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, vote]);3441 }34423443 removeVote(signer: TSigner, referendumIndex: number, targetAccount?: string) {3444 if(targetAccount) {3445 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.removeOtherVote', [targetAccount, referendumIndex]);3446 } else {3447 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.removeVote', [referendumIndex]);3448 }3449 }34503451 unlock(signer: TSigner, targetAccount: string) {3452 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.unlock', [targetAccount]);3453 }34543455 delegate(signer: TSigner, toAccount: string, conviction: PalletDemocracyConviction, balance: bigint) {3456 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.delegate', [toAccount, conviction, balance]);3457 }34583459 undelegate(signer: TSigner) {3460 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.undelegate', []);3461 }34623463 async referendumInfo(referendumIndex: number) {3464 return (await this.helper.callRpc('api.query.democracy.referendumInfoOf', [referendumIndex])).toJSON();3465 }34663467 async publicProposals() {3468 return (await this.helper.callRpc('api.query.democracy.publicProps', [])).toJSON();3469 }34703471 async findPublicProposal(proposalIndex: number) {3472 const proposalInfo = (await this.publicProposals()).find((proposalInfo: any[]) => proposalInfo[0] == proposalIndex);34733474 return proposalInfo ? proposalInfo[1] : null;3475 }34763477 async expectPublicProposal(proposalIndex: number) {3478 const proposal = await this.findPublicProposal(proposalIndex);34793480 if(proposal) {3481 return proposal;3482 } else {3483 throw Error(`Proposal #${proposalIndex} is expected to exist`);3484 }3485 }34863487 async getExternalProposal() {3488 return (await this.helper.callRpc('api.query.democracy.nextExternal', []));3489 }34903491 async expectExternalProposal() {3492 const proposal = await this.getExternalProposal();34933494 if(proposal) {3495 return proposal;3496 } else {3497 throw Error('An external proposal is expected to exist');3498 }3499 }35003501 /* setMetadata? */35023503 /* todo?3504 referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3505 return this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3506 }*/3507}35083509class PreimageGroup extends HelperGroup<UniqueHelper> {3510 async getPreimageInfo(h256: string) {3511 return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();3512 }35133514 /**3515 * Create a preimage from an API call.3516 * @param signer keyring of the signer.3517 * @param call an extrinsic call3518 * @example await notePreimageFromCall(preimageMaker,3519 * helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd])3520 * );3521 * @returns promise of extrinsic execution.3522 */3523 notePreimageFromCall(signer: TSigner, call: any, returnPreimageHash = false) {3524 return this.notePreimage(signer, call.method.toHex(), returnPreimageHash);3525 }35263527 /**3528 * Create a preimage with a hex or a byte array.3529 * @param signer keyring of the signer.3530 * @param bytes preimage encoded in hex or a byte array, e.g. an extrinsic call.3531 * @example await notePreimage(preimageMaker,3532 * helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex()3533 * );3534 * @returns promise of extrinsic execution.3535 */3536 async notePreimage(signer: TSigner, bytes: string | Uint8Array, returnPreimageHash = false) {3537 const promise = this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);3538 if(returnPreimageHash) {3539 const result = await promise;3540 const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');3541 const preimageHash = events[0].event.data[0].toHuman();3542 return preimageHash;3543 }3544 return promise;3545 }35463547 /**3548 * Delete an existing preimage and return the deposit.3549 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).3550 * @param h256 hash of the preimage.3551 * @returns promise of extrinsic execution.3552 */3553 unnotePreimage(signer: TSigner, h256: string) {3554 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);3555 }35563557 /**3558 * Request a preimage be uploaded to the chain without paying any fees or deposits.3559 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).3560 * @param h256 hash of the preimage.3561 * @returns promise of extrinsic execution.3562 */3563 requestPreimage(signer: TSigner, h256: string) {3564 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);3565 }35663567 /**3568 * Clear a previously made request for a preimage.3569 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).3570 * @param h256 hash of the preimage.3571 * @returns promise of extrinsic execution.3572 */3573 unrequestPreimage(signer: TSigner, h256: string) {3574 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);3575 }3576}35773578class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {3579 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {3580 await this.helper.executeExtrinsic(3581 signer,3582 'api.tx.foreignAssets.registerForeignAsset',3583 [ownerAddress, location, metadata],3584 true,3585 );3586 }35873588 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {3589 await this.helper.executeExtrinsic(3590 signer,3591 'api.tx.foreignAssets.updateForeignAsset',3592 [foreignAssetId, location, metadata],3593 true,3594 );3595 }3596}35973598class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {3599 palletName: string;36003601 constructor(helper: T, palletName: string) {3602 super(helper);36033604 this.palletName = palletName;3605 }36063607 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {3608 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);3609 }36103611 async setSafeXcmVersion(signer: TSigner, version: number) {3612 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);3613 }36143615 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {3616 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);3617 }36183619 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {3620 const destinationContent = {3621 parents: 0,3622 interior: {3623 X1: {3624 Parachain: destinationParaId,3625 },3626 },3627 };36283629 const beneficiaryContent = {3630 parents: 0,3631 interior: {3632 X1: {3633 AccountId32: {3634 network: 'Any',3635 id: targetAccount,3636 },3637 },3638 },3639 };36403641 const assetsContent = [3642 {3643 id: {3644 Concrete: {3645 parents: 0,3646 interior: 'Here',3647 },3648 },3649 fun: {3650 Fungible: amount,3651 },3652 },3653 ];36543655 let destination;3656 let beneficiary;3657 let assets;36583659 if(xcmVersion == 2) {3660 destination = {V1: destinationContent};3661 beneficiary = {V1: beneficiaryContent};3662 assets = {V1: assetsContent};36633664 } else if(xcmVersion == 3) {3665 destination = {V2: destinationContent};3666 beneficiary = {V2: beneficiaryContent};3667 assets = {V2: assetsContent};36683669 } else {3670 throw Error('Unknown XCM version: ' + xcmVersion);3671 }36723673 const feeAssetItem = 0;36743675 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3676 }36773678 async send(signer: IKeyringPair, destination: any, message: any) {3679 await this.helper.executeExtrinsic(3680 signer,3681 `api.tx.${this.palletName}.send`,3682 [3683 destination,3684 message,3685 ],3686 true,3687 );3688 }3689}36903691class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3692 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3693 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3694 }36953696 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3697 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3698 }36993700 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3701 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3702 }3703}37043705class PolkadexXcmHelperGroup<T extends ChainHelperBase> extends HelperGroup<T> {3706 async whitelistToken(signer: TSigner, assetId: any) {3707 await this.helper.executeExtrinsic(signer, 'api.tx.xcmHelper.whitelistToken', [assetId], true);3708 }3709}37103711class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3712 async accounts(address: string, currencyId: any) {3713 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3714 return BigInt(free);3715 }3716}37173718class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3719 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3720 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3721 }37223723 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3724 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3725 }37263727 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3728 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3729 }37303731 async account(assetId: string | number, address: string) {3732 const accountAsset = (3733 await this.helper.callRpc('api.query.assets.account', [assetId, address])3734 ).toJSON()! as any;37353736 if(accountAsset !== null) {3737 return BigInt(accountAsset['balance']);3738 } else {3739 return null;3740 }3741 }3742}37433744class UtilityGroup<T extends ChainHelperBase> extends HelperGroup<T> {3745 async batch(signer: TSigner, txs: any[]) {3746 return await this.helper.executeExtrinsic(signer, 'api.tx.utility.batch', [txs]);3747 }37483749 async batchAll(signer: TSigner, txs: any[]) {3750 return await this.helper.executeExtrinsic(signer, 'api.tx.utility.batchAll', [txs]);3751 }37523753 batchAllCall(txs: any[]) {3754 return this.helper.constructApiCall('api.tx.utility.batchAll', [txs]);3755 }3756}37573758class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3759 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3760 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3761 }3762}37633764class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3765 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3766 const apiPrefix = 'api.tx.assetManager.';37673768 const registerTx = this.helper.constructApiCall(3769 apiPrefix + 'registerForeignAsset',3770 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3771 );37723773 const setUnitsTx = this.helper.constructApiCall(3774 apiPrefix + 'setAssetUnitsPerSecond',3775 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3776 );37773778 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3779 const encodedProposal = batchCall?.method.toHex() || '';3780 return encodedProposal;3781 }37823783 async assetTypeId(location: any) {3784 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3785 }3786}37873788class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3789 notePreimagePallet: string;37903791 constructor(helper: MoonbeamHelper, options: { [key: string]: any } = {}) {3792 super(helper);3793 this.notePreimagePallet = options.notePreimagePallet;3794 }37953796 async notePreimage(signer: TSigner, encodedProposal: string) {3797 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3798 }37993800 externalProposeMajority(proposal: any) {3801 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3802 }38033804 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3805 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3806 }38073808 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3809 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3810 }3811}38123813class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3814 collective: string;38153816 constructor(helper: MoonbeamHelper, collective: string) {3817 super(helper);38183819 this.collective = collective;3820 }38213822 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3823 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3824 }38253826 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3827 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3828 }38293830 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3831 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3832 }38333834 async proposalCount() {3835 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3836 }3837}38383839export type ChainHelperBaseConstructor = new (...args: any[]) => ChainHelperBase;3840export type UniqueHelperConstructor = new (...args: any[]) => UniqueHelper;38413842export class UniqueHelper extends ChainHelperBase {3843 balance: BalanceGroup<UniqueHelper>;3844 collection: CollectionGroup;3845 nft: NFTGroup;3846 rft: RFTGroup;3847 ft: FTGroup;3848 staking: StakingGroup;3849 scheduler: SchedulerGroup;3850 collatorSelection: CollatorSelectionGroup;3851 council: ICollectiveGroup;3852 technicalCommittee: ICollectiveGroup;3853 fellowship: IFellowshipGroup;3854 democracy: DemocracyGroup;3855 preimage: PreimageGroup;3856 foreignAssets: ForeignAssetsGroup;3857 xcm: XcmGroup<UniqueHelper>;3858 xTokens: XTokensGroup<UniqueHelper>;3859 tokens: TokensGroup<UniqueHelper>;3860 utility: UtilityGroup<UniqueHelper>;38613862 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3863 super(logger, options.helperBase ?? UniqueHelper);38643865 this.balance = new BalanceGroup(this);3866 this.collection = new CollectionGroup(this);3867 this.nft = new NFTGroup(this);3868 this.rft = new RFTGroup(this);3869 this.ft = new FTGroup(this);3870 this.staking = new StakingGroup(this);3871 this.scheduler = new SchedulerGroup(this);3872 this.collatorSelection = new CollatorSelectionGroup(this);3873 this.council = {3874 collective: new CollectiveGroup(this, 'council'),3875 membership: new CollectiveMembershipGroup(this, 'councilMembership'),3876 };3877 this.technicalCommittee = {3878 collective: new CollectiveGroup(this, 'technicalCommittee'),3879 membership: new CollectiveMembershipGroup(this, 'technicalCommitteeMembership'),3880 };3881 this.fellowship = {3882 collective: new RankedCollectiveGroup(this, 'fellowshipCollective'),3883 referenda: new ReferendaGroup(this, 'fellowshipReferenda'),3884 };3885 this.democracy = new DemocracyGroup(this);3886 this.preimage = new PreimageGroup(this);3887 this.foreignAssets = new ForeignAssetsGroup(this);3888 this.xcm = new XcmGroup(this, 'polkadotXcm');3889 this.xTokens = new XTokensGroup(this);3890 this.tokens = new TokensGroup(this);3891 this.utility = new UtilityGroup(this);3892 }38933894 getSudo<T extends UniqueHelper>() {3895 // eslint-disable-next-line @typescript-eslint/naming-convention3896 const SudoHelperType = SudoHelper(this.helperBase);3897 return this.clone(SudoHelperType) as T;3898 }3899}39003901export class XcmChainHelper extends ChainHelperBase {3902 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3903 const wsProvider = new WsProvider(wsEndpoint);3904 this.api = new ApiPromise({3905 provider: wsProvider,3906 });3907 await this.api.isReadyOrError;3908 this.network = await UniqueHelper.detectNetwork(this.api);3909 }3910}39113912export class RelayHelper extends XcmChainHelper {3913 balance: SubstrateBalanceGroup<RelayHelper>;3914 xcm: XcmGroup<RelayHelper>;39153916 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3917 super(logger, options.helperBase ?? RelayHelper);39183919 this.balance = new SubstrateBalanceGroup(this);3920 this.xcm = new XcmGroup(this, 'xcmPallet');3921 }3922}39233924export class WestmintHelper extends XcmChainHelper {3925 balance: SubstrateBalanceGroup<WestmintHelper>;3926 xcm: XcmGroup<WestmintHelper>;3927 assets: AssetsGroup<WestmintHelper>;3928 xTokens: XTokensGroup<WestmintHelper>;39293930 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3931 super(logger, options.helperBase ?? WestmintHelper);39323933 this.balance = new SubstrateBalanceGroup(this);3934 this.xcm = new XcmGroup(this, 'polkadotXcm');3935 this.assets = new AssetsGroup(this);3936 this.xTokens = new XTokensGroup(this);3937 }3938}39393940export class MoonbeamHelper extends XcmChainHelper {3941 balance: EthereumBalanceGroup<MoonbeamHelper>;3942 assetManager: MoonbeamAssetManagerGroup;3943 assets: AssetsGroup<MoonbeamHelper>;3944 xTokens: XTokensGroup<MoonbeamHelper>;3945 democracy: MoonbeamDemocracyGroup;3946 collective: {3947 council: MoonbeamCollectiveGroup,3948 techCommittee: MoonbeamCollectiveGroup,3949 };39503951 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3952 super(logger, options.helperBase ?? MoonbeamHelper);39533954 this.balance = new EthereumBalanceGroup(this);3955 this.assetManager = new MoonbeamAssetManagerGroup(this);3956 this.assets = new AssetsGroup(this);3957 this.xTokens = new XTokensGroup(this);3958 this.democracy = new MoonbeamDemocracyGroup(this, options);3959 this.collective = {3960 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3961 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3962 };3963 }3964}39653966export class AstarHelper extends XcmChainHelper {3967 balance: SubstrateBalanceGroup<AstarHelper>;3968 assets: AssetsGroup<AstarHelper>;3969 xcm: XcmGroup<AstarHelper>;39703971 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3972 super(logger, options.helperBase ?? AstarHelper);39733974 this.balance = new SubstrateBalanceGroup(this);3975 this.assets = new AssetsGroup(this);3976 this.xcm = new XcmGroup(this, 'polkadotXcm');3977 }39783979 getSudo<T extends UniqueHelper>() {3980 // eslint-disable-next-line @typescript-eslint/naming-convention3981 const SudoHelperType = SudoHelper(this.helperBase);3982 return this.clone(SudoHelperType) as T;3983 }3984}39853986export class AcalaHelper extends XcmChainHelper {3987 balance: SubstrateBalanceGroup<AcalaHelper>;3988 assetRegistry: AcalaAssetRegistryGroup;3989 xTokens: XTokensGroup<AcalaHelper>;3990 tokens: TokensGroup<AcalaHelper>;3991 xcm: XcmGroup<AcalaHelper>;39923993 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3994 super(logger, options.helperBase ?? AcalaHelper);39953996 this.balance = new SubstrateBalanceGroup(this);3997 this.assetRegistry = new AcalaAssetRegistryGroup(this);3998 this.xTokens = new XTokensGroup(this);3999 this.tokens = new TokensGroup(this);4000 this.xcm = new XcmGroup(this, 'polkadotXcm');4001 }40024003 getSudo<T extends AcalaHelper>() {4004 // eslint-disable-next-line @typescript-eslint/naming-convention4005 const SudoHelperType = SudoHelper(this.helperBase);4006 return this.clone(SudoHelperType) as T;4007 }4008}40094010export class PolkadexHelper extends XcmChainHelper {4011 assets: AssetsGroup<PolkadexHelper>;4012 balance: SubstrateBalanceGroup<PolkadexHelper>;4013 xTokens: XTokensGroup<PolkadexHelper>;4014 xcm: XcmGroup<PolkadexHelper>;4015 xcmHelper: PolkadexXcmHelperGroup<PolkadexHelper>;40164017 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {4018 super(logger, options.helperBase ?? PolkadexHelper);40194020 this.assets = new AssetsGroup(this);4021 this.balance = new SubstrateBalanceGroup(this);4022 this.xTokens = new XTokensGroup(this);4023 this.xcm = new XcmGroup(this, 'polkadotXcm');4024 this.xcmHelper = new PolkadexXcmHelperGroup(this);4025 }40264027 getSudo<T extends PolkadexHelper>() {4028 // eslint-disable-next-line @typescript-eslint/naming-convention4029 const SudoHelperType = SudoHelper(this.helperBase);4030 return this.clone(SudoHelperType) as T;4031 }4032}40334034// eslint-disable-next-line @typescript-eslint/naming-convention4035function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {4036 return class extends Base {4037 scheduleFn: 'schedule' | 'scheduleAfter';4038 blocksNum: number;4039 options: ISchedulerOptions;40404041 constructor(...args: any[]) {4042 const logger = args[0] as ILogger;4043 const options = args[1] as {4044 scheduleFn: 'schedule' | 'scheduleAfter',4045 blocksNum: number,4046 options: ISchedulerOptions4047 };40484049 super(logger);40504051 this.scheduleFn = options.scheduleFn;4052 this.blocksNum = options.blocksNum;4053 this.options = options.options;4054 }40554056 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {4057 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);40584059 const mandatorySchedArgs = [4060 this.blocksNum,4061 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,4062 this.options.priority ?? null,4063 scheduledTx,4064 ];40654066 let schedArgs;4067 let scheduleFn;40684069 if(this.options.scheduledId) {4070 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];40714072 if(this.scheduleFn == 'schedule') {4073 scheduleFn = 'scheduleNamed';4074 } else if(this.scheduleFn == 'scheduleAfter') {4075 scheduleFn = 'scheduleNamedAfter';4076 }4077 } else {4078 schedArgs = mandatorySchedArgs;4079 scheduleFn = this.scheduleFn;4080 }40814082 const extrinsic = 'api.tx.scheduler.' + scheduleFn;40834084 return super.executeExtrinsic(4085 sender,4086 extrinsic as any,4087 schedArgs,4088 expectSuccess,4089 );4090 }4091 };4092}40934094// eslint-disable-next-line @typescript-eslint/naming-convention4095function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {4096 return class extends Base {4097 constructor(...args: any[]) {4098 super(...args);4099 }41004101 async executeExtrinsic(4102 sender: IKeyringPair,4103 extrinsic: string,4104 params: any[],4105 expectSuccess?: boolean,4106 options: Partial<SignerOptions> | null = null,4107 ): Promise<ITransactionResult> {4108 const call = this.constructApiCall(extrinsic, params);4109 const result = await super.executeExtrinsic(4110 sender,4111 'api.tx.sudo.sudo',4112 [call],4113 expectSuccess,4114 options,4115 );41164117 if(result.status === 'Fail') return result;41184119 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;4120 if(data.isErr) {4121 if(data.asErr.isModule) {4122 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;4123 const metaError = super.getApi()?.registry.findMetaError(error);4124 throw new Error(`${metaError.section}.${metaError.name}`);4125 } else if(data.asErr.isToken) {4126 throw new Error(`Token: ${data.asErr.asToken}`);4127 }4128 // May be [object Object] in case of unhandled non-unit enum4129 throw new Error(`Misc: ${data.asErr.toHuman()}`);4130 }4131 return result;4132 }4133 async executeExtrinsicUncheckedWeight(4134 sender: IKeyringPair,4135 extrinsic: string,4136 params: any[],4137 expectSuccess?: boolean,4138 options: Partial<SignerOptions> | null = null,4139 ): Promise<ITransactionResult> {4140 const call = this.constructApiCall(extrinsic, params);4141 const result = await super.executeExtrinsic(4142 sender,4143 'api.tx.sudo.sudoUncheckedWeight',4144 [call, {refTime: 0, proofSize: 0}],4145 expectSuccess,4146 options,4147 );41484149 if(result.status === 'Fail') return result;41504151 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;4152 if(data.isErr) {4153 if(data.asErr.isModule) {4154 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;4155 const metaError = super.getApi()?.registry.findMetaError(error);4156 throw new Error(`${metaError.section}.${metaError.name}`);4157 } else if(data.asErr.isToken) {4158 throw new Error(`Token: ${data.asErr.asToken}`);4159 }4160 // May be [object Object] in case of unhandled non-unit enum4161 throw new Error(`Misc: ${data.asErr.toHuman()}`);4162 }4163 return result;4164 }4165 };4166}41674168export class UniqueBaseCollection {4169 helper: UniqueHelper;4170 collectionId: number;41714172 constructor(collectionId: number, uniqueHelper: UniqueHelper) {4173 this.collectionId = collectionId;4174 this.helper = uniqueHelper;4175 }41764177 async getData() {4178 return await this.helper.collection.getData(this.collectionId);4179 }41804181 async getLastTokenId() {4182 return await this.helper.collection.getLastTokenId(this.collectionId);4183 }41844185 async doesTokenExist(tokenId: number) {4186 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);4187 }41884189 async getAdmins() {4190 return await this.helper.collection.getAdmins(this.collectionId);4191 }41924193 async getAllowList() {4194 return await this.helper.collection.getAllowList(this.collectionId);4195 }41964197 async getEffectiveLimits() {4198 return await this.helper.collection.getEffectiveLimits(this.collectionId);4199 }42004201 async getProperties(propertyKeys?: string[] | null) {4202 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);4203 }42044205 async getPropertiesConsumedSpace() {4206 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);4207 }42084209 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {4210 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);4211 }42124213 async getOptions() {4214 return await this.helper.collection.getCollectionOptions(this.collectionId);4215 }42164217 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {4218 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);4219 }42204221 async confirmSponsorship(signer: TSigner) {4222 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);4223 }42244225 async removeSponsor(signer: TSigner) {4226 return await this.helper.collection.removeSponsor(signer, this.collectionId);4227 }42284229 async setLimits(signer: TSigner, limits: ICollectionLimits) {4230 return await this.helper.collection.setLimits(signer, this.collectionId, limits);4231 }42324233 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {4234 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);4235 }42364237 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {4238 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);4239 }42404241 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {4242 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);4243 }42444245 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {4246 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);4247 }42484249 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {4250 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);4251 }42524253 async setProperties(signer: TSigner, properties: IProperty[]) {4254 return await this.helper.collection.setProperties(signer, this.collectionId, properties);4255 }42564257 async deleteProperties(signer: TSigner, propertyKeys: string[]) {4258 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);4259 }42604261 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {4262 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);4263 }42644265 async enableNesting(signer: TSigner, permissions: INestingPermissions) {4266 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);4267 }42684269 async disableNesting(signer: TSigner) {4270 return await this.helper.collection.disableNesting(signer, this.collectionId);4271 }42724273 async burn(signer: TSigner) {4274 return await this.helper.collection.burn(signer, this.collectionId);4275 }42764277 scheduleAt<T extends UniqueHelper>(4278 executionBlockNumber: number,4279 options: ISchedulerOptions = {},4280 ) {4281 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);4282 return new UniqueBaseCollection(this.collectionId, scheduledHelper);4283 }42844285 scheduleAfter<T extends UniqueHelper>(4286 blocksBeforeExecution: number,4287 options: ISchedulerOptions = {},4288 ) {4289 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);4290 return new UniqueBaseCollection(this.collectionId, scheduledHelper);4291 }42924293 getSudo<T extends UniqueHelper>() {4294 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());4295 }4296}429742984299export class UniqueNFTCollection extends UniqueBaseCollection {4300 getTokenObject(tokenId: number) {4301 return new UniqueNFToken(tokenId, this);4302 }43034304 async getTokensByAddress(addressObj: ICrossAccountId) {4305 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);4306 }43074308 async getToken(tokenId: number, blockHashAt?: string) {4309 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);4310 }43114312 async getTokenOwner(tokenId: number, blockHashAt?: string) {4313 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);4314 }43154316 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {4317 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);4318 }43194320 async getTokenChildren(tokenId: number, blockHashAt?: string) {4321 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);4322 }43234324 async getPropertyPermissions(propertyKeys: string[] | null = null) {4325 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);4326 }43274328 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {4329 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);4330 }43314332 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {4333 const api = this.helper.getApi();4334 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();43354336 return (props! as any).consumedSpace;4337 }43384339 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {4340 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);4341 }43424343 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4344 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);4345 }43464347 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {4348 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);4349 }43504351 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {4352 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);4353 }43544355 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {4356 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});4357 }43584359 async mintMultipleTokens(signer: TSigner, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]) {4360 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);4361 }43624363 async burnToken(signer: TSigner, tokenId: number) {4364 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);4365 }43664367 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {4368 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);4369 }43704371 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {4372 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);4373 }43744375 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {4376 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);4377 }43784379 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {4380 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);4381 }43824383 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {4384 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);4385 }43864387 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4388 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);4389 }43904391 scheduleAt<T extends UniqueHelper>(4392 executionBlockNumber: number,4393 options: ISchedulerOptions = {},4394 ) {4395 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);4396 return new UniqueNFTCollection(this.collectionId, scheduledHelper);4397 }43984399 scheduleAfter<T extends UniqueHelper>(4400 blocksBeforeExecution: number,4401 options: ISchedulerOptions = {},4402 ) {4403 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);4404 return new UniqueNFTCollection(this.collectionId, scheduledHelper);4405 }44064407 getSudo<T extends UniqueHelper>() {4408 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());4409 }4410}441144124413export class UniqueRFTCollection extends UniqueBaseCollection {4414 getTokenObject(tokenId: number) {4415 return new UniqueRFToken(tokenId, this);4416 }44174418 async getToken(tokenId: number, blockHashAt?: string) {4419 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);4420 }44214422 async getTokenOwner(tokenId: number, blockHashAt?: string) {4423 return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);4424 }44254426 async getTokensByAddress(addressObj: ICrossAccountId) {4427 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);4428 }44294430 async getTop10TokenOwners(tokenId: number) {4431 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);4432 }44334434 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {4435 return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);4436 }44374438 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {4439 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);4440 }44414442 async getTokenTotalPieces(tokenId: number) {4443 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);4444 }44454446 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4447 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);4448 }44494450 async getPropertyPermissions(propertyKeys: string[] | null = null) {4451 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);4452 }44534454 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {4455 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);4456 }44574458 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {4459 const api = this.helper.getApi();4460 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();44614462 return (props! as any).consumedSpace;4463 }44644465 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount = 1n) {4466 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);4467 }44684469 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4470 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);4471 }44724473 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {4474 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);4475 }44764477 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {4478 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);4479 }44804481 async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {4482 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});4483 }44844485 async mintMultipleTokens(signer: TSigner, tokens: { pieces: bigint, owner: ICrossAccountId, properties?: IProperty[] }[]) {4486 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);4487 }44884489 async burnToken(signer: TSigner, tokenId: number, amount = 1n) {4490 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);4491 }44924493 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n) {4494 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);4495 }44964497 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {4498 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);4499 }45004501 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {4502 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);4503 }45044505 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {4506 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);4507 }45084509 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {4510 return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);4511 }45124513 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4514 return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);4515 }45164517 scheduleAt<T extends UniqueHelper>(4518 executionBlockNumber: number,4519 options: ISchedulerOptions = {},4520 ) {4521 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);4522 return new UniqueRFTCollection(this.collectionId, scheduledHelper);4523 }45244525 scheduleAfter<T extends UniqueHelper>(4526 blocksBeforeExecution: number,4527 options: ISchedulerOptions = {},4528 ) {4529 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);4530 return new UniqueRFTCollection(this.collectionId, scheduledHelper);4531 }45324533 getSudo<T extends UniqueHelper>() {4534 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());4535 }4536}453745384539export class UniqueFTCollection extends UniqueBaseCollection {4540 async getBalance(addressObj: ICrossAccountId) {4541 return await this.helper.ft.getBalance(this.collectionId, addressObj);4542 }45434544 async getTotalPieces() {4545 return await this.helper.ft.getTotalPieces(this.collectionId);4546 }45474548 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4549 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);4550 }45514552 async getTop10Owners() {4553 return await this.helper.ft.getTop10Owners(this.collectionId);4554 }45554556 async mint(signer: TSigner, amount = 1n, owner: ICrossAccountId = {Substrate: signer.address}) {4557 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);4558 }45594560 async mintWithOneOwner(signer: TSigner, tokens: { value: bigint }[], owner: ICrossAccountId = {Substrate: signer.address}) {4561 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);4562 }45634564 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4565 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);4566 }45674568 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4569 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);4570 }45714572 async burnTokens(signer: TSigner, amount = 1n) {4573 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);4574 }45754576 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {4577 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);4578 }45794580 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4581 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);4582 }45834584 scheduleAt<T extends UniqueHelper>(4585 executionBlockNumber: number,4586 options: ISchedulerOptions = {},4587 ) {4588 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);4589 return new UniqueFTCollection(this.collectionId, scheduledHelper);4590 }45914592 scheduleAfter<T extends UniqueHelper>(4593 blocksBeforeExecution: number,4594 options: ISchedulerOptions = {},4595 ) {4596 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);4597 return new UniqueFTCollection(this.collectionId, scheduledHelper);4598 }45994600 getSudo<T extends UniqueHelper>() {4601 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());4602 }4603}460446054606export class UniqueBaseToken {4607 collection: UniqueNFTCollection | UniqueRFTCollection;4608 collectionId: number;4609 tokenId: number;46104611 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {4612 this.collection = collection;4613 this.collectionId = collection.collectionId;4614 this.tokenId = tokenId;4615 }46164617 async getNextSponsored(addressObj: ICrossAccountId) {4618 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);4619 }46204621 async getProperties(propertyKeys?: string[] | null) {4622 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);4623 }46244625 async getTokenPropertiesConsumedSpace() {4626 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);4627 }46284629 async setProperties(signer: TSigner, properties: IProperty[]) {4630 return await this.collection.setTokenProperties(signer, this.tokenId, properties);4631 }46324633 async deleteProperties(signer: TSigner, propertyKeys: string[]) {4634 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);4635 }46364637 async doesExist() {4638 return await this.collection.doesTokenExist(this.tokenId);4639 }46404641 nestingAccount() {4642 return this.collection.helper.util.getTokenAccount(this);4643 }46444645 scheduleAt<T extends UniqueHelper>(4646 executionBlockNumber: number,4647 options: ISchedulerOptions = {},4648 ) {4649 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4650 return new UniqueBaseToken(this.tokenId, scheduledCollection);4651 }46524653 scheduleAfter<T extends UniqueHelper>(4654 blocksBeforeExecution: number,4655 options: ISchedulerOptions = {},4656 ) {4657 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4658 return new UniqueBaseToken(this.tokenId, scheduledCollection);4659 }46604661 getSudo<T extends UniqueHelper>() {4662 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());4663 }4664}466546664667export class UniqueNFToken extends UniqueBaseToken {4668 collection: UniqueNFTCollection;46694670 constructor(tokenId: number, collection: UniqueNFTCollection) {4671 super(tokenId, collection);4672 this.collection = collection;4673 }46744675 async getData(blockHashAt?: string) {4676 return await this.collection.getToken(this.tokenId, blockHashAt);4677 }46784679 async getOwner(blockHashAt?: string) {4680 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4681 }46824683 async getTopmostOwner(blockHashAt?: string) {4684 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4685 }46864687 async getChildren(blockHashAt?: string) {4688 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);4689 }46904691 async nest(signer: TSigner, toTokenObj: IToken) {4692 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4693 }46944695 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4696 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4697 }46984699 async transfer(signer: TSigner, addressObj: ICrossAccountId) {4700 return await this.collection.transferToken(signer, this.tokenId, addressObj);4701 }47024703 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4704 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);4705 }47064707 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {4708 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);4709 }47104711 async isApproved(toAddressObj: ICrossAccountId) {4712 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);4713 }47144715 async burn(signer: TSigner) {4716 return await this.collection.burnToken(signer, this.tokenId);4717 }47184719 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {4720 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);4721 }47224723 scheduleAt<T extends UniqueHelper>(4724 executionBlockNumber: number,4725 options: ISchedulerOptions = {},4726 ) {4727 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4728 return new UniqueNFToken(this.tokenId, scheduledCollection);4729 }47304731 scheduleAfter<T extends UniqueHelper>(4732 blocksBeforeExecution: number,4733 options: ISchedulerOptions = {},4734 ) {4735 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4736 return new UniqueNFToken(this.tokenId, scheduledCollection);4737 }47384739 getSudo<T extends UniqueHelper>() {4740 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());4741 }4742}47434744export class UniqueRFToken extends UniqueBaseToken {4745 collection: UniqueRFTCollection;47464747 constructor(tokenId: number, collection: UniqueRFTCollection) {4748 super(tokenId, collection);4749 this.collection = collection;4750 }47514752 async getData(blockHashAt?: string) {4753 return await this.collection.getToken(this.tokenId, blockHashAt);4754 }47554756 async getOwner(blockHashAt?: string) {4757 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4758 }47594760 async getTop10Owners() {4761 return await this.collection.getTop10TokenOwners(this.tokenId);4762 }47634764 async getTopmostOwner(blockHashAt?: string) {4765 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4766 }47674768 async nest(signer: TSigner, toTokenObj: IToken) {4769 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4770 }47714772 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4773 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4774 }47754776 async getBalance(addressObj: ICrossAccountId) {4777 return await this.collection.getTokenBalance(this.tokenId, addressObj);4778 }47794780 async getTotalPieces() {4781 return await this.collection.getTokenTotalPieces(this.tokenId);4782 }47834784 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {4785 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);4786 }47874788 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount = 1n) {4789 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);4790 }47914792 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4793 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);4794 }47954796 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4797 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);4798 }47994800 async repartition(signer: TSigner, amount: bigint) {4801 return await this.collection.repartitionToken(signer, this.tokenId, amount);4802 }48034804 async burn(signer: TSigner, amount = 1n) {4805 return await this.collection.burnToken(signer, this.tokenId, amount);4806 }48074808 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {4809 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);4810 }48114812 scheduleAt<T extends UniqueHelper>(4813 executionBlockNumber: number,4814 options: ISchedulerOptions = {},4815 ) {4816 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4817 return new UniqueRFToken(this.tokenId, scheduledCollection);4818 }48194820 scheduleAfter<T extends UniqueHelper>(4821 blocksBeforeExecution: number,4822 options: ISchedulerOptions = {},4823 ) {4824 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4825 return new UniqueRFToken(this.tokenId, scheduledCollection);4826 }48274828 getSudo<T extends UniqueHelper>() {4829 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4830 }4831}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 {SignerOptions} from '@polkadot/api/types/submittable';10import '../../interfaces/augment-api';11import {AugmentedSubmittables} from '@polkadot/api-base/types/submittable';12import {ApiInterfaceEvents} from '@polkadot/api/types';13import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a, blake2AsHex} from '@polkadot/util-crypto';14import {IKeyringPair} from '@polkadot/types/types';15import {hexToU8a} from '@polkadot/util/hex';16import {u8aConcat} from '@polkadot/util/u8a';17import {18 IApiListeners,19 IBlock,20 IEvent,21 IChainProperties,22 ICollectionCreationOptions,23 ICollectionLimits,24 ICollectionPermissions,25 ICrossAccountId,26 ICrossAccountIdLower,27 ILogger,28 INestingPermissions,29 IProperty,30 IStakingInfo,31 ISchedulerOptions,32 ISubstrateBalance,33 IToken,34 ITokenPropertyPermission,35 ITransactionResult,36 IUniqueHelperLog,37 TApiAllowedListeners,38 TEthereumAccount,39 TSigner,40 TSubstrateAccount,41 TNetworks,42 IEthCrossAccountId,43} from './types';44import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';45import type {Vec} from '@polkadot/types-codec';46import {FrameSystemEventRecord} from '@polkadot/types/lookup';4748export class CrossAccountId {49 Substrate!: TSubstrateAccount;50 Ethereum!: TEthereumAccount;5152 constructor(account: ICrossAccountId) {53 if('Substrate' in account) this.Substrate = account.Substrate;54 else this.Ethereum = account.Ethereum;55 }5657 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {58 switch (domain) {59 case 'Substrate': return new CrossAccountId({Substrate: account.address});60 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();61 }62 }6364 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {65 if('substrate' in address) return new CrossAccountId({Substrate: address.substrate});66 else return new CrossAccountId({Ethereum: address.ethereum});67 }6869 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70 return encodeAddress(decodeAddress(address), ss58Format);71 }7273 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75 }7677 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78 if(this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79 return this;80 }8182 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84 }8586 toEthereum(): CrossAccountId {87 if(this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88 return this;89 }9091 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92 return evmToAddress(address, ss58Format);93 }9495 toSubstrate(ss58Format?: number): CrossAccountId {96 if(this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97 return this;98 }99100 toLowerCase(): CrossAccountId {101 if(this.Substrate) this.Substrate = this.Substrate.toLowerCase();102 if(this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103 return this;104 }105}106107const nesting = {108 toChecksumAddress(address: string): string {109 if(typeof address === 'undefined') return '';110111 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113 address = address.toLowerCase().replace(/^0x/i, '');114 const addressHash = keccakAsHex(address).replace(/^0x/i, '');115 const checksumAddress = ['0x'];116117 for(let i = 0; i < address.length; i++) {118 // If ith character is 8 to f then make it uppercase119 if(parseInt(addressHash[i], 16) > 7) {120 checksumAddress.push(address[i].toUpperCase());121 } else {122 checksumAddress.push(address[i]);123 }124 }125 return checksumAddress.join('');126 },127 tokenIdToAddress(collectionId: number, tokenId: number) {128 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);129 },130};131132class UniqueUtil {133 static transactionStatus = {134 NOT_READY: 'NotReady',135 FAIL: 'Fail',136 SUCCESS: 'Success',137 };138139 static chainLogType = {140 EXTRINSIC: 'extrinsic',141 RPC: 'rpc',142 };143144 static getTokenAccount(token: IToken): CrossAccountId {145 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146 }147148 static getTokenAddress(token: IToken): string {149 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150 }151152 static getDefaultLogger(): ILogger {153 return {154 log(msg: any, level = 'INFO') {155 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156 },157 level: {158 ERROR: 'ERROR',159 WARNING: 'WARNING',160 INFO: 'INFO',161 },162 };163 }164165 static vec2str(arr: string[] | number[]) {166 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167 }168169 static str2vec(string: string) {170 if(typeof string !== 'string') return string;171 return Array.from(string).map(x => x.charCodeAt(0));172 }173174 static fromSeed(seed: string, ss58Format = 42) {175 const keyring = new Keyring({type: 'sr25519', ss58Format});176 return keyring.addFromUri(seed);177 }178179 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180 if(creationResult.status !== this.transactionStatus.SUCCESS) {181 throw Error('Unable to create collection!');182 }183184 let collectionId = null;185 creationResult.result.events.forEach(({event: {data, method, section}}) => {186 if((section === 'common') && (method === 'CollectionCreated')) {187 collectionId = parseInt(data[0].toString(), 10);188 }189 });190191 if(collectionId === null) {192 throw Error('No CollectionCreated event was found!');193 }194195 return collectionId;196 }197198 static extractTokensFromCreationResult(creationResult: ITransactionResult): {199 success: boolean,200 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],201 } {202 if(creationResult.status !== this.transactionStatus.SUCCESS) {203 throw Error('Unable to create tokens!');204 }205 let success = false;206 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];207 creationResult.result.events.forEach(({event: {data, method, section}}) => {208 if(method === 'ExtrinsicSuccess') {209 success = true;210 } else if((section === 'common') && (method === 'ItemCreated')) {211 tokens.push({212 collectionId: parseInt(data[0].toString(), 10),213 tokenId: parseInt(data[1].toString(), 10),214 owner: data[2].toHuman(),215 amount: data[3].toBigInt(),216 });217 }218 });219 return {success, tokens};220 }221222 static extractTokensFromBurnResult(burnResult: ITransactionResult): {223 success: boolean,224 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],225 } {226 if(burnResult.status !== this.transactionStatus.SUCCESS) {227 throw Error('Unable to burn tokens!');228 }229 let success = false;230 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];231 burnResult.result.events.forEach(({event: {data, method, section}}) => {232 if(method === 'ExtrinsicSuccess') {233 success = true;234 } else if((section === 'common') && (method === 'ItemDestroyed')) {235 tokens.push({236 collectionId: parseInt(data[0].toString(), 10),237 tokenId: parseInt(data[1].toString(), 10),238 owner: data[2].toHuman(),239 amount: data[3].toBigInt(),240 });241 }242 });243 return {success, tokens};244 }245246 static findCollectionInEvents(events: { event: IEvent }[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247 let eventId = null;248 events.forEach(({event: {data, method, section}}) => {249 if((section === expectedSection) && (method === expectedMethod)) {250 eventId = parseInt(data[0].toString(), 10);251 }252 });253254 if(eventId === null) {255 throw Error(`No ${expectedMethod} event was found!`);256 }257 return eventId === collectionId;258 }259260 static isTokenTransferSuccess(events: { event: IEvent }[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {261 const normalizeAddress = (address: string | ICrossAccountId) => {262 if(typeof address === 'string') return address;263 const obj = {} as any;264 Object.keys(address).forEach(k => {265 obj[k.toLocaleLowerCase()] = (address as any)[k];266 });267 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269 return address;270 };271 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272 events.forEach(({event: {data, method, section}}) => {273 if((section === 'common') && (method === 'Transfer')) {274 const hData = (data as any).toJSON();275 transfer = {276 collectionId: hData[0],277 tokenId: hData[1],278 from: normalizeAddress(hData[2]),279 to: normalizeAddress(hData[3]),280 amount: BigInt(hData[4]),281 };282 }283 });284 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287 isSuccess = isSuccess && amount === transfer.amount;288 return isSuccess;289 }290291 static bigIntToDecimals(number: bigint, decimals = 18) {292 const numberStr = number.toString();293 const dotPos = numberStr.length - decimals;294295 if(dotPos <= 0) {296 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297 } else {298 const intPart = numberStr.substring(0, dotPos);299 const fractPart = numberStr.substring(dotPos);300 return intPart + '.' + fractPart;301 }302 }303}304305class UniqueEventHelper {306 private static extractIndex(index: any): [number, number] | string {307 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308 return index.toJSON();309 }310311 private static extractSub(data: any, subTypes: any): { [key: string]: any } {312 let obj: any = {};313 let index = 0;314315 if(data.entries) {316 for(const [key, value] of data.entries()) {317 obj[key] = this.extractData(value, subTypes[index]);318 index++;319 }320 } else obj = data.toJSON();321322 return obj;323 }324325 private static toHuman(data: any) {326 return data && data.toHuman ? data.toHuman() : `${data}`;327 }328329 private static extractData(data: any, type: any): any {330 if(!type) return this.toHuman(data);331 if(['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332 if(['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334 return this.toHuman(data);335 }336337 public static extractEvents(events: { event: any, phase: any }[]): IEvent[] {338 const parsedEvents: IEvent[] = [];339340 events.forEach((record) => {341 const {event, phase} = record;342 const types = event.typeDef;343344 const eventData: IEvent = {345 section: event.section.toString(),346 method: event.method.toString(),347 index: this.extractIndex(event.index),348 data: [],349 phase: phase.toJSON(),350 };351352 event.data.forEach((val: any, index: number) => {353 eventData.data.push(this.extractData(val, types[index]));354 });355356 parsedEvents.push(eventData);357 });358359 return parsedEvents;360 }361}362const InvalidTypeSymbol = Symbol('Invalid type');363// eslint-disable-next-line @typescript-eslint/no-unused-vars364export type Invalid<ErrorMessage> =365 | ((366 invalidType: typeof InvalidTypeSymbol,367 ..._: typeof InvalidTypeSymbol[]368 ) => typeof InvalidTypeSymbol)369 | null370 | undefined;371// Has slightly better error messages than Get372type Get2<T, P extends string, E> =373 P extends `${infer Key}.${infer Key2}` ? Key extends keyof T ? Key2 extends keyof T[Key] ? T[Key][Key2] : E : E : E;374type ForceFunction<T> = T extends (...args: any) => any ? T : (...args: any) => Invalid<'not a function'>;375376export class ChainHelperBase {377 helperBase: any;378379 transactionStatus = UniqueUtil.transactionStatus;380 chainLogType = UniqueUtil.chainLogType;381 util: typeof UniqueUtil;382 eventHelper: typeof UniqueEventHelper;383 logger: ILogger;384 api: ApiPromise | null;385 forcedNetwork: TNetworks | null;386 network: TNetworks | null;387 wsEndpoint: string | null;388 chainLog: IUniqueHelperLog[];389 children: ChainHelperBase[];390 address: AddressGroup;391 chain: ChainGroup;392393 constructor(logger?: ILogger, helperBase?: any) {394 this.helperBase = helperBase;395396 this.util = UniqueUtil;397 this.eventHelper = UniqueEventHelper;398 if(typeof logger == 'undefined') logger = this.util.getDefaultLogger();399 this.logger = logger;400 this.api = null;401 this.forcedNetwork = null;402 this.network = null;403 this.wsEndpoint = null;404 this.chainLog = [];405 this.children = [];406 this.address = new AddressGroup(this);407 this.chain = new ChainGroup(this);408 }409410 clone(helperCls: ChainHelperBaseConstructor, options: { [key: string]: any } = {}) {411 Object.setPrototypeOf(helperCls.prototype, this);412 const newHelper = new helperCls(this.logger, options);413414 newHelper.api = this.api;415 newHelper.network = this.network;416 newHelper.forceNetwork = this.forceNetwork;417418 this.children.push(newHelper);419420 return newHelper;421 }422423 getEndpoint(): string {424 if(this.wsEndpoint === null) throw Error('No connection was established');425 return this.wsEndpoint;426 }427428 getApi(): ApiPromise {429 if(this.api === null) throw Error('API not initialized');430 return this.api;431 }432433 async subscribeEvents(expectedEvents: { section: string, names: string[] }[]) {434 const collectedEvents: IEvent[] = [];435 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {436 const ievents = this.eventHelper.extractEvents(events);437 ievents.forEach((event) => {438 expectedEvents.forEach((e => {439 if(event.section === e.section && e.names.includes(event.method)) {440 collectedEvents.push(event);441 }442 }));443 });444 });445 return {unsubscribe: unsubscribe as any, collectedEvents};446 }447448 clearChainLog(): void {449 this.chainLog = [];450 }451452 forceNetwork(value: TNetworks): void {453 this.forcedNetwork = value;454 }455456 async connect(wsEndpoint: string, listeners?: IApiListeners) {457 if(this.api !== null) throw Error('Already connected');458 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);459 this.wsEndpoint = wsEndpoint;460 this.api = api;461 this.network = network;462 }463464 async disconnect() {465 for(const child of this.children) {466 child.clearApi();467 }468469 if(this.api === null) return;470 await this.api.disconnect();471 this.clearApi();472 }473474 clearApi() {475 this.api = null;476 this.network = null;477 }478479 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {480 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;481 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];482483 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;484485 if(['quartz', 'unique', 'sapphire'].indexOf(spec.specName) > -1) return spec.specName;486 return 'opal';487 }488489 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {490 if(!wsEndpoint) throw new Error('wsEndpoint was not set');491 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});492 await api.isReady;493494 const network = await this.detectNetwork(api);495496 await api.disconnect();497498 return network;499 }500501 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{502 api: ApiPromise;503 network: TNetworks;504 }> {505 if(typeof network === 'undefined' || network === null) network = 'opal';506 if(!wsEndpoint) throw new Error('wsEndpoint was not set');507 const supportedRPC = {508 opal: {509 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,510 },511 quartz: {512 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,513 },514 unique: {515 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,516 },517 rococo: {},518 westend: {},519 moonbeam: {},520 moonriver: {},521 acala: {},522 karura: {},523 westmint: {},524 };525 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);526 const rpc = supportedRPC[network];527528 // TODO: investigate how to replace rpc in runtime529 // api._rpcCore.addUserInterfaces(rpc);530531 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});532533 await api.isReadyOrError;534535 if(typeof listeners === 'undefined') listeners = {};536 for(const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {537 if(!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;538 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);539 }540541 return {api, network};542 }543544 getTransactionStatus(data: { events: { event: IEvent }[], status: any }) {545 const {events, status} = data;546 if(status.isReady) {547 return this.transactionStatus.NOT_READY;548 }549 if(status.isBroadcast) {550 return this.transactionStatus.NOT_READY;551 }552 if(status.isInBlock || status.isFinalized) {553 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');554 if(errors.length > 0) {555 return this.transactionStatus.FAIL;556 }557 if(events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {558 return this.transactionStatus.SUCCESS;559 }560 }561562 return this.transactionStatus.FAIL;563 }564565 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {566 const sign = (callback: any) => {567 if(options !== null) return transaction.signAndSend(sender, options, callback);568 return transaction.signAndSend(sender, callback);569 };570 // eslint-disable-next-line no-async-promise-executor571 return new Promise(async (resolve, reject) => {572 try {573 const unsub = await sign((result: any) => {574 const status = this.getTransactionStatus(result);575576 if(status === this.transactionStatus.SUCCESS) {577 this.logger.log(`${label} successful`);578 unsub();579 resolve({result, status, blockHash: result.status.asInBlock.toHuman()});580 } else if(status === this.transactionStatus.FAIL) {581 let moduleError = null;582583 if(result.hasOwnProperty('dispatchError')) {584 const dispatchError = result['dispatchError'];585586 if(dispatchError) {587 if(dispatchError.isModule) {588 const modErr = dispatchError.asModule;589 const errorMeta = dispatchError.registry.findMetaError(modErr);590591 moduleError = `${errorMeta.section}.${errorMeta.name}`;592 } else if(dispatchError.isToken) {593 moduleError = `Token: ${dispatchError.asToken}`;594 } else {595 // May be [object Object] in case of unhandled non-unit enum596 moduleError = `Misc: ${dispatchError.toHuman()}`;597 }598 } else {599 this.logger.log(result, this.logger.level.ERROR);600 }601 }602603 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);604 unsub();605 reject({status, moduleError, result});606 }607 });608 } catch (e) {609 this.logger.log(e, this.logger.level.ERROR);610 reject(e);611 }612 });613 }614615 async signTransactionWithoutSending(signer: TSigner, tx: any) {616 const api = this.getApi();617 const signingInfo = await api.derive.tx.signingInfo(signer.address);618619 tx.sign(signer, {620 blockHash: api.genesisHash,621 genesisHash: api.genesisHash,622 runtimeVersion: api.runtimeVersion,623 nonce: signingInfo.nonce,624 });625626 return tx.toHex();627 }628629 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {630 const api = this.getApi();631 const signingInfo = await api.derive.tx.signingInfo(signer.address);632633 // We need to sign the tx because634 // unsigned transactions does not have an inclusion fee635 tx.sign(signer, {636 blockHash: api.genesisHash,637 genesisHash: api.genesisHash,638 runtimeVersion: api.runtimeVersion,639 nonce: signingInfo.nonce,640 });641642 if(len === null) {643 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;644 } else {645 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;646 }647 }648649 constructApiCall(apiCall: string, params: any[]) {650 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);651 let call = this.getApi() as any;652 for(const part of apiCall.slice(4).split('.')) {653 call = call[part];654 if(!call) {655 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';656 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);657 }658 }659 return call(...params);660 }661662 encodeApiCall(apiCall: string, params: any[]) {663 return this.constructApiCall(apiCall, params).method.toHex();664 }665666 async executeExtrinsic<667 E extends string,668 V extends (669 ...args: any) => any = ForceFunction<670 Get2<671 AugmentedSubmittables<'promise'>,672 E, (...args: any) => Invalid<'not found'>673 >674 >675 >(676 sender: TSigner,677 extrinsic: `api.tx.${E}`,678 params: Parameters<V>,679 expectSuccess = true,680 options: Partial<SignerOptions> | null = null,/*, failureMessage='expected success'*/681 ): Promise<ITransactionResult> {682 if(this.api === null) throw Error('API not initialized');683684 const startTime = (new Date()).getTime();685 let result: ITransactionResult;686 let events: IEvent[] = [];687 try {688 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;689 events = this.eventHelper.extractEvents(result.result.events);690 const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');691 if(errorEvent)692 throw Error(errorEvent.method + ': ' + extrinsic);693 }694 catch (e) {695 if(!(e as object).hasOwnProperty('status')) throw e;696 result = e as ITransactionResult;697 }698699 const endTime = (new Date()).getTime();700701 const log = {702 executedAt: endTime,703 executionTime: endTime - startTime,704 type: this.chainLogType.EXTRINSIC,705 status: result.status,706 call: extrinsic,707 signer: this.getSignerAddress(sender),708 params,709 } as IUniqueHelperLog;710711 let errorMessage = '';712713 if(result.status !== this.transactionStatus.SUCCESS) {714 if(result.moduleError) {715 errorMessage = typeof result.moduleError === 'string'716 ? result.moduleError717 : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;718 log.moduleError = errorMessage;719 }720 else if(result.result.dispatchError) log.dispatchError = result.result.dispatchError;721 }722 if(events.length > 0) log.events = events;723724 this.chainLog.push(log);725726 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {727 if(result.moduleError) throw Error(`${errorMessage}`);728 else if(result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));729 }730 return result as any;731 }732 executeExtrinsicUncheckedWeight<733 E extends string,734 V extends (735 ...args: any) => any = ForceFunction<736 Get2<737 AugmentedSubmittables<'promise'>,738 E, (...args: any) => Invalid<'not found'>739 >740 >741 >(742 sender: TSigner,743 extrinsic: `api.tx.${E}`,744 params: Parameters<V>,745 expectSuccess = true,746 options: Partial<SignerOptions> | null = null,/*, failureMessage='expected success'*/747 ): Promise<ITransactionResult> {748 throw new Error('executeExtrinsicUncheckedWeight only supported in sudo');749 }750751 async callRpc752 // TODO: make it strongly typed, or use api.query/api.rpc directly753 // <754 // K extends 'rpc' | 'query',755 // E extends string,756 // V extends (...args: any) => any = ForceFunction<757 // Get2<758 // K extends 'rpc' ? DecoratedRpc<'promise', RpcInterface> : QueryableStorage<'promise'>,759 // E, (...args: any) => Invalid<'not found'>760 // >761 // >,762 // P = Parameters<V>,763 // >764 (rpc: string, params?: any[]): Promise<any> {765766 if(typeof params === 'undefined') params = [] as any;767 if(this.api === null) throw Error('API not initialized');768 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);769770 const startTime = (new Date()).getTime();771 let result;772 let error = null;773 const log = {774 type: this.chainLogType.RPC,775 call: rpc,776 params,777 } as any as IUniqueHelperLog;778779 try {780 result = await this.constructApiCall(rpc, params as any);781 }782 catch (e) {783 error = e;784 }785786 const endTime = (new Date()).getTime();787788 log.executedAt = endTime;789 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';790 log.executionTime = endTime - startTime;791792 this.chainLog.push(log);793794 if(error !== null) throw error;795796 return result;797 }798799 getSignerAddress(signer: IKeyringPair | string): string {800 if(typeof signer === 'string') return signer;801 return signer.address;802 }803804 fetchAllPalletNames(): string[] {805 if(this.api === null) throw Error('API not initialized');806 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();807 }808809 fetchMissingPalletNames(requiredPallets: readonly string[]): string[] {810 const palletNames = this.fetchAllPalletNames();811 return requiredPallets.filter(p => !palletNames.includes(p));812 }813}814815816export class HelperGroup<T extends ChainHelperBase> {817 helper: T;818819 constructor(uniqueHelper: T) {820 this.helper = uniqueHelper;821 }822}823824825class CollectionGroup extends HelperGroup<UniqueHelper> {826 /**827 * Get number of blocks when sponsored transaction is available.828 *829 * @param collectionId ID of collection830 * @param tokenId ID of token831 * @param addressObj address for which the sponsorship is checked832 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});833 * @returns number of blocks or null if sponsorship hasn't been set834 */835 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {836 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();837 }838839 /**840 * Get the number of created collections.841 *842 * @returns number of created collections843 */844 async getTotalCount(): Promise<number> {845 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();846 }847848 /**849 * Get information about the collection with additional data,850 * including the number of tokens it contains, its administrators,851 * the normalized address of the collection's owner, and decoded name and description.852 *853 * @param collectionId ID of collection854 * @example await getData(2)855 * @returns collection information object856 */857 async getData(collectionId: number): Promise<{858 id: number;859 name: string;860 description: string;861 tokensCount: number;862 admins: CrossAccountId[];863 normalizedOwner: TSubstrateAccount;864 raw: any865 } | null> {866 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);867 const humanCollection = collection.toHuman(), collectionData = {868 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],869 raw: humanCollection,870 } as any, jsonCollection = collection.toJSON();871 if(humanCollection === null) return null;872 collectionData.raw.limits = jsonCollection.limits;873 collectionData.raw.permissions = jsonCollection.permissions;874 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);875 for(const key of ['name', 'description']) {876 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);877 }878879 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))880 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)881 : 0;882 collectionData.admins = await this.getAdmins(collectionId);883884 return collectionData;885 }886887 /**888 * Get the addresses of the collection's administrators, optionally normalized.889 *890 * @param collectionId ID of collection891 * @param normalize whether to normalize the addresses to the default ss58 format892 * @example await getAdmins(1)893 * @returns array of administrators894 */895 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {896 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();897898 return normalize899 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())900 : admins;901 }902903 /**904 * Get the addresses added to the collection allow-list, optionally normalized.905 * @param collectionId ID of collection906 * @param normalize whether to normalize the addresses to the default ss58 format907 * @example await getAllowList(1)908 * @returns array of allow-listed addresses909 */910 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {911 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();912 return normalize913 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())914 : allowListed;915 }916917 /**918 * Get the effective limits of the collection instead of null for default values919 *920 * @param collectionId ID of collection921 * @example await getEffectiveLimits(2)922 * @returns object of collection limits923 */924 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {925 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();926 }927928 /**929 * Burns the collection if the signer has sufficient permissions and collection is empty.930 *931 * @param signer keyring of signer932 * @param collectionId ID of collection933 * @example await helper.collection.burn(aliceKeyring, 3);934 * @returns ```true``` if extrinsic success, otherwise ```false```935 */936 async burn(signer: TSigner, collectionId: number): Promise<boolean> {937 const result = await this.helper.executeExtrinsic(938 signer,939 'api.tx.unique.destroyCollection', [collectionId],940 true,941 );942943 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');944 }945946 /**947 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.948 *949 * @param signer keyring of signer950 * @param collectionId ID of collection951 * @param sponsorAddress Sponsor substrate address952 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")953 * @returns ```true``` if extrinsic success, otherwise ```false```954 */955 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {956 const result = await this.helper.executeExtrinsic(957 signer,958 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],959 true,960 );961962 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');963 }964965 /**966 * Confirms consent to sponsor the collection on behalf of the signer.967 *968 * @param signer keyring of signer969 * @param collectionId ID of collection970 * @example confirmSponsorship(aliceKeyring, 10)971 * @returns ```true``` if extrinsic success, otherwise ```false```972 */973 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {974 const result = await this.helper.executeExtrinsic(975 signer,976 'api.tx.unique.confirmSponsorship', [collectionId],977 true,978 );979980 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');981 }982983 /**984 * Removes the sponsor of a collection, regardless if it consented or not.985 *986 * @param signer keyring of signer987 * @param collectionId ID of collection988 * @example removeSponsor(aliceKeyring, 10)989 * @returns ```true``` if extrinsic success, otherwise ```false```990 */991 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {992 const result = await this.helper.executeExtrinsic(993 signer,994 'api.tx.unique.removeCollectionSponsor', [collectionId],995 true,996 );997998 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');999 }10001001 /**1002 * Sets the limits of the collection. At least one limit must be specified for a correct call.1003 *1004 * @param signer keyring of signer1005 * @param collectionId ID of collection1006 * @param limits collection limits object1007 * @example1008 * await setLimits(1009 * aliceKeyring,1010 * 10,1011 * {1012 * sponsorTransferTimeout: 0,1013 * ownerCanDestroy: false1014 * }1015 * )1016 * @returns ```true``` if extrinsic success, otherwise ```false```1017 */1018 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {1019 const result = await this.helper.executeExtrinsic(1020 signer,1021 'api.tx.unique.setCollectionLimits', [collectionId, limits],1022 true,1023 );10241025 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');1026 }10271028 /**1029 * Changes the owner of the collection to the new Substrate address.1030 *1031 * @param signer keyring of signer1032 * @param collectionId ID of collection1033 * @param ownerAddress substrate address of new owner1034 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")1035 * @returns ```true``` if extrinsic success, otherwise ```false```1036 */1037 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],1041 true,1042 );10431044 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');1045 }10461047 /**1048 * Adds a collection administrator.1049 *1050 * @param signer keyring of signer1051 * @param collectionId ID of collection1052 * @param adminAddressObj Administrator address (substrate or ethereum)1053 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1054 * @returns ```true``` if extrinsic success, otherwise ```false```1055 */1056 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1057 const result = await this.helper.executeExtrinsic(1058 signer,1059 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],1060 true,1061 );10621063 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');1064 }10651066 /**1067 * Removes a collection administrator.1068 *1069 * @param signer keyring of signer1070 * @param collectionId ID of collection1071 * @param adminAddressObj Administrator address (substrate or ethereum)1072 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1073 * @returns ```true``` if extrinsic success, otherwise ```false```1074 */1075 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1076 const result = await this.helper.executeExtrinsic(1077 signer,1078 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1079 true,1080 );10811082 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1083 }10841085 /**1086 * Check if user is in allow list.1087 *1088 * @param collectionId ID of collection1089 * @param user Account to check1090 * @example await getAdmins(1)1091 * @returns is user in allow list1092 */1093 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1094 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1095 }10961097 /**1098 * Adds an address to allow list1099 * @param signer keyring of signer1100 * @param collectionId ID of collection1101 * @param addressObj address to add to the allow list1102 * @returns ```true``` if extrinsic success, otherwise ```false```1103 */1104 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1105 const result = await this.helper.executeExtrinsic(1106 signer,1107 'api.tx.unique.addToAllowList', [collectionId, addressObj],1108 true,1109 );11101111 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1112 }11131114 /**1115 * Removes an address from allow list1116 *1117 * @param signer keyring of signer1118 * @param collectionId ID of collection1119 * @param addressObj address to remove from the allow list1120 * @returns ```true``` if extrinsic success, otherwise ```false```1121 */1122 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1123 const result = await this.helper.executeExtrinsic(1124 signer,1125 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1126 true,1127 );11281129 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1130 }11311132 /**1133 * Sets onchain permissions for selected collection.1134 *1135 * @param signer keyring of signer1136 * @param collectionId ID of collection1137 * @param permissions collection permissions object1138 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1139 * @returns ```true``` if extrinsic success, otherwise ```false```1140 */1141 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1142 const result = await this.helper.executeExtrinsic(1143 signer,1144 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1145 true,1146 );11471148 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1149 }11501151 /**1152 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1153 *1154 * @param signer keyring of signer1155 * @param collectionId ID of collection1156 * @param permissions nesting permissions object1157 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1158 * @returns ```true``` if extrinsic success, otherwise ```false```1159 */1160 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1161 return await this.setPermissions(signer, collectionId, {nesting: permissions});1162 }11631164 /**1165 * Disables nesting for selected collection.1166 *1167 * @param signer keyring of signer1168 * @param collectionId ID of collection1169 * @example disableNesting(aliceKeyring, 10);1170 * @returns ```true``` if extrinsic success, otherwise ```false```1171 */1172 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1173 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1174 }11751176 /**1177 * Sets onchain properties to the collection.1178 *1179 * @param signer keyring of signer1180 * @param collectionId ID of collection1181 * @param properties array of property objects1182 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1183 * @returns ```true``` if extrinsic success, otherwise ```false```1184 */1185 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1186 const result = await this.helper.executeExtrinsic(1187 signer,1188 'api.tx.unique.setCollectionProperties', [collectionId, properties],1189 true,1190 );11911192 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1193 }11941195 /**1196 * Get collection properties.1197 *1198 * @param collectionId ID of collection1199 * @param propertyKeys optionally filter the returned properties to only these keys1200 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1201 * @returns array of key-value pairs1202 */1203 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1204 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1205 }12061207 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1208 const api = this.helper.getApi();1209 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();12101211 return (props! as any).consumedSpace;1212 }12131214 async getCollectionOptions(collectionId: number) {1215 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1216 }12171218 /**1219 * Deletes onchain properties from the collection.1220 *1221 * @param signer keyring of signer1222 * @param collectionId ID of collection1223 * @param propertyKeys array of property keys to delete1224 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1225 * @returns ```true``` if extrinsic success, otherwise ```false```1226 */1227 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1228 const result = await this.helper.executeExtrinsic(1229 signer,1230 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1231 true,1232 );12331234 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1235 }12361237 /**1238 * Changes the owner of the token.1239 *1240 * @param signer keyring of signer1241 * @param collectionId ID of collection1242 * @param tokenId ID of token1243 * @param addressObj address of a new owner1244 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1245 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1246 * @returns true if the token success, otherwise false1247 */1248 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1249 const result = await this.helper.executeExtrinsic(1250 signer,1251 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1252 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1253 );12541255 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1256 }12571258 /**1259 *1260 * Change ownership of a token(s) on behalf of the owner.1261 *1262 * @param signer keyring of signer1263 * @param collectionId ID of collection1264 * @param tokenId ID of token1265 * @param fromAddressObj address on behalf of which the token will be sent1266 * @param toAddressObj new token owner1267 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1268 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1269 * @returns true if the token success, otherwise false1270 */1271 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1272 const result = await this.helper.executeExtrinsic(1273 signer,1274 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1275 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1276 );1277 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1278 }12791280 /**1281 *1282 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1283 *1284 * @param signer keyring of signer1285 * @param collectionId ID of collection1286 * @param tokenId ID of token1287 * @param amount amount of tokens to be burned. For NFT must be set to 1n1288 * @example burnToken(aliceKeyring, 10, 5);1289 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1290 */1291 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {1292 const burnResult = await this.helper.executeExtrinsic(1293 signer,1294 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1295 true, // `Unable to burn token for ${label}`,1296 );1297 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1298 if(burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1299 return burnedTokens.success;1300 }13011302 /**1303 * Destroys a concrete instance of NFT on behalf of the owner1304 *1305 * @param signer keyring of signer1306 * @param collectionId ID of collection1307 * @param tokenId ID of token1308 * @param fromAddressObj address on behalf of which the token will be burnt1309 * @param amount amount of tokens to be burned. For NFT must be set to 1n1310 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1311 * @returns ```true``` if extrinsic success, otherwise ```false```1312 */1313 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1314 const burnResult = await this.helper.executeExtrinsic(1315 signer,1316 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1317 true, // `Unable to burn token from for ${label}`,1318 );1319 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1320 return burnedTokens.success && burnedTokens.tokens.length > 0;1321 }13221323 /**1324 * Set, change, or remove approved address to transfer the ownership of the NFT.1325 *1326 * @param signer keyring of signer1327 * @param collectionId ID of collection1328 * @param tokenId ID of token1329 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1330 * @param amount amount of token to be approved. For NFT must be set to 1n1331 * @returns ```true``` if extrinsic success, otherwise ```false```1332 */1333 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1334 const approveResult = await this.helper.executeExtrinsic(1335 signer,1336 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1337 true, // `Unable to approve token for ${label}`,1338 );13391340 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1341 }13421343 /**1344 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1345 *1346 * @param signer keyring of signer1347 * @param collectionId ID of collection1348 * @param tokenId ID of token1349 * @param fromAddressObj Signer's Ethereum address containing her tokens1350 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1351 * @param amount amount of token to be approved. For NFT must be set to 1n1352 * @returns ```true``` if extrinsic success, otherwise ```false```1353 */1354 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {1355 const approveResult = await this.helper.executeExtrinsic(1356 signer,1357 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1358 true, // `Unable to approve token for ${label}`,1359 );13601361 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1362 }13631364 /**1365 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1366 *1367 * @param signer keyring of signer1368 * @param collectionId ID of collection1369 * @param tokenId ID of token1370 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1371 * @param amount amount of token to be approved. For NFT must be set to 1n1372 * @returns ```true``` if extrinsic success, otherwise ```false```1373 */1374 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1375 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1376 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1377 }13781379 /**1380 * Get the amount of token pieces approved to transfer or burn. Normally 0.1381 *1382 * @param collectionId ID of collection1383 * @param tokenId ID of token1384 * @param toAccountObj address which is approved to use token pieces1385 * @param fromAccountObj address which may have allowed the use of its owned tokens1386 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1387 * @returns number of approved to transfer pieces1388 */1389 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1390 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1391 }13921393 /**1394 * Get the last created token ID in a collection1395 *1396 * @param collectionId ID of collection1397 * @example getLastTokenId(10);1398 * @returns id of the last created token1399 */1400 async getLastTokenId(collectionId: number): Promise<number> {1401 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1402 }14031404 /**1405 * Check if token exists1406 *1407 * @param collectionId ID of collection1408 * @param tokenId ID of token1409 * @example doesTokenExist(10, 20);1410 * @returns true if the token exists, otherwise false1411 */1412 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1413 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1414 }1415}14161417class NFTnRFT extends CollectionGroup {1418 /**1419 * Get tokens owned by account1420 *1421 * @param collectionId ID of collection1422 * @param addressObj tokens owner1423 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1424 * @returns array of token ids owned by account1425 */1426 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1427 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1428 }14291430 /**1431 * Get token data1432 *1433 * @param collectionId ID of collection1434 * @param tokenId ID of token1435 * @param propertyKeys optionally filter the token properties to only these keys1436 * @param blockHashAt optionally query the data at some block with this hash1437 * @example getToken(10, 5);1438 * @returns human readable token data1439 */1440 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1441 properties: IProperty[];1442 owner: CrossAccountId;1443 normalizedOwner: CrossAccountId;1444 } | null> {1445 let tokenData;1446 if(typeof blockHashAt === 'undefined') {1447 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1448 }1449 else {1450 if(propertyKeys.length == 0) {1451 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1452 if(!collection) return null;1453 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1454 }1455 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1456 }1457 tokenData = tokenData.toHuman();1458 if(tokenData === null || tokenData.owner === null) return null;1459 const owner = {} as any;1460 for(const key of Object.keys(tokenData.owner)) {1461 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1462 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1463 : tokenData.owner[key];1464 }1465 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1466 return tokenData;1467 }14681469 /**1470 * Get token's owner1471 * @param collectionId ID of collection1472 * @param tokenId ID of token1473 * @param blockHashAt optionally query the data at the block with this hash1474 * @example getTokenOwner(10, 5);1475 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1476 */1477 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1478 let owner;1479 if(typeof blockHashAt === 'undefined') {1480 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1481 } else {1482 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1483 }1484 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1485 }14861487 /**1488 * Recursively find the address that owns the token1489 * @param collectionId ID of collection1490 * @param tokenId ID of token1491 * @param blockHashAt1492 * @example getTokenTopmostOwner(10, 5);1493 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1494 */1495 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1496 let owner;1497 if(typeof blockHashAt === 'undefined') {1498 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1499 } else {1500 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1501 }15021503 if(owner === null) return null;15041505 return owner.toHuman();1506 }15071508 /**1509 * Nest one token into another1510 * @param signer keyring of signer1511 * @param tokenObj token to be nested1512 * @param rootTokenObj token to be parent1513 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1514 * @returns ```true``` if extrinsic success, otherwise ```false```1515 */1516 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1517 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1518 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1519 if(!result) {1520 throw Error('Unable to nest token!');1521 }1522 return result;1523 }15241525 /**1526 * Remove token from nested state1527 * @param signer keyring of signer1528 * @param tokenObj token to unnest1529 * @param rootTokenObj parent of a token1530 * @param toAddressObj address of a new token owner1531 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1532 * @returns ```true``` if extrinsic success, otherwise ```false```1533 */1534 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1535 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1536 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1537 if(!result) {1538 throw Error('Unable to unnest token!');1539 }1540 return result;1541 }15421543 /**1544 * Set permissions to change token properties1545 *1546 * @param signer keyring of signer1547 * @param collectionId ID of collection1548 * @param permissions permissions to change a property by the collection admin or token owner1549 * @example setTokenPropertyPermissions(1550 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1551 * )1552 * @returns true if extrinsic success otherwise false1553 */1554 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1555 const result = await this.helper.executeExtrinsic(1556 signer,1557 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1558 true,1559 );15601561 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1562 }15631564 /**1565 * Get token property permissions.1566 *1567 * @param collectionId ID of collection1568 * @param propertyKeys optionally filter the returned property permissions to only these keys1569 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1570 * @returns array of key-permission pairs1571 */1572 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1573 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1574 }15751576 /**1577 * Set token properties1578 *1579 * @param signer keyring of signer1580 * @param collectionId ID of collection1581 * @param tokenId ID of token1582 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1583 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1584 * @returns ```true``` if extrinsic success, otherwise ```false```1585 */1586 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1587 const result = await this.helper.executeExtrinsic(1588 signer,1589 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1590 true,1591 );15921593 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1594 }15951596 /**1597 * Get properties, metadata assigned to a token.1598 *1599 * @param collectionId ID of collection1600 * @param tokenId ID of token1601 * @param propertyKeys optionally filter the returned properties to only these keys1602 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1603 * @returns array of key-value pairs1604 */1605 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1606 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1607 }16081609 /**1610 * Delete the provided properties of a token1611 * @param signer keyring of signer1612 * @param collectionId ID of collection1613 * @param tokenId ID of token1614 * @param propertyKeys property keys to be deleted1615 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1616 * @returns ```true``` if extrinsic success, otherwise ```false```1617 */1618 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1619 const result = await this.helper.executeExtrinsic(1620 signer,1621 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1622 true,1623 );16241625 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1626 }16271628 /**1629 * Mint new collection1630 *1631 * @param signer keyring of signer1632 * @param collectionOptions basic collection options and properties1633 * @param mode NFT or RFT type of a collection1634 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1635 * @returns object of the created collection1636 */1637 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1638 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1639 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1640 for(const key of ['name', 'description', 'tokenPrefix']) {1641 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);1642 }16431644 let flags = 0;1645 // convert CollectionFlags to number and join them in one number1646 if(collectionOptions.flags) {1647 for(let i = 0; i < collectionOptions.flags.length; i++){1648 const flag = collectionOptions.flags[i];1649 flags = flags | flag;1650 }1651 }1652 collectionOptions.flags = [flags];16531654 const creationResult = await this.helper.executeExtrinsic(1655 signer,1656 'api.tx.unique.createCollectionEx', [collectionOptions],1657 true, // errorLabel,1658 );1659 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1660 }16611662 getCollectionObject(_collectionId: number): any {1663 return null;1664 }16651666 getTokenObject(_collectionId: number, _tokenId: number): any {1667 return null;1668 }16691670 /**1671 * Tells whether the given `owner` approves the `operator`.1672 * @param collectionId ID of collection1673 * @param owner owner address1674 * @param operator operator addrees1675 * @returns true if operator is enabled1676 */1677 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1678 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1679 }16801681 /** Sets or unsets the approval of a given operator.1682 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1683 * @param operator Operator1684 * @param approved Should operator status be granted or revoked?1685 * @returns ```true``` if extrinsic success, otherwise ```false```1686 */1687 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1688 const result = await this.helper.executeExtrinsic(1689 signer,1690 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1691 true,1692 );1693 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1694 }1695}169616971698class NFTGroup extends NFTnRFT {1699 /**1700 * Get collection object1701 * @param collectionId ID of collection1702 * @example getCollectionObject(2);1703 * @returns instance of UniqueNFTCollection1704 */1705 getCollectionObject(collectionId: number): UniqueNFTCollection {1706 return new UniqueNFTCollection(collectionId, this.helper);1707 }17081709 /**1710 * Get token object1711 * @param collectionId ID of collection1712 * @param tokenId ID of token1713 * @example getTokenObject(10, 5);1714 * @returns instance of UniqueNFTToken1715 */1716 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1717 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1718 }17191720 /**1721 * Is token approved to transfer1722 * @param collectionId ID of collection1723 * @param tokenId ID of token1724 * @param toAccountObj address to be approved1725 * @returns ```true``` if extrinsic success, otherwise ```false```1726 */1727 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1728 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1729 }17301731 /**1732 * Changes the owner of the token.1733 *1734 * @param signer keyring of signer1735 * @param collectionId ID of collection1736 * @param tokenId ID of token1737 * @param addressObj address of a new owner1738 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1739 * @returns ```true``` if extrinsic success, otherwise ```false```1740 */1741 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1742 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1743 }17441745 /**1746 *1747 * Change ownership of a NFT on behalf of the owner.1748 *1749 * @param signer keyring of signer1750 * @param collectionId ID of collection1751 * @param tokenId ID of token1752 * @param fromAddressObj address on behalf of which the token will be sent1753 * @param toAddressObj new token owner1754 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1755 * @returns ```true``` if extrinsic success, otherwise ```false```1756 */1757 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1758 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1759 }17601761 /**1762 * Get tokens nested in the provided token1763 * @param collectionId ID of collection1764 * @param tokenId ID of token1765 * @param blockHashAt optionally query the data at the block with this hash1766 * @example getTokenChildren(10, 5);1767 * @returns tokens whose depth of nesting is <= 51768 */1769 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1770 let children;1771 if(typeof blockHashAt === 'undefined') {1772 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1773 } else {1774 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1775 }17761777 return children.toJSON().map((x: any) => ({collectionId: x.collection, tokenId: x.token}));1778 }17791780 /**1781 * Mint new collection1782 * @param signer keyring of signer1783 * @param collectionOptions Collection options1784 * @example1785 * mintCollection(aliceKeyring, {1786 * name: 'New',1787 * description: 'New collection',1788 * tokenPrefix: 'NEW',1789 * })1790 * @returns object of the created collection1791 */1792 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1793 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1794 }17951796 /**1797 * Mint new token1798 * @param signer keyring of signer1799 * @param data token data1800 * @returns created token object1801 */1802 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1803 const creationResult = await this.helper.executeExtrinsic(1804 signer,1805 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1806 NFT: {1807 properties: data.properties,1808 },1809 }],1810 true,1811 );1812 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1813 if(createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1814 if(createdTokens.tokens.length < 1) throw Error('No tokens minted');1815 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1816 }18171818 /**1819 * Mint multiple NFT tokens1820 * @param signer keyring of signer1821 * @param collectionId ID of collection1822 * @param tokens array of tokens with owner and properties1823 * @example1824 * mintMultipleTokens(aliceKeyring, 10, [{1825 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1826 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1827 * },{1828 * owner: {Ethereum: "0x9F0583DbB855d..."},1829 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1830 * }]);1831 * @returns ```true``` if extrinsic success, otherwise ```false```1832 */1833 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1834 const creationResult = await this.helper.executeExtrinsic(1835 signer,1836 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1837 true,1838 );1839 const collection = this.getCollectionObject(collectionId);1840 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1841 }18421843 /**1844 * Mint multiple NFT tokens with one owner1845 * @param signer keyring of signer1846 * @param collectionId ID of collection1847 * @param owner tokens owner1848 * @param tokens array of tokens with owner and properties1849 * @example1850 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1851 * properties: [{1852 * key: "gender",1853 * value: "female",1854 * },{1855 * key: "age",1856 * value: "33",1857 * }],1858 * }]);1859 * @returns array of newly created tokens1860 */1861 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1862 const rawTokens = [];1863 for(const token of tokens) {1864 const raw = {NFT: {properties: token.properties}};1865 rawTokens.push(raw);1866 }1867 const creationResult = await this.helper.executeExtrinsic(1868 signer,1869 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1870 true,1871 );1872 const collection = this.getCollectionObject(collectionId);1873 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1874 }18751876 /**1877 * Set, change, or remove approved address to transfer the ownership of the NFT.1878 *1879 * @param signer keyring of signer1880 * @param collectionId ID of collection1881 * @param tokenId ID of token1882 * @param toAddressObj address to approve1883 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1884 * @returns ```true``` if extrinsic success, otherwise ```false```1885 */1886 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1887 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1888 }1889}189018911892class RFTGroup extends NFTnRFT {1893 /**1894 * Get collection object1895 * @param collectionId ID of collection1896 * @example getCollectionObject(2);1897 * @returns instance of UniqueRFTCollection1898 */1899 getCollectionObject(collectionId: number): UniqueRFTCollection {1900 return new UniqueRFTCollection(collectionId, this.helper);1901 }19021903 /**1904 * Get token object1905 * @param collectionId ID of collection1906 * @param tokenId ID of token1907 * @example getTokenObject(10, 5);1908 * @returns instance of UniqueNFTToken1909 */1910 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1911 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1912 }19131914 /**1915 * Get top 10 token owners with the largest number of pieces1916 * @param collectionId ID of collection1917 * @param tokenId ID of token1918 * @example getTokenTop10Owners(10, 5);1919 * @returns array of top 10 owners1920 */1921 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1922 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1923 }19241925 /**1926 * Get number of pieces owned by address1927 * @param collectionId ID of collection1928 * @param tokenId ID of token1929 * @param addressObj address token owner1930 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1931 * @returns number of pieces ownerd by address1932 */1933 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1934 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1935 }19361937 /**1938 * Transfer pieces of token to another address1939 * @param signer keyring of signer1940 * @param collectionId ID of collection1941 * @param tokenId ID of token1942 * @param addressObj address of a new owner1943 * @param amount number of pieces to be transfered1944 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1945 * @returns ```true``` if extrinsic success, otherwise ```false```1946 */1947 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1948 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1949 }19501951 /**1952 * Change ownership of some pieces of RFT on behalf of the owner.1953 * @param signer keyring of signer1954 * @param collectionId ID of collection1955 * @param tokenId ID of token1956 * @param fromAddressObj address on behalf of which the token will be sent1957 * @param toAddressObj new token owner1958 * @param amount number of pieces to be transfered1959 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1960 * @returns ```true``` if extrinsic success, otherwise ```false```1961 */1962 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1963 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1964 }19651966 /**1967 * Mint new collection1968 * @param signer keyring of signer1969 * @param collectionOptions Collection options1970 * @example1971 * mintCollection(aliceKeyring, {1972 * name: 'New',1973 * description: 'New collection',1974 * tokenPrefix: 'NEW',1975 * })1976 * @returns object of the created collection1977 */1978 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1979 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1980 }19811982 /**1983 * Mint new token1984 * @param signer keyring of signer1985 * @param data token data1986 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1987 * @returns created token object1988 */1989 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1990 const creationResult = await this.helper.executeExtrinsic(1991 signer,1992 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1993 ReFungible: {1994 pieces: data.pieces,1995 properties: data.properties,1996 },1997 }],1998 true,1999 );2000 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);2001 if(createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');2002 if(createdTokens.tokens.length < 1) throw Error('No tokens minted');2003 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);2004 }20052006 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {2007 throw Error('Not implemented');2008 const creationResult = await this.helper.executeExtrinsic(2009 signer,2010 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],2011 true, // `Unable to mint RFT tokens for ${label}`,2012 );2013 const collection = this.getCollectionObject(collectionId);2014 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2015 }20162017 /**2018 * Mint multiple RFT tokens with one owner2019 * @param signer keyring of signer2020 * @param collectionId ID of collection2021 * @param owner tokens owner2022 * @param tokens array of tokens with properties and pieces2023 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);2024 * @returns array of newly created RFT tokens2025 */2026 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {2027 const rawTokens = [];2028 for(const token of tokens) {2029 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};2030 rawTokens.push(raw);2031 }2032 const creationResult = await this.helper.executeExtrinsic(2033 signer,2034 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2035 true,2036 );2037 const collection = this.getCollectionObject(collectionId);2038 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2039 }20402041 /**2042 * Destroys a concrete instance of RFT.2043 * @param signer keyring of signer2044 * @param collectionId ID of collection2045 * @param tokenId ID of token2046 * @param amount number of pieces to be burnt2047 * @example burnToken(aliceKeyring, 10, 5);2048 * @returns ```true``` if the extrinsic is successful, otherwise ```false```2049 */2050 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {2051 return await super.burnToken(signer, collectionId, tokenId, amount);2052 }20532054 /**2055 * Destroys a concrete instance of RFT on behalf of the owner.2056 * @param signer keyring of signer2057 * @param collectionId ID of collection2058 * @param tokenId ID of token2059 * @param fromAddressObj address on behalf of which the token will be burnt2060 * @param amount number of pieces to be burnt2061 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)2062 * @returns ```true``` if extrinsic success, otherwise ```false```2063 */2064 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2065 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);2066 }20672068 /**2069 * Set, change, or remove approved address to transfer the ownership of the RFT.2070 *2071 * @param signer keyring of signer2072 * @param collectionId ID of collection2073 * @param tokenId ID of token2074 * @param toAddressObj address to approve2075 * @param amount number of pieces to be approved2076 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);2077 * @returns true if the token success, otherwise false2078 */2079 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {2080 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2081 }20822083 /**2084 * Get total number of pieces2085 * @param collectionId ID of collection2086 * @param tokenId ID of token2087 * @example getTokenTotalPieces(10, 5);2088 * @returns number of pieces2089 */2090 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2091 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2092 }20932094 /**2095 * Change number of token pieces. Signer must be the owner of all token pieces.2096 * @param signer keyring of signer2097 * @param collectionId ID of collection2098 * @param tokenId ID of token2099 * @param amount new number of pieces2100 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2101 * @returns true if the repartion was success, otherwise false2102 */2103 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2104 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2105 const repartitionResult = await this.helper.executeExtrinsic(2106 signer,2107 'api.tx.unique.repartition', [collectionId, tokenId, amount],2108 true,2109 );2110 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2111 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2112 }2113}211421152116class FTGroup extends CollectionGroup {2117 /**2118 * Get collection object2119 * @param collectionId ID of collection2120 * @example getCollectionObject(2);2121 * @returns instance of UniqueFTCollection2122 */2123 getCollectionObject(collectionId: number): UniqueFTCollection {2124 return new UniqueFTCollection(collectionId, this.helper);2125 }21262127 /**2128 * Mint new fungible collection2129 * @param signer keyring of signer2130 * @param collectionOptions Collection options2131 * @param decimalPoints number of token decimals2132 * @example2133 * mintCollection(aliceKeyring, {2134 * name: 'New',2135 * description: 'New collection',2136 * tokenPrefix: 'NEW',2137 * }, 18)2138 * @returns newly created fungible collection2139 */2140 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2141 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2142 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2143 collectionOptions.mode = {fungible: decimalPoints};2144 for(const key of ['name', 'description', 'tokenPrefix']) {2145 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);2146 }2147 const creationResult = await this.helper.executeExtrinsic(2148 signer,2149 'api.tx.unique.createCollectionEx', [collectionOptions],2150 true,2151 );2152 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2153 }21542155 /**2156 * Mint tokens2157 * @param signer keyring of signer2158 * @param collectionId ID of collection2159 * @param owner address owner of new tokens2160 * @param amount amount of tokens to be meanted2161 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2162 * @returns ```true``` if extrinsic success, otherwise ```false```2163 */2164 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2165 const creationResult = await this.helper.executeExtrinsic(2166 signer,2167 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2168 Fungible: {2169 value: amount,2170 },2171 }],2172 true, // `Unable to mint fungible tokens for ${label}`,2173 );2174 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2175 }21762177 /**2178 * Mint multiple Fungible tokens with one owner2179 * @param signer keyring of signer2180 * @param collectionId ID of collection2181 * @param owner tokens owner2182 * @param tokens array of tokens with properties and pieces2183 * @returns ```true``` if extrinsic success, otherwise ```false```2184 */2185 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: { value: bigint }[], owner: ICrossAccountId): Promise<boolean> {2186 const rawTokens = [];2187 for(const token of tokens) {2188 const raw = {Fungible: {Value: token.value}};2189 rawTokens.push(raw);2190 }2191 const creationResult = await this.helper.executeExtrinsic(2192 signer,2193 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2194 true,2195 );2196 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2197 }21982199 /**2200 * Get the top 10 owners with the largest balance for the Fungible collection2201 * @param collectionId ID of collection2202 * @example getTop10Owners(10);2203 * @returns array of ```ICrossAccountId```2204 */2205 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2206 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2207 }22082209 /**2210 * Get account balance2211 * @param collectionId ID of collection2212 * @param addressObj address of owner2213 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2214 * @returns amount of fungible tokens owned by address2215 */2216 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2217 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2218 }22192220 /**2221 * Transfer tokens to address2222 * @param signer keyring of signer2223 * @param collectionId ID of collection2224 * @param toAddressObj address recipient2225 * @param amount amount of tokens to be sent2226 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2227 * @returns ```true``` if extrinsic success, otherwise ```false```2228 */2229 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2230 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2231 }22322233 /**2234 * Transfer some tokens on behalf of the owner.2235 * @param signer keyring of signer2236 * @param collectionId ID of collection2237 * @param fromAddressObj address on behalf of which tokens will be sent2238 * @param toAddressObj address where token to be sent2239 * @param amount number of tokens to be sent2240 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2241 * @returns ```true``` if extrinsic success, otherwise ```false```2242 */2243 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {2244 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2245 }22462247 /**2248 * Destroy some amount of tokens2249 * @param signer keyring of signer2250 * @param collectionId ID of collection2251 * @param amount amount of tokens to be destroyed2252 * @example burnTokens(aliceKeyring, 10, 1000n);2253 * @returns ```true``` if extrinsic success, otherwise ```false```2254 */2255 async burnTokens(signer: IKeyringPair, collectionId: number, amount = 1n): Promise<boolean> {2256 return await super.burnToken(signer, collectionId, 0, amount);2257 }22582259 /**2260 * Burn some tokens on behalf of the owner.2261 * @param signer keyring of signer2262 * @param collectionId ID of collection2263 * @param fromAddressObj address on behalf of which tokens will be burnt2264 * @param amount amount of tokens to be burnt2265 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2266 * @returns ```true``` if extrinsic success, otherwise ```false```2267 */2268 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2269 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2270 }22712272 /**2273 * Get total collection supply2274 * @param collectionId2275 * @returns2276 */2277 async getTotalPieces(collectionId: number): Promise<bigint> {2278 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2279 }22802281 /**2282 * Set, change, or remove approved address to transfer tokens.2283 *2284 * @param signer keyring of signer2285 * @param collectionId ID of collection2286 * @param toAddressObj address to be approved2287 * @param amount amount of tokens to be approved2288 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2289 * @returns ```true``` if extrinsic success, otherwise ```false```2290 */2291 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2292 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2293 }22942295 /**2296 * Get amount of fungible tokens approved to transfer2297 * @param collectionId ID of collection2298 * @param fromAddressObj owner of tokens2299 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2300 * @returns number of tokens approved for the transfer2301 */2302 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2303 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2304 }2305}230623072308class ChainGroup extends HelperGroup<ChainHelperBase> {2309 /**2310 * Get system properties of a chain2311 * @example getChainProperties();2312 * @returns ss58Format, token decimals, and token symbol2313 */2314 getChainProperties(): IChainProperties {2315 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2316 return {2317 ss58Format: properties.ss58Format.toJSON(),2318 tokenDecimals: properties.tokenDecimals.toJSON(),2319 tokenSymbol: properties.tokenSymbol.toJSON(),2320 };2321 }23222323 /**2324 * Get chain header2325 * @example getLatestBlockNumber();2326 * @returns the number of the last block2327 */2328 async getLatestBlockNumber(): Promise<number> {2329 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2330 }23312332 /**2333 * Get block hash by block number2334 * @param blockNumber number of block2335 * @example getBlockHashByNumber(12345);2336 * @returns hash of a block2337 */2338 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2339 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2340 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2341 return blockHash;2342 }23432344 // TODO add docs2345 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2346 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2347 if(!blockHash) return null;2348 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2349 }23502351 /**2352 * Get latest relay block2353 * @returns {number} relay block2354 */2355 async getRelayBlockNumber(): Promise<bigint> {2356 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2357 return BigInt(blockNumber);2358 }23592360 /**2361 * Get account nonce2362 * @param address substrate address2363 * @example getNonce("5GrwvaEF5zXb26Fz...");2364 * @returns number, account's nonce2365 */2366 async getNonce(address: TSubstrateAccount): Promise<number> {2367 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2368 }2369}23702371export class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2372 /**2373 * Get substrate address balance2374 * @param address substrate address2375 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2376 * @returns amount of tokens on address2377 */2378 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2379 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2380 }23812382 /**2383 * Transfer tokens to substrate address2384 * @param signer keyring of signer2385 * @param address substrate address of a recipient2386 * @param amount amount of tokens to be transfered2387 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2388 * @returns ```true``` if extrinsic success, otherwise ```false```2389 */2390 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2391 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}`*/);23922393 let transfer = {from: null, to: null, amount: 0n} as any;2394 result.result.events.forEach(({event: {data, method, section}}) => {2395 if((section === 'balances') && (method === 'Transfer')) {2396 transfer = {2397 from: this.helper.address.normalizeSubstrate(data[0]),2398 to: this.helper.address.normalizeSubstrate(data[1]),2399 amount: BigInt(data[2]),2400 };2401 }2402 });2403 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2404 && this.helper.address.normalizeSubstrate(address) === transfer.to2405 && BigInt(amount) === transfer.amount;2406 return isSuccess;2407 }24082409 /**2410 * Get full substrate balance including free, frozen, and reserved2411 * @param address substrate address2412 * @returns2413 */2414 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2415 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2416 return {free: accountInfo.free.toBigInt(), frozen: accountInfo.frozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2417 }24182419 /**2420 * Get total issuance2421 * @returns2422 */2423 async getTotalIssuance(): Promise<bigint> {2424 const total = (await this.helper.callRpc('api.query.balances.totalIssuance', []));2425 return total.toBigInt();2426 }24272428 async getLocked(address: TSubstrateAccount): Promise<{ id: string, amount: bigint, reason: string }[]> {2429 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2430 return locks.map((lock: any) => ({id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}));2431 }2432 async getFrozen(address: TSubstrateAccount): Promise<{ id: string, amount: bigint }[]> {2433 const locks = (await this.helper.api!.query.balances.freezes(address)) as unknown as Array<any>;2434 return locks.map(lock => ({id: lock.id.toUtf8(), amount: lock.amount.toBigInt()}));2435 }2436}24372438export class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2439 /**2440 * Get ethereum address balance2441 * @param address ethereum address2442 * @example getEthereum("0x9F0583DbB855d...")2443 * @returns amount of tokens on address2444 */2445 async getEthereum(address: TEthereumAccount): Promise<bigint> {2446 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2447 }24482449 /**2450 * Transfer tokens to address2451 * @param signer keyring of signer2452 * @param address Ethereum address of a recipient2453 * @param amount amount of tokens to be transfered2454 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2455 * @returns ```true``` if extrinsic success, otherwise ```false```2456 */2457 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2458 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);24592460 let transfer = {from: null, to: null, amount: 0n} as any;2461 result.result.events.forEach(({event: {data, method, section}}) => {2462 if((section === 'balances') && (method === 'Transfer')) {2463 transfer = {2464 from: data[0].toString(),2465 to: data[1].toString(),2466 amount: BigInt(data[2]),2467 };2468 }2469 });2470 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2471 && address === transfer.to2472 && BigInt(amount) === transfer.amount;2473 return isSuccess;2474 }2475}24762477class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2478 subBalanceGroup: SubstrateBalanceGroup<T>;2479 ethBalanceGroup: EthereumBalanceGroup<T>;24802481 constructor(helper: T) {2482 super(helper);2483 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2484 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2485 }24862487 getCollectionCreationPrice(): bigint {2488 return 2n * this.getOneTokenNominal();2489 }2490 /**2491 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2492 * @example getOneTokenNominal()2493 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2494 */2495 getOneTokenNominal(): bigint {2496 const chainProperties = this.helper.chain.getChainProperties();2497 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2498 }24992500 /**2501 * Get substrate address balance2502 * @param address substrate address2503 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2504 * @returns amount of tokens on address2505 */2506 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2507 return this.subBalanceGroup.getSubstrate(address);2508 }25092510 /**2511 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2512 * @param address substrate address2513 * @returns2514 */2515 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2516 return this.subBalanceGroup.getSubstrateFull(address);2517 }25182519 /**2520 * Get total issuance2521 * @returns2522 */2523 getTotalIssuance(): Promise<bigint> {2524 return this.subBalanceGroup.getTotalIssuance();2525 }25262527 /**2528 * Get locked balances2529 * @param address substrate address2530 * @returns locked balances with reason via api.query.balances.locks2531 * @deprecated all the methods should switch to getFrozen2532 */2533 getLocked(address: TSubstrateAccount) {2534 return this.subBalanceGroup.getLocked(address);2535 }25362537 /**2538 * Get frozen balances2539 * @param address substrate address2540 * @returns frozen balances with id via api.query.balances.freezes2541 */2542 getFrozen(address: TSubstrateAccount) {2543 return this.subBalanceGroup.getFrozen(address);2544 }25452546 /**2547 * Get ethereum address balance2548 * @param address ethereum address2549 * @example getEthereum("0x9F0583DbB855d...")2550 * @returns amount of tokens on address2551 */2552 getEthereum(address: TEthereumAccount): Promise<bigint> {2553 return this.ethBalanceGroup.getEthereum(address);2554 }25552556 async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint) {2557 await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceSetBalance', [address, amount], true);2558 }25592560 /**2561 * Transfer tokens to substrate address2562 * @param signer keyring of signer2563 * @param address substrate address of a recipient2564 * @param amount amount of tokens to be transfered2565 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2566 * @returns ```true``` if extrinsic success, otherwise ```false```2567 */2568 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2569 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2570 }25712572 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2573 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);25742575 let transfer = {from: null, to: null, amount: 0n} as any;2576 result.result.events.forEach(({event: {data, method, section}}) => {2577 if((section === 'balances') && (method === 'Transfer')) {2578 transfer = {2579 from: this.helper.address.normalizeSubstrate(data[0]),2580 to: this.helper.address.normalizeSubstrate(data[1]),2581 amount: BigInt(data[2]),2582 };2583 }2584 });2585 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2586 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2587 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2588 return isSuccess;2589 }25902591 /**2592 * Transfer tokens with the unlock period2593 * @param signer signers Keyring2594 * @param address Substrate address of recipient2595 * @param schedule Schedule params2596 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002597 */2598 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: { start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }): Promise<void> {2599 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2600 const event = result.result.events2601 .find(e => e.event.section === 'vesting' &&2602 e.event.method === 'VestingScheduleAdded' &&2603 e.event.data[0].toHuman() === signer.address);2604 if(!event) throw Error('Cannot find transfer in events');2605 }26062607 /**2608 * Get schedule for recepient of vested transfer2609 * @param address Substrate address of recipient2610 * @returns2611 */2612 async getVestingSchedules(address: TSubstrateAccount): Promise<{ start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }[]> {2613 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2614 return schedule.map((schedule: any) => ({2615 start: BigInt(schedule.start),2616 period: BigInt(schedule.period),2617 periodCount: BigInt(schedule.periodCount),2618 perPeriod: BigInt(schedule.perPeriod),2619 }));2620 }26212622 /**2623 * Claim vested tokens2624 * @param signer signers Keyring2625 */2626 async claim(signer: TSigner) {2627 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2628 const event = result.result.events2629 .find(e => e.event.section === 'vesting' &&2630 e.event.method === 'Claimed' &&2631 e.event.data[0].toHuman() === signer.address);2632 if(!event) throw Error('Cannot find claim in events');2633 }2634}26352636class AddressGroup extends HelperGroup<ChainHelperBase> {2637 /**2638 * Normalizes the address to the specified ss58 format, by default ```42```.2639 * @param address substrate address2640 * @param ss58Format format for address conversion, by default ```42```2641 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2642 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2643 */2644 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2645 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2646 }26472648 /**2649 * Get address in the connected chain format2650 * @param address substrate address2651 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2652 * @returns address in chain format2653 */2654 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2655 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2656 }26572658 /**2659 * Get substrate mirror of an ethereum address2660 * @param ethAddress ethereum address2661 * @param toChainFormat false for normalized account2662 * @example ethToSubstrate('0x9F0583DbB855d...')2663 * @returns substrate mirror of a provided ethereum address2664 */2665 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat = false): TSubstrateAccount {2666 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2667 }26682669 /**2670 * Get ethereum mirror of a substrate address2671 * @param subAddress substrate account2672 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2673 * @returns ethereum mirror of a provided substrate address2674 */2675 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2676 return CrossAccountId.translateSubToEth(subAddress);2677 }26782679 /**2680 * Encode key to substrate address2681 * @param key key for encoding address2682 * @param ss58Format prefix for encoding to the address of the corresponding network2683 * @returns encoded substrate address2684 */2685 encodeSubstrateAddress(key: Uint8Array | string | bigint, ss58Format = 42): string {2686 const u8a: Uint8Array = typeof key === 'string'2687 ? hexToU8a(key)2688 : typeof key === 'bigint'2689 ? hexToU8a(key.toString(16))2690 : key;26912692 if(ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2693 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2694 }26952696 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2697 if(!allowedDecodedLengths.includes(u8a.length)) {2698 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2699 }27002701 const u8aPrefix = ss58Format < 642702 ? new Uint8Array([ss58Format])2703 : new Uint8Array([2704 ((ss58Format & 0xfc) >> 2) | 0x40,2705 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2706 ]);27072708 const input = u8aConcat(u8aPrefix, u8a);27092710 return base58Encode(u8aConcat(2711 input,2712 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2713 ));2714 }27152716 /**2717 * Restore substrate address from bigint representation2718 * @param number decimal representation of substrate address2719 * @returns substrate address2720 */2721 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2722 if(this.helper.api === null) {2723 throw 'Not connected';2724 }2725 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2726 if(res === undefined || res === null) {2727 throw 'Restore address error';2728 }2729 return res.toString();2730 }27312732 /**2733 * Convert etherium cross account id to substrate cross account id2734 * @param ethCrossAccount etherium cross account2735 * @returns substrate cross account id2736 */2737 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2738 if(ethCrossAccount.sub === '0') {2739 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2740 }27412742 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2743 return {Substrate: ss58};2744 }27452746 paraSiblingSovereignAccount(paraid: number) {2747 // We are getting a *sibling* parachain sovereign account,2748 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2749 const siblingPrefix = '0x7369626c';27502751 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2752 const suffix = '000000000000000000000000000000000000000000000000';27532754 return siblingPrefix + encodedParaId + suffix;2755 }2756}275727582759class StakingGroup extends HelperGroup<UniqueHelper> {2760 /**2761 * Stake tokens for App Promotion2762 * @param signer keyring of signer2763 * @param amountToStake amount of tokens to stake2764 * @param label extra label for log2765 * @returns2766 */2767 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2768 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2769 const _stakeResult = await this.helper.executeExtrinsic(2770 signer, 'api.tx.appPromotion.stake',2771 [amountToStake], true,2772 );2773 // TODO extract info from stakeResult2774 return true;2775 }27762777 /**2778 * Unstake all staked tokens2779 * @param signer keyring of signer2780 * @param amountToUnstake amount of tokens to unstake2781 * @param label extra label for log2782 * @returns block hash where unstake happened2783 */2784 async unstakeAll(signer: TSigner, label?: string): Promise<string> {2785 if(typeof label === 'undefined') label = `${signer.address}`;2786 const unstakeResult = await this.helper.executeExtrinsic(2787 signer, 'api.tx.appPromotion.unstakeAll',2788 [], true,2789 );2790 return unstakeResult.blockHash;2791 }27922793 /**2794 * Unstake the part of a staked tokens2795 * @param signer keyring of signer2796 * @param amount amount of tokens to unstake2797 * @param label extra label for log2798 * @returns block hash where unstake happened2799 */2800 async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2801 if(typeof label === 'undefined') label = `${signer.address}`;2802 const unstakeResult = await this.helper.executeExtrinsic(2803 signer, 'api.tx.appPromotion.unstakePartial',2804 [amount], true,2805 );2806 return unstakeResult.blockHash;2807 }28082809 /**2810 * Get total number of active stakes2811 * @param address substrate address2812 * @returns {number}2813 */2814 async getStakesNumber(address: ICrossAccountId): Promise<number> {2815 if('Ethereum' in address) throw Error('only substrate address');2816 return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2817 }28182819 /**2820 * Get total staked amount for address2821 * @param address substrate or ethereum address2822 * @returns total staked amount2823 */2824 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2825 if(address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2826 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2827 }28282829 /**2830 * Get total staked per block2831 * @param address substrate or ethereum address2832 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2833 */2834 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2835 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2836 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => ({2837 block: block.toBigInt(),2838 amount: amount.toBigInt(),2839 }));2840 }28412842 /**2843 * Get total pending unstake amount for address2844 * @param address substrate or ethereum address2845 * @returns total pending unstake amount2846 */2847 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2848 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2849 }28502851 /**2852 * Get pending unstake amount per block for address2853 * @param address substrate or ethereum address2854 * @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 block2855 */2856 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2857 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2858 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => ({2859 block: block.toBigInt(),2860 amount: amount.toBigInt(),2861 }));2862 return result;2863 }2864}286528662867class PreimageGroup extends HelperGroup<UniqueHelper> {2868 async getPreimageInfo(h256: string) {2869 return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();2870 }28712872 /**2873 * Create a preimage from an API call.2874 * @param signer keyring of the signer.2875 * @param call an extrinsic call2876 * @example await notePreimageFromCall(preimageMaker,2877 * helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd])2878 * );2879 * @returns promise of extrinsic execution.2880 */2881 notePreimageFromCall(signer: TSigner, call: any, returnPreimageHash = false) {2882 return this.notePreimage(signer, call.method.toHex(), returnPreimageHash);2883 }28842885 /**2886 * Create a preimage with a hex or a byte array.2887 * @param signer keyring of the signer.2888 * @param bytes preimage encoded in hex or a byte array, e.g. an extrinsic call.2889 * @example await notePreimage(preimageMaker,2890 * helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex()2891 * );2892 * @returns promise of extrinsic execution.2893 */2894 async notePreimage(signer: TSigner, bytes: string | Uint8Array, returnPreimageHash = false) {2895 const promise = this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);2896 if(returnPreimageHash) {2897 const result = await promise;2898 const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');2899 const preimageHash = events[0].event.data[0].toHuman();2900 return preimageHash;2901 }2902 return promise;2903 }29042905 /**2906 * Delete an existing preimage and return the deposit.2907 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2908 * @param h256 hash of the preimage.2909 * @returns promise of extrinsic execution.2910 */2911 unnotePreimage(signer: TSigner, h256: string) {2912 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);2913 }29142915 /**2916 * Request a preimage be uploaded to the chain without paying any fees or deposits.2917 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2918 * @param h256 hash of the preimage.2919 * @returns promise of extrinsic execution.2920 */2921 requestPreimage(signer: TSigner, h256: string) {2922 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);2923 }29242925 /**2926 * Clear a previously made request for a preimage.2927 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2928 * @param h256 hash of the preimage.2929 * @returns promise of extrinsic execution.2930 */2931 unrequestPreimage(signer: TSigner, h256: string) {2932 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);2933 }2934}29352936class UtilityGroup<T extends ChainHelperBase> extends HelperGroup<T> {2937 async batch(signer: TSigner, txs: any[]) {2938 return await this.helper.executeExtrinsic(signer, 'api.tx.utility.batch', [txs]);2939 }29402941 async batchAll(signer: TSigner, txs: any[]) {2942 return await this.helper.executeExtrinsic(signer, 'api.tx.utility.batchAll', [txs]);2943 }29442945 batchAllCall(txs: any[]) {2946 return this.helper.constructApiCall('api.tx.utility.batchAll', [txs]);2947 }2948}29492950export type ChainHelperBaseConstructor = new (...args: any[]) => ChainHelperBase;2951export type UniqueHelperConstructor = new (...args: any[]) => UniqueHelper;29522953export class UniqueHelper extends ChainHelperBase {2954 balance: BalanceGroup<UniqueHelper>;2955 collection: CollectionGroup;2956 nft: NFTGroup;2957 rft: RFTGroup;2958 ft: FTGroup;2959 staking: StakingGroup;2960 preimage: PreimageGroup;2961 utility: UtilityGroup<UniqueHelper>;29622963 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {2964 super(logger, options.helperBase ?? UniqueHelper);29652966 this.balance = new BalanceGroup(this);2967 this.collection = new CollectionGroup(this);2968 this.nft = new NFTGroup(this);2969 this.rft = new RFTGroup(this);2970 this.ft = new FTGroup(this);2971 this.staking = new StakingGroup(this);2972 this.preimage = new PreimageGroup(this);2973 this.utility = new UtilityGroup(this);2974 }2975}29762977export class UniqueBaseCollection {2978 helper: UniqueHelper;2979 collectionId: number;29802981 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2982 this.collectionId = collectionId;2983 this.helper = uniqueHelper;2984 }29852986 async getData() {2987 return await this.helper.collection.getData(this.collectionId);2988 }29892990 async getLastTokenId() {2991 return await this.helper.collection.getLastTokenId(this.collectionId);2992 }29932994 async doesTokenExist(tokenId: number) {2995 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2996 }29972998 async getAdmins() {2999 return await this.helper.collection.getAdmins(this.collectionId);3000 }30013002 async getAllowList() {3003 return await this.helper.collection.getAllowList(this.collectionId);3004 }30053006 async getEffectiveLimits() {3007 return await this.helper.collection.getEffectiveLimits(this.collectionId);3008 }30093010 async getProperties(propertyKeys?: string[] | null) {3011 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3012 }30133014 async getPropertiesConsumedSpace() {3015 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3016 }30173018 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3019 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3020 }30213022 async getOptions() {3023 return await this.helper.collection.getCollectionOptions(this.collectionId);3024 }30253026 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3027 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3028 }30293030 async confirmSponsorship(signer: TSigner) {3031 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3032 }30333034 async removeSponsor(signer: TSigner) {3035 return await this.helper.collection.removeSponsor(signer, this.collectionId);3036 }30373038 async setLimits(signer: TSigner, limits: ICollectionLimits) {3039 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3040 }30413042 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3043 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3044 }30453046 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3047 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3048 }30493050 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3051 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3052 }30533054 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3055 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3056 }30573058 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3059 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3060 }30613062 async setProperties(signer: TSigner, properties: IProperty[]) {3063 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3064 }30653066 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3067 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3068 }30693070 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3071 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3072 }30733074 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3075 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3076 }30773078 async disableNesting(signer: TSigner) {3079 return await this.helper.collection.disableNesting(signer, this.collectionId);3080 }30813082 async burn(signer: TSigner) {3083 return await this.helper.collection.burn(signer, this.collectionId);3084 }3085}30863087export class UniqueNFTCollection extends UniqueBaseCollection {3088 getTokenObject(tokenId: number) {3089 return new UniqueNFToken(tokenId, this);3090 }30913092 async getTokensByAddress(addressObj: ICrossAccountId) {3093 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3094 }30953096 async getToken(tokenId: number, blockHashAt?: string) {3097 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3098 }30993100 async getTokenOwner(tokenId: number, blockHashAt?: string) {3101 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3102 }31033104 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3105 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3106 }31073108 async getTokenChildren(tokenId: number, blockHashAt?: string) {3109 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3110 }31113112 async getPropertyPermissions(propertyKeys: string[] | null = null) {3113 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3114 }31153116 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3117 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3118 }31193120 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3121 const api = this.helper.getApi();3122 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();31233124 return (props! as any).consumedSpace;3125 }31263127 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3128 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3129 }31303131 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3132 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3133 }31343135 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3136 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3137 }31383139 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3140 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3141 }31423143 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3144 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3145 }31463147 async mintMultipleTokens(signer: TSigner, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]) {3148 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3149 }31503151 async burnToken(signer: TSigner, tokenId: number) {3152 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3153 }31543155 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3156 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3157 }31583159 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3160 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3161 }31623163 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3164 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3165 }31663167 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3168 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3169 }31703171 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3172 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3173 }31743175 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3176 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3177 }3178}31793180export class UniqueRFTCollection extends UniqueBaseCollection {3181 getTokenObject(tokenId: number) {3182 return new UniqueRFToken(tokenId, this);3183 }31843185 async getToken(tokenId: number, blockHashAt?: string) {3186 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3187 }31883189 async getTokenOwner(tokenId: number, blockHashAt?: string) {3190 return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3191 }31923193 async getTokensByAddress(addressObj: ICrossAccountId) {3194 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3195 }31963197 async getTop10TokenOwners(tokenId: number) {3198 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3199 }32003201 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3202 return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3203 }32043205 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3206 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3207 }32083209 async getTokenTotalPieces(tokenId: number) {3210 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3211 }32123213 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3214 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3215 }32163217 async getPropertyPermissions(propertyKeys: string[] | null = null) {3218 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3219 }32203221 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3222 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3223 }32243225 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3226 const api = this.helper.getApi();3227 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();32283229 return (props! as any).consumedSpace;3230 }32313232 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount = 1n) {3233 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3234 }32353236 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3237 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3238 }32393240 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {3241 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3242 }32433244 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3245 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3246 }32473248 async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3249 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3250 }32513252 async mintMultipleTokens(signer: TSigner, tokens: { pieces: bigint, owner: ICrossAccountId, properties?: IProperty[] }[]) {3253 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3254 }32553256 async burnToken(signer: TSigner, tokenId: number, amount = 1n) {3257 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3258 }32593260 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n) {3261 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3262 }32633264 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3265 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3266 }32673268 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3269 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3270 }32713272 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3273 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3274 }32753276 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3277 return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3278 }32793280 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3281 return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3282 }3283}32843285export class UniqueFTCollection extends UniqueBaseCollection {3286 async getBalance(addressObj: ICrossAccountId) {3287 return await this.helper.ft.getBalance(this.collectionId, addressObj);3288 }32893290 async getTotalPieces() {3291 return await this.helper.ft.getTotalPieces(this.collectionId);3292 }32933294 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3295 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3296 }32973298 async getTop10Owners() {3299 return await this.helper.ft.getTop10Owners(this.collectionId);3300 }33013302 async mint(signer: TSigner, amount = 1n, owner: ICrossAccountId = {Substrate: signer.address}) {3303 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3304 }33053306 async mintWithOneOwner(signer: TSigner, tokens: { value: bigint }[], owner: ICrossAccountId = {Substrate: signer.address}) {3307 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3308 }33093310 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3311 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3312 }33133314 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3315 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3316 }33173318 async burnTokens(signer: TSigner, amount = 1n) {3319 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3320 }33213322 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {3323 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3324 }33253326 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3327 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3328 }3329}33303331export class UniqueBaseToken {3332 collection: UniqueNFTCollection | UniqueRFTCollection;3333 collectionId: number;3334 tokenId: number;33353336 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3337 this.collection = collection;3338 this.collectionId = collection.collectionId;3339 this.tokenId = tokenId;3340 }33413342 async getNextSponsored(addressObj: ICrossAccountId) {3343 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3344 }33453346 async getProperties(propertyKeys?: string[] | null) {3347 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3348 }33493350 async getTokenPropertiesConsumedSpace() {3351 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3352 }33533354 async setProperties(signer: TSigner, properties: IProperty[]) {3355 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3356 }33573358 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3359 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3360 }33613362 async doesExist() {3363 return await this.collection.doesTokenExist(this.tokenId);3364 }33653366 nestingAccount() {3367 return this.collection.helper.util.getTokenAccount(this);3368 }3369}33703371export class UniqueNFToken extends UniqueBaseToken {3372 collection: UniqueNFTCollection;33733374 constructor(tokenId: number, collection: UniqueNFTCollection) {3375 super(tokenId, collection);3376 this.collection = collection;3377 }33783379 async getData(blockHashAt?: string) {3380 return await this.collection.getToken(this.tokenId, blockHashAt);3381 }33823383 async getOwner(blockHashAt?: string) {3384 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3385 }33863387 async getTopmostOwner(blockHashAt?: string) {3388 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3389 }33903391 async getChildren(blockHashAt?: string) {3392 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3393 }33943395 async nest(signer: TSigner, toTokenObj: IToken) {3396 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3397 }33983399 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3400 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3401 }34023403 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3404 return await this.collection.transferToken(signer, this.tokenId, addressObj);3405 }34063407 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3408 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3409 }34103411 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3412 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3413 }34143415 async isApproved(toAddressObj: ICrossAccountId) {3416 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3417 }34183419 async burn(signer: TSigner) {3420 return await this.collection.burnToken(signer, this.tokenId);3421 }34223423 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3424 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3425 }3426}34273428export class UniqueRFToken extends UniqueBaseToken {3429 collection: UniqueRFTCollection;34303431 constructor(tokenId: number, collection: UniqueRFTCollection) {3432 super(tokenId, collection);3433 this.collection = collection;3434 }34353436 async getData(blockHashAt?: string) {3437 return await this.collection.getToken(this.tokenId, blockHashAt);3438 }34393440 async getOwner(blockHashAt?: string) {3441 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3442 }34433444 async getTop10Owners() {3445 return await this.collection.getTop10TokenOwners(this.tokenId);3446 }34473448 async getTopmostOwner(blockHashAt?: string) {3449 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3450 }34513452 async nest(signer: TSigner, toTokenObj: IToken) {3453 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3454 }34553456 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3457 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3458 }34593460 async getBalance(addressObj: ICrossAccountId) {3461 return await this.collection.getTokenBalance(this.tokenId, addressObj);3462 }34633464 async getTotalPieces() {3465 return await this.collection.getTokenTotalPieces(this.tokenId);3466 }34673468 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3469 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3470 }34713472 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount = 1n) {3473 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3474 }34753476 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3477 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3478 }34793480 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3481 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3482 }34833484 async repartition(signer: TSigner, amount: bigint) {3485 return await this.collection.repartitionToken(signer, this.tokenId, amount);3486 }34873488 async burn(signer: TSigner, amount = 1n) {3489 return await this.collection.burnToken(signer, this.tokenId, amount);3490 }34913492 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {3493 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3494 }3495}tests/src/util/playgrounds/unique.xcm.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/util/playgrounds/unique.xcm.ts
@@ -0,0 +1,371 @@
+import {ApiPromise, WsProvider} from '@polkadot/api';
+import {IKeyringPair} from '@polkadot/types/types';
+import {ChainHelperBase, EthereumBalanceGroup, HelperGroup, SubstrateBalanceGroup, UniqueHelper} from './unique';
+import {ILogger, TSigner, TSubstrateAccount} from './types';
+import {AcalaAssetMetadata, DemocracyStandardAccountVote, IForeignAssetMetadata, MoonbeamAssetInfo} from './types.xcm';
+
+
+export class XcmChainHelper extends ChainHelperBase {
+ async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
+ const wsProvider = new WsProvider(wsEndpoint);
+ this.api = new ApiPromise({
+ provider: wsProvider,
+ });
+ await this.api.isReadyOrError;
+ this.network = await UniqueHelper.detectNetwork(this.api);
+ }
+}
+
+class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {
+ async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);
+ }
+}
+
+class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {
+ makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {
+ const apiPrefix = 'api.tx.assetManager.';
+
+ const registerTx = this.helper.constructApiCall(
+ apiPrefix + 'registerForeignAsset',
+ [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],
+ );
+
+ const setUnitsTx = this.helper.constructApiCall(
+ apiPrefix + 'setAssetUnitsPerSecond',
+ [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],
+ );
+
+ const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);
+ const encodedProposal = batchCall?.method.toHex() || '';
+ return encodedProposal;
+ }
+
+ async assetTypeId(location: any) {
+ return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);
+ }
+}
+
+class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {
+ notePreimagePallet: string;
+
+ constructor(helper: MoonbeamHelper, options: { [key: string]: any } = {}) {
+ super(helper);
+ this.notePreimagePallet = options.notePreimagePallet;
+ }
+
+ async notePreimage(signer: TSigner, encodedProposal: string) {
+ await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);
+ }
+
+ externalProposeMajority(proposal: any) {
+ return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);
+ }
+
+ fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {
+ return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);
+ }
+
+ async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);
+ }
+}
+
+class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {
+ collective: string;
+
+ constructor(helper: MoonbeamHelper, collective: string) {
+ super(helper);
+
+ this.collective = collective;
+ }
+
+ async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {
+ await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);
+ }
+
+ async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {
+ await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);
+ }
+
+ async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {
+ await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);
+ }
+
+ async proposalCount() {
+ return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));
+ }
+}
+
+class PolkadexXcmHelperGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ async whitelistToken(signer: TSigner, assetId: any) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.xcmHelper.whitelistToken', [assetId], true);
+ }
+}
+
+export class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {
+ async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {
+ await this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.foreignAssets.registerForeignAsset',
+ [ownerAddress, location, metadata],
+ true,
+ );
+ }
+
+ async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {
+ await this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.foreignAssets.updateForeignAsset',
+ [foreignAssetId, location, metadata],
+ true,
+ );
+ }
+}
+
+export class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ palletName: string;
+
+ constructor(helper: T, palletName: string) {
+ super(helper);
+
+ this.palletName = palletName;
+ }
+
+ async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {
+ await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);
+ }
+
+ async setSafeXcmVersion(signer: TSigner, version: number) {
+ await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);
+ }
+
+ async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {
+ await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);
+ }
+
+ async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {
+ const destinationContent = {
+ parents: 0,
+ interior: {
+ X1: {
+ Parachain: destinationParaId,
+ },
+ },
+ };
+
+ const beneficiaryContent = {
+ parents: 0,
+ interior: {
+ X1: {
+ AccountId32: {
+ network: 'Any',
+ id: targetAccount,
+ },
+ },
+ },
+ };
+
+ const assetsContent = [
+ {
+ id: {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ fun: {
+ Fungible: amount,
+ },
+ },
+ ];
+
+ let destination;
+ let beneficiary;
+ let assets;
+
+ if(xcmVersion == 2) {
+ destination = {V1: destinationContent};
+ beneficiary = {V1: beneficiaryContent};
+ assets = {V1: assetsContent};
+
+ } else if(xcmVersion == 3) {
+ destination = {V2: destinationContent};
+ beneficiary = {V2: beneficiaryContent};
+ assets = {V2: assetsContent};
+
+ } else {
+ throw Error('Unknown XCM version: ' + xcmVersion);
+ }
+
+ const feeAssetItem = 0;
+
+ await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);
+ }
+
+ async send(signer: IKeyringPair, destination: any, message: any) {
+ await this.helper.executeExtrinsic(
+ signer,
+ `api.tx.${this.palletName}.send`,
+ [
+ destination,
+ message,
+ ],
+ true,
+ );
+ }
+}
+
+export class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);
+ }
+
+ async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);
+ }
+
+ async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);
+ }
+}
+
+
+
+export class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ async accounts(address: string, currencyId: any) {
+ const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;
+ return BigInt(free);
+ }
+}
+
+export class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);
+ }
+
+ async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);
+ }
+
+ async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);
+ }
+
+ async account(assetId: string | number, address: string) {
+ const accountAsset = (
+ await this.helper.callRpc('api.query.assets.account', [assetId, address])
+ ).toJSON()! as any;
+
+ if(accountAsset !== null) {
+ return BigInt(accountAsset['balance']);
+ } else {
+ return null;
+ }
+ }
+}
+
+export class RelayHelper extends XcmChainHelper {
+ balance: SubstrateBalanceGroup<RelayHelper>;
+ xcm: XcmGroup<RelayHelper>;
+
+ constructor(logger?: ILogger, options: { [key: string]: any } = {}) {
+ super(logger, options.helperBase ?? RelayHelper);
+
+ this.balance = new SubstrateBalanceGroup(this);
+ this.xcm = new XcmGroup(this, 'xcmPallet');
+ }
+}
+
+export class WestmintHelper extends XcmChainHelper {
+ balance: SubstrateBalanceGroup<WestmintHelper>;
+ xcm: XcmGroup<WestmintHelper>;
+ assets: AssetsGroup<WestmintHelper>;
+ xTokens: XTokensGroup<WestmintHelper>;
+
+ constructor(logger?: ILogger, options: { [key: string]: any } = {}) {
+ super(logger, options.helperBase ?? WestmintHelper);
+
+ this.balance = new SubstrateBalanceGroup(this);
+ this.xcm = new XcmGroup(this, 'polkadotXcm');
+ this.assets = new AssetsGroup(this);
+ this.xTokens = new XTokensGroup(this);
+ }
+}
+
+export class MoonbeamHelper extends XcmChainHelper {
+ balance: EthereumBalanceGroup<MoonbeamHelper>;
+ assetManager: MoonbeamAssetManagerGroup;
+ assets: AssetsGroup<MoonbeamHelper>;
+ xTokens: XTokensGroup<MoonbeamHelper>;
+ democracy: MoonbeamDemocracyGroup;
+ collective: {
+ council: MoonbeamCollectiveGroup,
+ techCommittee: MoonbeamCollectiveGroup,
+ };
+
+ constructor(logger?: ILogger, options: { [key: string]: any } = {}) {
+ super(logger, options.helperBase ?? MoonbeamHelper);
+
+ this.balance = new EthereumBalanceGroup(this);
+ this.assetManager = new MoonbeamAssetManagerGroup(this);
+ this.assets = new AssetsGroup(this);
+ this.xTokens = new XTokensGroup(this);
+ this.democracy = new MoonbeamDemocracyGroup(this, options);
+ this.collective = {
+ council: new MoonbeamCollectiveGroup(this, 'councilCollective'),
+ techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),
+ };
+ }
+}
+
+export class AstarHelper extends XcmChainHelper {
+ balance: SubstrateBalanceGroup<AstarHelper>;
+ assets: AssetsGroup<AstarHelper>;
+ xcm: XcmGroup<AstarHelper>;
+
+ constructor(logger?: ILogger, options: { [key: string]: any } = {}) {
+ super(logger, options.helperBase ?? AstarHelper);
+
+ this.balance = new SubstrateBalanceGroup(this);
+ this.assets = new AssetsGroup(this);
+ this.xcm = new XcmGroup(this, 'polkadotXcm');
+ }
+}
+
+export class AcalaHelper extends XcmChainHelper {
+ balance: SubstrateBalanceGroup<AcalaHelper>;
+ assetRegistry: AcalaAssetRegistryGroup;
+ xTokens: XTokensGroup<AcalaHelper>;
+ tokens: TokensGroup<AcalaHelper>;
+ xcm: XcmGroup<AcalaHelper>;
+
+ constructor(logger?: ILogger, options: { [key: string]: any } = {}) {
+ super(logger, options.helperBase ?? AcalaHelper);
+
+ this.balance = new SubstrateBalanceGroup(this);
+ this.assetRegistry = new AcalaAssetRegistryGroup(this);
+ this.xTokens = new XTokensGroup(this);
+ this.tokens = new TokensGroup(this);
+ this.xcm = new XcmGroup(this, 'polkadotXcm');
+ }
+}
+
+export class PolkadexHelper extends XcmChainHelper {
+ assets: AssetsGroup<PolkadexHelper>;
+ balance: SubstrateBalanceGroup<PolkadexHelper>;
+ xTokens: XTokensGroup<PolkadexHelper>;
+ xcm: XcmGroup<PolkadexHelper>;
+ xcmHelper: PolkadexXcmHelperGroup<PolkadexHelper>;
+
+ constructor(logger?: ILogger, options: { [key: string]: any } = {}) {
+ super(logger, options.helperBase ?? PolkadexHelper);
+
+ this.assets = new AssetsGroup(this);
+ this.balance = new SubstrateBalanceGroup(this);
+ this.xTokens = new XTokensGroup(this);
+ this.xcm = new XcmGroup(this, 'polkadotXcm');
+ this.xcmHelper = new PolkadexXcmHelperGroup(this);
+ }
+}
+