difftreelog
Merge pull request #639 from UniqueNetwork/feature/playgrounds-nested-ops
in: master
Feature/playgrounds nested ops
5 files changed
tests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/index.ts
+++ b/tests/src/eth/util/playgrounds/index.ts
@@ -39,7 +39,6 @@
}
finally {
await helper.disconnect();
- await helper.disconnectWeb3();
silentConsole.disable();
}
};
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -321,6 +321,7 @@
}
}
+export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;
export class EthUniqueHelper extends DevUniqueHelper {
web3: Web3 | null = null;
@@ -331,8 +332,10 @@
ethNativeContract: NativeContractGroup;
ethContract: ContractGroup;
- constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
- super(logger);
+ constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
+ options.helperBase = options.helperBase ?? EthUniqueHelper;
+
+ super(logger, options);
this.eth = new EthGroup(this);
this.ethAddress = new EthAddressGroup(this);
this.ethNativeContract = new NativeContractGroup(this);
@@ -350,10 +353,23 @@
this.web3 = new Web3(this.web3Provider);
}
- async disconnectWeb3() {
+ async disconnect() {
if(this.web3 === null) return;
this.web3Provider?.connection.close();
+
+ await super.disconnect();
+ }
+
+ clearApi() {
this.web3 = null;
}
+
+ clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {
+ const newHelper = super.clone(helperCls, options) as EthUniqueHelper;
+ newHelper.web3 = this.web3;
+ newHelper.web3Provider = this.web3Provider;
+
+ return newHelper;
+ }
}
\ No newline at end of file
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -14,6 +14,7 @@
export interface ITransactionResult {
status: 'Fail' | 'Success';
result: {
+ dispatchError: any,
events: {
phase: any, // {ApplyExtrinsic: number} | 'Initialization',
event: IEvent;
@@ -47,6 +48,7 @@
call: string;
params: any[];
moduleError?: string;
+ dispatchError?: any;
events?: any;
}
@@ -162,6 +164,14 @@
amount: bigint,
}
+export interface ISchedulerOptions {
+ priority?: number,
+ periodic?: {
+ period: number,
+ repetitions: number,
+ },
+}
+
export type TSubstrateAccount = string;
export type TEthereumAccount = string;
export type TApiAllowedListeners = 'connected' | 'disconnected' | 'error' | 'ready' | 'decorated';
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {mnemonicGenerate} from '@polkadot/util-crypto';5import {UniqueHelper} from './unique';6import {ApiPromise, WsProvider} from '@polkadot/api';7import * as defs from '../../interfaces/definitions';8import {IKeyringPair} from '@polkadot/types/types';9import {ICrossAccountId} from './types';101112export class SilentLogger {13 log(_msg: any, _level: any): void { }14 level = {15 ERROR: 'ERROR' as const,16 WARNING: 'WARNING' as const,17 INFO: 'INFO' as const,18 };19}2021export class SilentConsole {22 // TODO: Remove, this is temporary: Filter unneeded API output23 // (Jaco promised it will be removed in the next version)24 consoleErr: any;25 consoleLog: any;26 consoleWarn: any;2728 constructor() {29 this.consoleErr = console.error;30 this.consoleLog = console.log;31 this.consoleWarn = console.warn;32 }3334 enable() { 35 const outFn = (printer: any) => (...args: any[]) => {36 for (const arg of args) {37 if (typeof arg !== 'string')38 continue;39 if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')40 return;41 }42 printer(...args);43 };44 45 console.error = outFn(this.consoleErr.bind(console));46 console.log = outFn(this.consoleLog.bind(console));47 console.warn = outFn(this.consoleWarn.bind(console));48 }4950 disable() {51 console.error = this.consoleErr;52 console.log = this.consoleLog;53 console.warn = this.consoleWarn;54 }55}565758export class DevUniqueHelper extends UniqueHelper {59 /**60 * Arrange methods for tests61 */62 arrange: ArrangeGroup;63 wait: WaitGroup;64 admin: AdminGroup;6566 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {67 super(logger);68 this.arrange = new ArrangeGroup(this);69 this.wait = new WaitGroup(this);70 this.admin = new AdminGroup(this);71 }7273 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {74 const wsProvider = new WsProvider(wsEndpoint);75 this.api = new ApiPromise({76 provider: wsProvider,77 signedExtensions: {78 ContractHelpers: {79 extrinsic: {},80 payload: {},81 },82 FakeTransactionFinalizer: {83 extrinsic: {},84 payload: {},85 },86 },87 rpc: {88 unique: defs.unique.rpc,89 appPromotion: defs.appPromotion.rpc,90 rmrk: defs.rmrk.rpc,91 eth: {92 feeHistory: {93 description: 'Dummy',94 params: [],95 type: 'u8',96 },97 maxPriorityFeePerGas: {98 description: 'Dummy',99 params: [],100 type: 'u8',101 },102 },103 },104 });105 await this.api.isReadyOrError;106 this.network = await UniqueHelper.detectNetwork(this.api);107 }108}109110class ArrangeGroup {111 helper: UniqueHelper;112113 constructor(helper: UniqueHelper) {114 this.helper = helper;115 }116117 /**118 * Generates accounts with the specified UNQ token balance 119 * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.120 * @param donor donor account for balances121 * @returns array of newly created accounts122 * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 123 */124 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {125 let nonce = await this.helper.chain.getNonce(donor.address);126 const wait = new WaitGroup(this.helper);127 const ss58Format = this.helper.chain.getChainProperties().ss58Format;128 const tokenNominal = this.helper.balance.getOneTokenNominal();129 const transactions = [];130 const accounts: IKeyringPair[] = [];131 for (const balance of balances) {132 const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);133 accounts.push(recipient);134 if (balance !== 0n) {135 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);136 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));137 nonce++;138 }139 }140141 await Promise.all(transactions).catch(_e => {});142 143 //#region TODO remove this region, when nonce problem will be solved144 const checkBalances = async () => {145 let isSuccess = true;146 for (let i = 0; i < balances.length; i++) {147 const balance = await this.helper.balance.getSubstrate(accounts[i].address);148 if (balance !== balances[i] * tokenNominal) {149 isSuccess = false;150 break;151 }152 }153 return isSuccess;154 };155156 let accountsCreated = false;157 // checkBalances retry up to 5 blocks158 for (let index = 0; index < 5; index++) {159 accountsCreated = await checkBalances();160 if(accountsCreated) break;161 await wait.newBlocks(1);162 }163164 if (!accountsCreated) throw Error('Accounts generation failed');165 //#endregion166167 return accounts;168 };169170 // TODO combine this method and createAccounts into one171 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 172 const createAsManyAsCan = async () => {173 let transactions: any = [];174 const accounts: IKeyringPair[] = [];175 let nonce = await this.helper.chain.getNonce(donor.address);176 const tokenNominal = this.helper.balance.getOneTokenNominal();177 for (let i = 0; i < accountsToCreate; i++) {178 if (i === 500) { // if there are too many accounts to create179 await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 180 transactions = []; //181 nonce = await this.helper.chain.getNonce(donor.address); // update nonce 182 }183 const recepient = this.helper.util.fromSeed(mnemonicGenerate());184 accounts.push(recepient);185 if (withBalance !== 0n) {186 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);187 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));188 nonce++;189 }190 }191 192 const fullfilledAccounts = [];193 await Promise.allSettled(transactions);194 for (const account of accounts) {195 const accountBalance = await this.helper.balance.getSubstrate(account.address);196 if (accountBalance === withBalance * tokenNominal) {197 fullfilledAccounts.push(account);198 }199 }200 return fullfilledAccounts;201 };202203 204 const crowd: IKeyringPair[] = [];205 // do up to 5 retries206 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {207 const asManyAsCan = await createAsManyAsCan();208 crowd.push(...asManyAsCan);209 accountsToCreate -= asManyAsCan.length;210 }211212 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);213214 return crowd;215 };216217 isDevNode = async () => {218 const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [1])]);219 const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [2])]);220 const findCreationDate = async (block: any) => {221 const humanBlock = block.toHuman();222 let date;223 humanBlock.block.extrinsics.forEach((ext: any) => {224 if(ext.method.section === 'timestamp') {225 date = Number(ext.method.args.now.replaceAll(',', ''));226 }227 });228 return date;229 };230 const block1date = await findCreationDate(block1);231 const block2date = await findCreationDate(block2);232 if(block2date! - block1date! < 9000) return true;233 };234 235 async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {236 const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);237 let balance = await this.helper.balance.getSubstrate(address); 238 239 await promise();240 241 balance -= await this.helper.balance.getSubstrate(address);242 243 return balance;244 }245}246247class WaitGroup {248 helper: UniqueHelper;249250 constructor(helper: UniqueHelper) {251 this.helper = helper;252 }253254 /**255 * Wait for specified bnumber of blocks256 * @param blocksCount number of blocks to wait257 * @returns 258 */259 async newBlocks(blocksCount = 1): Promise<void> {260 // eslint-disable-next-line no-async-promise-executor261 const promise = new Promise<void>(async (resolve) => {262 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {263 if (blocksCount > 0) {264 blocksCount--;265 } else {266 unsubscribe();267 resolve();268 }269 });270 });271 return promise;272 }273274 async forParachainBlockNumber(blockNumber: bigint) {275 // eslint-disable-next-line no-async-promise-executor276 return new Promise<void>(async (resolve) => {277 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {278 if (data.number.toNumber() >= blockNumber) {279 unsubscribe();280 resolve();281 }282 });283 });284 }285 286 async forRelayBlockNumber(blockNumber: bigint) {287 // eslint-disable-next-line no-async-promise-executor288 return new Promise<void>(async (resolve) => {289 const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {290 if (data.value.relayParentNumber.toNumber() >= blockNumber) {291 // @ts-ignore292 unsubscribe();293 resolve();294 }295 });296 });297 }298}299300class AdminGroup {301 helper: UniqueHelper;302303 constructor(helper: UniqueHelper) {304 this.helper = helper;305 }306307 async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {308 const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);309 return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {310 return {311 staker: e.event.data[0].toString(),312 stake: e.event.data[1].toBigInt(),313 payout: e.event.data[2].toBigInt(),314 };315 });316 }317}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {mnemonicGenerate} from '@polkadot/util-crypto';5import {UniqueHelper} from './unique';6import {ApiPromise, WsProvider} from '@polkadot/api';7import * as defs from '../../interfaces/definitions';8import {IKeyringPair} from '@polkadot/types/types';9import {ICrossAccountId} from './types';1011export class SilentLogger {12 log(_msg: any, _level: any): void { }13 level = {14 ERROR: 'ERROR' as const,15 WARNING: 'WARNING' as const,16 INFO: 'INFO' as const,17 };18}1920export class SilentConsole {21 // TODO: Remove, this is temporary: Filter unneeded API output22 // (Jaco promised it will be removed in the next version)23 consoleErr: any;24 consoleLog: any;25 consoleWarn: any;2627 constructor() {28 this.consoleErr = console.error;29 this.consoleLog = console.log;30 this.consoleWarn = console.warn;31 }3233 enable() { 34 const outFn = (printer: any) => (...args: any[]) => {35 for (const arg of args) {36 if (typeof arg !== 'string')37 continue;38 if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')39 return;40 }41 printer(...args);42 };43 44 console.error = outFn(this.consoleErr.bind(console));45 console.log = outFn(this.consoleLog.bind(console));46 console.warn = outFn(this.consoleWarn.bind(console));47 }4849 disable() {50 console.error = this.consoleErr;51 console.log = this.consoleLog;52 console.warn = this.consoleWarn;53 }54}555657export class DevUniqueHelper extends UniqueHelper {58 /**59 * Arrange methods for tests60 */61 arrange: ArrangeGroup;62 wait: WaitGroup;63 admin: AdminGroup;6465 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {66 options.helperBase = options.helperBase ?? DevUniqueHelper;6768 super(logger, options);69 this.arrange = new ArrangeGroup(this);70 this.wait = new WaitGroup(this);71 this.admin = new AdminGroup(this);72 }7374 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {75 const wsProvider = new WsProvider(wsEndpoint);76 this.api = new ApiPromise({77 provider: wsProvider,78 signedExtensions: {79 ContractHelpers: {80 extrinsic: {},81 payload: {},82 },83 FakeTransactionFinalizer: {84 extrinsic: {},85 payload: {},86 },87 },88 rpc: {89 unique: defs.unique.rpc,90 appPromotion: defs.appPromotion.rpc,91 rmrk: defs.rmrk.rpc,92 eth: {93 feeHistory: {94 description: 'Dummy',95 params: [],96 type: 'u8',97 },98 maxPriorityFeePerGas: {99 description: 'Dummy',100 params: [],101 type: 'u8',102 },103 },104 },105 });106 await this.api.isReadyOrError;107 this.network = await UniqueHelper.detectNetwork(this.api);108 }109}110111class ArrangeGroup {112 helper: DevUniqueHelper;113114 constructor(helper: DevUniqueHelper) {115 this.helper = helper;116 }117118 /**119 * Generates accounts with the specified UNQ token balance 120 * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.121 * @param donor donor account for balances122 * @returns array of newly created accounts123 * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 124 */125 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {126 let nonce = await this.helper.chain.getNonce(donor.address);127 const wait = new WaitGroup(this.helper);128 const ss58Format = this.helper.chain.getChainProperties().ss58Format;129 const tokenNominal = this.helper.balance.getOneTokenNominal();130 const transactions = [];131 const accounts: IKeyringPair[] = [];132 for (const balance of balances) {133 const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);134 accounts.push(recipient);135 if (balance !== 0n) {136 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);137 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));138 nonce++;139 }140 }141142 await Promise.all(transactions).catch(_e => {});143 144 //#region TODO remove this region, when nonce problem will be solved145 const checkBalances = async () => {146 let isSuccess = true;147 for (let i = 0; i < balances.length; i++) {148 const balance = await this.helper.balance.getSubstrate(accounts[i].address);149 if (balance !== balances[i] * tokenNominal) {150 isSuccess = false;151 break;152 }153 }154 return isSuccess;155 };156157 let accountsCreated = false;158 // checkBalances retry up to 5 blocks159 for (let index = 0; index < 5; index++) {160 accountsCreated = await checkBalances();161 if(accountsCreated) break;162 await wait.newBlocks(1);163 }164165 if (!accountsCreated) throw Error('Accounts generation failed');166 //#endregion167168 return accounts;169 };170171 // TODO combine this method and createAccounts into one172 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 173 const createAsManyAsCan = async () => {174 let transactions: any = [];175 const accounts: IKeyringPair[] = [];176 let nonce = await this.helper.chain.getNonce(donor.address);177 const tokenNominal = this.helper.balance.getOneTokenNominal();178 for (let i = 0; i < accountsToCreate; i++) {179 if (i === 500) { // if there are too many accounts to create180 await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 181 transactions = []; //182 nonce = await this.helper.chain.getNonce(donor.address); // update nonce 183 }184 const recepient = this.helper.util.fromSeed(mnemonicGenerate());185 accounts.push(recepient);186 if (withBalance !== 0n) {187 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);188 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));189 nonce++;190 }191 }192 193 const fullfilledAccounts = [];194 await Promise.allSettled(transactions);195 for (const account of accounts) {196 const accountBalance = await this.helper.balance.getSubstrate(account.address);197 if (accountBalance === withBalance * tokenNominal) {198 fullfilledAccounts.push(account);199 }200 }201 return fullfilledAccounts;202 };203204 205 const crowd: IKeyringPair[] = [];206 // do up to 5 retries207 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {208 const asManyAsCan = await createAsManyAsCan();209 crowd.push(...asManyAsCan);210 accountsToCreate -= asManyAsCan.length;211 }212213 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);214215 return crowd;216 };217218 isDevNode = async () => {219 const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [1])]);220 const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [2])]);221 const findCreationDate = async (block: any) => {222 const humanBlock = block.toHuman();223 let date;224 humanBlock.block.extrinsics.forEach((ext: any) => {225 if(ext.method.section === 'timestamp') {226 date = Number(ext.method.args.now.replaceAll(',', ''));227 }228 });229 return date;230 };231 const block1date = await findCreationDate(block1);232 const block2date = await findCreationDate(block2);233 if(block2date! - block1date! < 9000) return true;234 };235 236 async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {237 const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);238 let balance = await this.helper.balance.getSubstrate(address); 239 240 await promise();241 242 balance -= await this.helper.balance.getSubstrate(address);243 244 return balance;245 }246}247248class WaitGroup {249 helper: DevUniqueHelper;250251 constructor(helper: DevUniqueHelper) {252 this.helper = helper;253 }254255 /**256 * Wait for specified number of blocks257 * @param blocksCount number of blocks to wait258 * @returns 259 */260 async newBlocks(blocksCount = 1): Promise<void> {261 // eslint-disable-next-line no-async-promise-executor262 const promise = new Promise<void>(async (resolve) => {263 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {264 if (blocksCount > 0) {265 blocksCount--;266 } else {267 unsubscribe();268 resolve();269 }270 });271 });272 return promise;273 }274275 async forParachainBlockNumber(blockNumber: bigint) {276 // eslint-disable-next-line no-async-promise-executor277 return new Promise<void>(async (resolve) => {278 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {279 if (data.number.toNumber() >= blockNumber) {280 unsubscribe();281 resolve();282 }283 });284 });285 }286 287 async forRelayBlockNumber(blockNumber: bigint) {288 // eslint-disable-next-line no-async-promise-executor289 return new Promise<void>(async (resolve) => {290 const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {291 if (data.value.relayParentNumber.toNumber() >= blockNumber) {292 // @ts-ignore293 unsubscribe();294 resolve();295 }296 });297 });298 }299}300301class AdminGroup {302 helper: UniqueHelper;303304 constructor(helper: UniqueHelper) {305 this.helper = helper;306 }307308 async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {309 const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);310 return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {311 return {312 staker: e.event.data[0].toString(),313 stake: e.event.data[1].toBigInt(),314 payout: e.event.data[2].toBigInt(),315 };316 });317 }318}tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -9,7 +9,7 @@
import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';
import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
-import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
+import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
export class CrossAccountId implements ICrossAccountId {
Substrate?: TSubstrateAccount;
@@ -318,6 +318,7 @@
forcedNetwork: TUniqueNetworks | null;
network: TUniqueNetworks | null;
chainLog: IUniqueHelperLog[];
+ children: ChainHelperBase[];
constructor(logger?: ILogger) {
this.util = UniqueUtil;
@@ -328,6 +329,7 @@
this.forcedNetwork = null;
this.network = null;
this.chainLog = [];
+ this.children = [];
}
getApi(): ApiPromise {
@@ -351,8 +353,16 @@
}
async disconnect() {
+ for (const child of this.children) {
+ child.clearApi();
+ }
+
if (this.api === null) return;
await this.api.disconnect();
+ this.clearApi();
+ }
+
+ clearApi() {
this.api = null;
this.network = null;
}
@@ -479,7 +489,7 @@
constructApiCall(apiCall: string, params: any[]) {
if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);
- let call = this.api as any;
+ let call = this.getApi() as any;
for(const part of apiCall.slice(4).split('.')) {
call = call[part];
}
@@ -514,12 +524,18 @@
params,
} as IUniqueHelperLog;
- if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;
+ if(result.status !== this.transactionStatus.SUCCESS) {
+ if (result.moduleError) log.moduleError = result.moduleError;
+ else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;
+ }
if(events.length > 0) log.events = events;
this.chainLog.push(log);
- if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);
+ if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {
+ if (result.moduleError) throw Error(`${result.moduleError}`);
+ else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));
+ }
return result;
}
@@ -2242,7 +2258,67 @@
}
}
+class SchedulerGroup extends HelperGroup {
+ constructor(helper: UniqueHelper) {
+ super(helper);
+ }
+
+ async cancelScheduled(signer: TSigner, scheduledId: string) {
+ return this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.scheduler.cancelNamed',
+ [scheduledId],
+ true,
+ );
+ }
+
+ async changePriority(signer: TSigner, scheduledId: string, priority: number) {
+ return this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.scheduler.changeNamedPriority',
+ [scheduledId, priority],
+ true,
+ );
+ }
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);
+ }
+
+ schedule<T extends UniqueHelper>(
+ scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',
+ scheduledId: string,
+ blocksNum: number,
+ options: ISchedulerOptions = {},
+ ) {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);
+ return this.helper.clone(ScheduledHelperType, {
+ scheduleFn,
+ scheduledId,
+ blocksNum,
+ options,
+ }) as T;
+ }
+}
+
+export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;
+
export class UniqueHelper extends ChainHelperBase {
+ helperBase: any;
+
chain: ChainGroup;
balance: BalanceGroup;
address: AddressGroup;
@@ -2251,9 +2327,13 @@
rft: RFTGroup;
ft: FTGroup;
staking: StakingGroup;
+ scheduler: SchedulerGroup;
- constructor(logger?: ILogger) {
+ constructor(logger?: ILogger, options: {[key: string]: any} = {}) {
super(logger);
+
+ this.helperBase = options.helperBase ?? UniqueHelper;
+
this.chain = new ChainGroup(this);
this.balance = new BalanceGroup(this);
this.address = new AddressGroup(this);
@@ -2262,10 +2342,99 @@
this.rft = new RFTGroup(this);
this.ft = new FTGroup(this);
this.staking = new StakingGroup(this);
+ this.scheduler = new SchedulerGroup(this);
+ }
+
+ clone(helperCls: UniqueHelperConstructor, options: {[key: string]: any} = {}) {
+ Object.setPrototypeOf(helperCls.prototype, this);
+ const newHelper = new helperCls(this.logger, options);
+
+ newHelper.api = this.api;
+ newHelper.network = this.network;
+ newHelper.forceNetwork = this.forceNetwork;
+
+ this.children.push(newHelper);
+
+ return newHelper;
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const SudoHelperType = SudoUniqueHelper(this.helperBase);
+ return this.clone(SudoHelperType) as T;
}
}
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {
+ return class extends Base {
+ scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';
+ scheduledId: string;
+ blocksNum: number;
+ options: ISchedulerOptions;
+
+ constructor(...args: any[]) {
+ const logger = args[0] as ILogger;
+ const options = args[1] as {
+ scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',
+ scheduledId: string,
+ blocksNum: number,
+ options: ISchedulerOptions
+ };
+ super(logger);
+
+ this.scheduleFn = options.scheduleFn;
+ this.scheduledId = options.scheduledId;
+ 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 extrinsic = 'api.tx.scheduler.' + this.scheduleFn;
+
+ return super.executeExtrinsic(
+ sender,
+ extrinsic,
+ [
+ this.scheduledId,
+ this.blocksNum,
+ this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,
+ this.options.priority ?? null,
+ {Value: scheduledTx},
+ ],
+ expectSuccess,
+ );
+ }
+ };
+}
+
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function SudoUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {
+ return class extends Base {
+ constructor(...args: any[]) {
+ super(...args);
+ }
+
+ executeExtrinsic (
+ sender: IKeyringPair,
+ extrinsic: string,
+ params: any[],
+ expectSuccess?: boolean,
+ ): Promise<ITransactionResult> {
+ const call = this.constructApiCall(extrinsic, params);
+
+ return super.executeExtrinsic(
+ sender,
+ 'api.tx.sudo.sudo',
+ [call],
+ expectSuccess,
+ );
+ }
+ };
+}
+
export class UniqueBaseCollection {
helper: UniqueHelper;
collectionId: number;
@@ -2366,6 +2535,28 @@
async burn(signer: TSigner) {
return await this.helper.collection.burn(signer, this.collectionId);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueBaseCollection(this.collectionId, scheduledHelper);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueBaseCollection(this.collectionId, scheduledHelper);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());
+ }
}
@@ -2453,6 +2644,28 @@
async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {
return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueNFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueNFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());
+ }
}
@@ -2536,6 +2749,28 @@
async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {
return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueRFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueRFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());
+ }
}
@@ -2583,6 +2818,28 @@
async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {
return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());
+ }
}
@@ -2620,6 +2877,28 @@
nestingAccount() {
return this.collection.helper.util.getTokenAccount(this);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueBaseToken(this.tokenId, scheduledCollection);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueBaseToken(this.tokenId, scheduledCollection);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());
+ }
}
@@ -2678,6 +2957,28 @@
async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {
return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueNFToken(this.tokenId, scheduledCollection);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueNFToken(this.tokenId, scheduledCollection);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());
+ }
}
export class UniqueRFToken extends UniqueBaseToken {
@@ -2731,4 +3032,26 @@
async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {
return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueRFToken(this.tokenId, scheduledCollection);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueRFToken(this.tokenId, scheduledCollection);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());
+ }
}