1234import {stringToU8a} from '@polkadot/util';5import {encodeAddress, mnemonicGenerate} from '@polkadot/util-crypto';6import {UniqueHelper, MoonbeamHelper, ChainHelperBase, AcalaHelper, RelayHelper, WestmintHelper} from './unique';7import {ApiPromise, Keyring, WsProvider} from '@polkadot/api';8import * as defs from '../../interfaces/definitions';9import {IKeyringPair} from '@polkadot/types/types';10import {EventRecord} from '@polkadot/types/interfaces';11import {ICrossAccountId, TSigner} from './types';12import {FrameSystemEventRecord} from '@polkadot/types/lookup';13import {VoidFn} from '@polkadot/api/types';14import {Pallets} from '..';1516export class SilentLogger {17 log(_msg: any, _level: any): void { }18 level = {19 ERROR: 'ERROR' as const,20 WARNING: 'WARNING' as const,21 INFO: 'INFO' as const,22 };23}2425export class SilentConsole {26 27 28 consoleErr: any;29 consoleLog: any;30 consoleWarn: any;3132 constructor() {33 this.consoleErr = console.error;34 this.consoleLog = console.log;35 this.consoleWarn = console.warn;36 }3738 enable() { 39 const outFn = (printer: any) => (...args: any[]) => {40 for (const arg of args) {41 if (typeof arg !== 'string')42 continue;43 if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')44 return;45 }46 printer(...args);47 };48 49 console.error = outFn(this.consoleErr.bind(console));50 console.log = outFn(this.consoleLog.bind(console));51 console.warn = outFn(this.consoleWarn.bind(console));52 }5354 disable() {55 console.error = this.consoleErr;56 console.log = this.consoleLog;57 console.warn = this.consoleWarn;58 }59}6061export class DevUniqueHelper extends UniqueHelper {62 636465 arrange: ArrangeGroup;66 wait: WaitGroup;67 admin: AdminGroup;68 testUtils: TestUtilGroup;6970 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {71 options.helperBase = options.helperBase ?? DevUniqueHelper;7273 super(logger, options);74 this.arrange = new ArrangeGroup(this);75 this.wait = new WaitGroup(this);76 this.admin = new AdminGroup(this);77 this.testUtils = new TestUtilGroup(this);78 }7980 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {81 const wsProvider = new WsProvider(wsEndpoint);82 this.api = new ApiPromise({83 provider: wsProvider,84 signedExtensions: {85 ContractHelpers: {86 extrinsic: {},87 payload: {},88 },89 CheckMaintenance: {90 extrinsic: {},91 payload: {},92 },93 FakeTransactionFinalizer: {94 extrinsic: {},95 payload: {},96 },97 },98 rpc: {99 unique: defs.unique.rpc,100 appPromotion: defs.appPromotion.rpc,101 rmrk: defs.rmrk.rpc,102 eth: {103 feeHistory: {104 description: 'Dummy',105 params: [],106 type: 'u8',107 },108 maxPriorityFeePerGas: {109 description: 'Dummy',110 params: [],111 type: 'u8',112 },113 },114 },115 });116 await this.api.isReadyOrError;117 this.network = await UniqueHelper.detectNetwork(this.api);118 }119}120121export class DevRelayHelper extends RelayHelper {}122123export class DevWestmintHelper extends WestmintHelper {124 wait: WaitGroup;125126 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {127 options.helperBase = options.helperBase ?? DevWestmintHelper;128129 super(logger, options);130 this.wait = new WaitGroup(this);131 }132}133134export class DevStatemineHelper extends DevWestmintHelper {}135136export class DevStatemintHelper extends DevWestmintHelper {}137138export class DevMoonbeamHelper extends MoonbeamHelper {139 account: MoonbeamAccountGroup;140 wait: WaitGroup;141142 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {143 options.helperBase = options.helperBase ?? DevMoonbeamHelper;144145 super(logger, options);146 this.account = new MoonbeamAccountGroup(this);147 this.wait = new WaitGroup(this);148 }149}150151export class DevMoonriverHelper extends DevMoonbeamHelper {}152153export class DevAcalaHelper extends AcalaHelper {154 wait: WaitGroup;155156 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {157 options.helperBase = options.helperBase ?? DevAcalaHelper;158159 super(logger, options);160 this.wait = new WaitGroup(this);161 }162}163164export class DevKaruraHelper extends DevAcalaHelper {}165166class ArrangeGroup {167 helper: DevUniqueHelper;168169 scheduledIdSlider = 0;170171 constructor(helper: DevUniqueHelper) {172 this.helper = helper;173 }174175 176177178179180181182 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {183 let nonce = await this.helper.chain.getNonce(donor.address);184 const wait = new WaitGroup(this.helper);185 const ss58Format = this.helper.chain.getChainProperties().ss58Format;186 const tokenNominal = this.helper.balance.getOneTokenNominal();187 const transactions = [];188 const accounts: IKeyringPair[] = [];189 for (const balance of balances) {190 const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);191 accounts.push(recipient);192 if (balance !== 0n) {193 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);194 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));195 nonce++;196 }197 }198199 await Promise.all(transactions).catch(_e => {});200 201 202 const checkBalances = async () => {203 let isSuccess = true;204 for (let i = 0; i < balances.length; i++) {205 const balance = await this.helper.balance.getSubstrate(accounts[i].address);206 if (balance !== balances[i] * tokenNominal) {207 isSuccess = false;208 break;209 }210 }211 return isSuccess;212 };213214 let accountsCreated = false;215 const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;216 217 for (let index = 0; index < maxBlocksChecked; index++) {218 accountsCreated = await checkBalances();219 if(accountsCreated) break;220 await wait.newBlocks(1);221 }222223 if (!accountsCreated) throw Error('Accounts generation failed');224 225226 return accounts;227 };228229 230 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 231 const createAsManyAsCan = async () => {232 let transactions: any = [];233 const accounts: IKeyringPair[] = [];234 let nonce = await this.helper.chain.getNonce(donor.address);235 const tokenNominal = this.helper.balance.getOneTokenNominal();236 for (let i = 0; i < accountsToCreate; i++) {237 if (i === 500) { 238 await Promise.allSettled(transactions); 239 transactions = []; 240 nonce = await this.helper.chain.getNonce(donor.address); 241 }242 const recepient = this.helper.util.fromSeed(mnemonicGenerate());243 accounts.push(recepient);244 if (withBalance !== 0n) {245 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);246 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));247 nonce++;248 }249 }250 251 const fullfilledAccounts = [];252 await Promise.allSettled(transactions);253 for (const account of accounts) {254 const accountBalance = await this.helper.balance.getSubstrate(account.address);255 if (accountBalance === withBalance * tokenNominal) {256 fullfilledAccounts.push(account);257 }258 }259 return fullfilledAccounts;260 };261262 263 const crowd: IKeyringPair[] = [];264 265 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {266 const asManyAsCan = await createAsManyAsCan();267 crowd.push(...asManyAsCan);268 accountsToCreate -= asManyAsCan.length;269 }270271 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);272273 return crowd;274 };275276 isDevNode = async () => {277 let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();278 if (blockNumber == 0) {279 await this.helper.wait.newBlocks(1); 280 blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();281 }282 const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])]);283 const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber - 1])]);284 const findCreationDate = (block: any) => {285 const humanBlock = block.toHuman();286 let date;287 humanBlock.block.extrinsics.forEach((ext: any) => {288 if(ext.method.section === 'timestamp') {289 date = Number(ext.method.args.now.replaceAll(',', ''));290 }291 });292 return date;293 };294 const block1date = await findCreationDate(block1);295 const block2date = await findCreationDate(block2);296 if(block2date! - block1date! < 9000) return true;297 };298 299 async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {300 const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);301 let balance = await this.helper.balance.getSubstrate(address); 302 303 await promise();304 305 balance -= await this.helper.balance.getSubstrate(address);306 307 return balance;308 }309310 calculatePalletAddress(palletId: any) {311 const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));312 return encodeAddress(address, this.helper.chain.getChainProperties().ss58Format);313 }314315 makeScheduledIds(num: number): string[] {316 function makeId(slider: number) {317 const scheduledIdSize = 64;318 const hexId = slider.toString(16);319 const prefixSize = scheduledIdSize - hexId.length;320321 const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;322323 return scheduledId; 324 }325326 const ids = [];327 for (let i = 0; i < num; i++) {328 ids.push(makeId(this.scheduledIdSlider));329 this.scheduledIdSlider += 1;330 }331332 return ids;333 }334335 makeScheduledId(): string {336 return (this.makeScheduledIds(1))[0];337 }338339 async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {340 const capture = new EventCapture(this.helper, eventSection, eventMethod);341 await capture.startCapture();342343 return capture;344 }345}346347class MoonbeamAccountGroup {348 helper: MoonbeamHelper;349350 keyring: Keyring;351 _alithAccount: IKeyringPair;352 _baltatharAccount: IKeyringPair;353 _dorothyAccount: IKeyringPair;354355 constructor(helper: MoonbeamHelper) {356 this.helper = helper;357358 this.keyring = new Keyring({type: 'ethereum'});359 const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';360 const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';361 const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';362363 this._alithAccount = this.keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');364 this._baltatharAccount = this.keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');365 this._dorothyAccount = this.keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');366 }367368 alithAccount() {369 return this._alithAccount;370 }371372 baltatharAccount() {373 return this._baltatharAccount;374 }375376 dorothyAccount() {377 return this._dorothyAccount;378 }379380 create() {381 return this.keyring.addFromUri(mnemonicGenerate());382 }383}384385class WaitGroup {386 helper: ChainHelperBase;387388 constructor(helper: ChainHelperBase) {389 this.helper = helper;390 }391392 sleep(milliseconds: number) {393 return new Promise((resolve) => setTimeout(resolve, milliseconds));394 }395396 private async waitWithTimeout(promise: Promise<any>, timeout: number) {397 let isBlock = false;398 promise.then(() => isBlock = true).catch(() => isBlock = true);399 let totalTime = 0;400 const step = 100;401 while(!isBlock) {402 await this.sleep(step);403 totalTime += step;404 if(totalTime >= timeout) throw Error('Blocks production failed');405 }406 return promise;407 }408409 410411412413414 async newBlocks(blocksCount = 1, timeout?: number): Promise<void> {415 timeout = timeout ?? blocksCount * 60_000;416 417 const promise = new Promise<void>(async (resolve) => {418 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {419 if (blocksCount > 0) {420 blocksCount--;421 } else {422 unsubscribe();423 resolve();424 }425 });426 });427 await this.waitWithTimeout(promise, timeout);428 return promise;429 }430431 async forParachainBlockNumber(blockNumber: bigint | number, timeout?: number) {432 timeout = timeout ?? 30 * 60 * 1000;433 434 const promise = new Promise<void>(async (resolve) => {435 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads((data: any) => {436 if (data.number.toNumber() >= blockNumber) {437 unsubscribe();438 resolve();439 }440 });441 });442 await this.waitWithTimeout(promise, timeout);443 return promise;444 }445 446 async forRelayBlockNumber(blockNumber: bigint | number, timeout?: number) {447 timeout = timeout ?? 30 * 60 * 1000;448 449 const promise = new Promise<void>(async (resolve) => {450 const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData((data: any) => {451 if (data.value.relayParentNumber.toNumber() >= blockNumber) {452 453 unsubscribe();454 resolve();455 }456 });457 });458 await this.waitWithTimeout(promise, timeout);459 return promise;460 }461462 noScheduledTasks() {463 const api = this.helper.getApi();464 465 466 const promise = new Promise<void>(async resolve => {467 const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {468 const areThereScheduledTasks = await api.query.scheduler.lookup.entries();469470 if(areThereScheduledTasks.length == 0) {471 unsubscribe();472 resolve();473 }474 }); 475 });476477 return promise;478 }479480 event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {481 482 const promise = new Promise<EventRecord | null>(async (resolve) => {483 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {484 const blockNumber = header.number.toHuman();485 const blockHash = header.hash;486 const eventIdStr = `${eventSection}.${eventMethod}`;487 const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;488 489 this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);490 491 const apiAt = await this.helper.getApi().at(blockHash);492 const eventRecords = (await apiAt.query.system.events()) as any;493 494 const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {495 return r.event.section == eventSection && r.event.method == eventMethod;496 });497 498 if (neededEvent) {499 unsubscribe();500 resolve(neededEvent);501 } else if (maxBlocksToWait > 0) {502 maxBlocksToWait--;503 } else {504 this.helper.logger.log(`Event \`${eventIdStr}\` is NOT found`);505 unsubscribe();506 resolve(null);507 }508 });509 });510 return promise;511 }512}513514class TestUtilGroup {515 helper: DevUniqueHelper;516517 constructor(helper: DevUniqueHelper) {518 this.helper = helper;519 }520521 async enable() {522 if (this.helper.fetchMissingPalletNames([Pallets.TestUtils]).length != 0) {523 return;524 }525526 const signer = this.helper.util.fromSeed('//Alice');527 await this.helper.getSudo<DevUniqueHelper>().executeExtrinsic(signer, 'api.tx.testUtils.enable', [], true);528 }529530 async setTestValue(signer: TSigner, testVal: number) {531 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValue', [testVal], true);532 }533534 async incTestValue(signer: TSigner) {535 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.incTestValue', [], true);536 }537538 async setTestValueAndRollback(signer: TSigner, testVal: number) {539 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValueAndRollback', [testVal], true);540 }541542 async testValue(blockIdx?: number) {543 const api = blockIdx544 ? await this.helper.getApi().at(await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockIdx]))545 : this.helper.getApi();546547 return (await api.query.testUtils.testValue()).toJSON();548 }549550 async justTakeFee(signer: TSigner) {551 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.justTakeFee', [], true);552 }553554 async selfCancelingInc(signer: TSigner, scheduledId: string, maxTestVal: number) {555 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.selfCancelingInc', [scheduledId, maxTestVal], true);556 }557}558559class EventCapture {560 helper: DevUniqueHelper;561 eventSection: string;562 eventMethod: string;563 events: EventRecord[] = [];564 unsubscribe: VoidFn | null = null;565566 constructor(567 helper: DevUniqueHelper,568 eventSection: string,569 eventMethod: string,570 ) {571 this.helper = helper;572 this.eventSection = eventSection;573 this.eventMethod = eventMethod;574 }575576 async startCapture() {577 this.stopCapture();578 this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {579 const newEvents = eventRecords.filter(r => {580 return r.event.section == this.eventSection && r.event.method == this.eventMethod;581 });582583 this.events.push(...newEvents);584 })) as any;585 }586587 stopCapture() {588 if (this.unsubscribe !== null) {589 this.unsubscribe();590 }591 }592593 extractCapturedEvents() {594 return this.events;595 }596}597598class AdminGroup {599 helper: UniqueHelper;600601 constructor(helper: UniqueHelper) {602 this.helper = helper;603 }604605 async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {606 const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);607 return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {608 return {609 staker: e.event.data[0].toString(),610 stake: e.event.data[1].toBigInt(),611 payout: e.event.data[2].toBigInt(),612 };613 });614 }615}