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, IPovInfo, TSigner} from './types';12import {FrameSystemEventRecord} from '@polkadot/types/lookup';13import {VoidFn} from '@polkadot/api/types';14import {Pallets} from '..';15import {spawnSync} from 'child_process';1617export class SilentLogger {18 log(_msg: any, _level: any): void { }19 level = {20 ERROR: 'ERROR' as const,21 WARNING: 'WARNING' as const,22 INFO: 'INFO' as const,23 };24}2526export class SilentConsole {27 28 29 consoleErr: any;30 consoleLog: any;31 consoleWarn: any;3233 constructor() {34 this.consoleErr = console.error;35 this.consoleLog = console.log;36 this.consoleWarn = console.warn;37 }3839 enable() {40 const outFn = (printer: any) => (...args: any[]) => {41 for (const arg of args) {42 if (typeof arg !== 'string')43 continue;44 if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')45 return;46 }47 printer(...args);48 };4950 console.error = outFn(this.consoleErr.bind(console));51 console.log = outFn(this.consoleLog.bind(console));52 console.warn = outFn(this.consoleWarn.bind(console));53 }5455 disable() {56 console.error = this.consoleErr;57 console.log = this.consoleLog;58 console.warn = this.consoleWarn;59 }60}6162export class DevUniqueHelper extends UniqueHelper {63 646566 arrange: ArrangeGroup;67 wait: WaitGroup;68 admin: AdminGroup;69 session: SessionGroup;70 testUtils: TestUtilGroup;7172 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {73 options.helperBase = options.helperBase ?? DevUniqueHelper;7475 super(logger, options);76 this.arrange = new ArrangeGroup(this);77 this.wait = new WaitGroup(this);78 this.admin = new AdminGroup(this);79 this.testUtils = new TestUtilGroup(this);80 this.session = new SessionGroup(this);81 }8283 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {84 const wsProvider = new WsProvider(wsEndpoint);85 this.api = new ApiPromise({86 provider: wsProvider,87 signedExtensions: {88 ContractHelpers: {89 extrinsic: {},90 payload: {},91 },92 CheckMaintenance: {93 extrinsic: {},94 payload: {},95 },96 FilterIdentity: {97 extrinsic: {},98 payload: {},99 },100 FakeTransactionFinalizer: {101 extrinsic: {},102 payload: {},103 },104 },105 rpc: {106 unique: defs.unique.rpc,107 appPromotion: defs.appPromotion.rpc,108 povinfo: defs.povinfo.rpc,109 rmrk: defs.rmrk.rpc,110 eth: {111 feeHistory: {112 description: 'Dummy',113 params: [],114 type: 'u8',115 },116 maxPriorityFeePerGas: {117 description: 'Dummy',118 params: [],119 type: 'u8',120 },121 },122 },123 });124 await this.api.isReadyOrError;125 this.network = await UniqueHelper.detectNetwork(this.api);126 this.wsEndpoint = wsEndpoint;127 }128}129130export class DevRelayHelper extends RelayHelper {131 wait: WaitGroup;132133 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {134 options.helperBase = options.helperBase ?? DevRelayHelper;135136 super(logger, options);137 this.wait = new WaitGroup(this);138 }139}140141export class DevWestmintHelper extends WestmintHelper {142 wait: WaitGroup;143144 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {145 options.helperBase = options.helperBase ?? DevWestmintHelper;146147 super(logger, options);148 this.wait = new WaitGroup(this);149 }150}151152export class DevStatemineHelper extends DevWestmintHelper {}153154export class DevStatemintHelper extends DevWestmintHelper {}155156export class DevMoonbeamHelper extends MoonbeamHelper {157 account: MoonbeamAccountGroup;158 wait: WaitGroup;159160 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {161 options.helperBase = options.helperBase ?? DevMoonbeamHelper;162 options.notePreimagePallet = options.notePreimagePallet ?? 'democracy';163164 super(logger, options);165 this.account = new MoonbeamAccountGroup(this);166 this.wait = new WaitGroup(this);167 }168}169170export class DevMoonriverHelper extends DevMoonbeamHelper {171 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {172 options.notePreimagePallet = options.notePreimagePallet ?? 'preimage';173 super(logger, options);174 }175}176177export class DevAcalaHelper extends AcalaHelper {178 wait: WaitGroup;179180 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {181 options.helperBase = options.helperBase ?? DevAcalaHelper;182183 super(logger, options);184 this.wait = new WaitGroup(this);185 }186}187188export class DevKaruraHelper extends DevAcalaHelper {}189190class ArrangeGroup {191 helper: DevUniqueHelper;192193 scheduledIdSlider = 0;194195 constructor(helper: DevUniqueHelper) {196 this.helper = helper;197 }198199 200201202203204205206 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {207 let nonce = await this.helper.chain.getNonce(donor.address);208 const wait = new WaitGroup(this.helper);209 const ss58Format = this.helper.chain.getChainProperties().ss58Format;210 const tokenNominal = this.helper.balance.getOneTokenNominal();211 const transactions = [];212 const accounts: IKeyringPair[] = [];213 for (const balance of balances) {214 const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);215 accounts.push(recipient);216 if (balance !== 0n) {217 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);218 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));219 nonce++;220 }221 }222223 await Promise.all(transactions).catch(_e => {});224225 226 const checkBalances = async () => {227 let isSuccess = true;228 for (let i = 0; i < balances.length; i++) {229 const balance = await this.helper.balance.getSubstrate(accounts[i].address);230 if (balance !== balances[i] * tokenNominal) {231 isSuccess = false;232 break;233 }234 }235 return isSuccess;236 };237238 let accountsCreated = false;239 const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;240 241 for (let index = 0; index < maxBlocksChecked; index++) {242 accountsCreated = await checkBalances();243 if(accountsCreated) break;244 await wait.newBlocks(1);245 }246247 if (!accountsCreated) throw Error('Accounts generation failed');248 249250 return accounts;251 };252253 254 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {255 const createAsManyAsCan = async () => {256 let transactions: any = [];257 const accounts: IKeyringPair[] = [];258 let nonce = await this.helper.chain.getNonce(donor.address);259 const tokenNominal = this.helper.balance.getOneTokenNominal();260 for (let i = 0; i < accountsToCreate; i++) {261 if (i === 500) { 262 await Promise.allSettled(transactions); 263 transactions = []; 264 nonce = await this.helper.chain.getNonce(donor.address); 265 }266 const recepient = this.helper.util.fromSeed(mnemonicGenerate());267 accounts.push(recepient);268 if (withBalance !== 0n) {269 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);270 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));271 nonce++;272 }273 }274275 const fullfilledAccounts = [];276 await Promise.allSettled(transactions);277 for (const account of accounts) {278 const accountBalance = await this.helper.balance.getSubstrate(account.address);279 if (accountBalance === withBalance * tokenNominal) {280 fullfilledAccounts.push(account);281 }282 }283 return fullfilledAccounts;284 };285286287 const crowd: IKeyringPair[] = [];288 289 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {290 const asManyAsCan = await createAsManyAsCan();291 crowd.push(...asManyAsCan);292 accountsToCreate -= asManyAsCan.length;293 }294295 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);296297 return crowd;298 };299300 isDevNode = async () => {301 let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();302 if (blockNumber == 0) {303 await this.helper.wait.newBlocks(1);304 blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();305 }306 const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])]);307 const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber - 1])]);308 const findCreationDate = (block: any) => {309 const humanBlock = block.toHuman();310 let date;311 humanBlock.block.extrinsics.forEach((ext: any) => {312 if(ext.method.section === 'timestamp') {313 date = Number(ext.method.args.now.replaceAll(',', ''));314 }315 });316 return date;317 };318 const block1date = await findCreationDate(block1);319 const block2date = await findCreationDate(block2);320 if(block2date! - block1date! < 9000) return true;321 };322323 async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {324 const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);325 let balance = await this.helper.balance.getSubstrate(address);326327 await promise();328329 balance -= await this.helper.balance.getSubstrate(address);330331 return balance;332 }333334 async calculatePoVInfo(txs: any[]): Promise<IPovInfo> {335 const rawPovInfo = await this.helper.callRpc('api.rpc.povinfo.estimateExtrinsicPoV', [txs]);336337 const kvJson: {[key: string]: string} = {};338339 for (const kv of rawPovInfo.keyValues) {340 kvJson[kv.key.toHex()] = kv.value.toHex();341 }342343 const kvStr = JSON.stringify(kvJson);344345 const chainql = spawnSync(346 'chainql',347 [348 `--tla-code=data=${kvStr}`,349 '-e', `function(data) cql.dump(cql.chain("${this.helper.getEndpoint()}").latest._meta, data, {omit_empty:true})`,350 ],351 );352353 if (!chainql.stdout) {354 throw Error('unable to get an output from the `chainql`');355 }356357 return {358 proofSize: rawPovInfo.proofSize.toNumber(),359 compactProofSize: rawPovInfo.compactProofSize.toNumber(),360 compressedProofSize: rawPovInfo.compressedProofSize.toNumber(),361 results: rawPovInfo.results,362 kv: JSON.parse(chainql.stdout.toString()),363 };364 }365366 calculatePalletAddress(palletId: any) {367 const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));368 return encodeAddress(address, this.helper.chain.getChainProperties().ss58Format);369 }370371 makeScheduledIds(num: number): string[] {372 function makeId(slider: number) {373 const scheduledIdSize = 64;374 const hexId = slider.toString(16);375 const prefixSize = scheduledIdSize - hexId.length;376377 const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;378379 return scheduledId;380 }381382 const ids = [];383 for (let i = 0; i < num; i++) {384 ids.push(makeId(this.scheduledIdSlider));385 this.scheduledIdSlider += 1;386 }387388 return ids;389 }390391 makeScheduledId(): string {392 return (this.makeScheduledIds(1))[0];393 }394395 async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {396 const capture = new EventCapture(this.helper, eventSection, eventMethod);397 await capture.startCapture();398399 return capture;400 }401}402403class MoonbeamAccountGroup {404 helper: MoonbeamHelper;405406 keyring: Keyring;407 _alithAccount: IKeyringPair;408 _baltatharAccount: IKeyringPair;409 _dorothyAccount: IKeyringPair;410411 constructor(helper: MoonbeamHelper) {412 this.helper = helper;413414 this.keyring = new Keyring({type: 'ethereum'});415 const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';416 const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';417 const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';418419 this._alithAccount = this.keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');420 this._baltatharAccount = this.keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');421 this._dorothyAccount = this.keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');422 }423424 alithAccount() {425 return this._alithAccount;426 }427428 baltatharAccount() {429 return this._baltatharAccount;430 }431432 dorothyAccount() {433 return this._dorothyAccount;434 }435436 create() {437 return this.keyring.addFromUri(mnemonicGenerate());438 }439}440441class WaitGroup {442 helper: ChainHelperBase;443444 constructor(helper: ChainHelperBase) {445 this.helper = helper;446 }447448 sleep(milliseconds: number) {449 return new Promise((resolve) => setTimeout(resolve, milliseconds));450 }451452 private async waitWithTimeout(promise: Promise<any>, timeout: number) {453 let isBlock = false;454 promise.then(() => isBlock = true).catch(() => isBlock = true);455 let totalTime = 0;456 const step = 100;457 while(!isBlock) {458 await this.sleep(step);459 totalTime += step;460 if(totalTime >= timeout) throw Error('Blocks production failed');461 }462 return promise;463 }464465 466467468469470471472 withTimeout<T>(473 promise: Promise<T>,474 timeoutMS = 30000,475 timeoutError = 'The operation has timed out!',476 ): Promise<T> {477 const timeout = new Promise<never>((_, reject) => {478 setTimeout(() => {479 reject(new Error(timeoutError));480 }, timeoutMS);481 });482483 return Promise.race<T>([promise, timeout]).catch(e => {throw new Error(e);});484 }485486 487488489490491 async newBlocks(blocksCount = 1, timeout?: number): Promise<void> {492 timeout = timeout ?? blocksCount * 60_000;493 494 const promise = new Promise<void>(async (resolve) => {495 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {496 if (blocksCount > 0) {497 blocksCount--;498 } else {499 unsubscribe();500 resolve();501 }502 });503 });504 await this.waitWithTimeout(promise, timeout);505 return promise;506 }507508 509510511512513514515 async newSessions(sessionCount = 1, blockTimeout = 60000): Promise<void> {516 console.log(`Waiting for ${sessionCount} new session${sessionCount > 1 ? 's' : ''}.`517 + ' This might take a while -- check SessionPeriod in pallet_session::Config for session time.');518519 const expectedSessionIndex = await (this.helper as DevUniqueHelper).session.getIndex() + sessionCount;520 let currentSessionIndex = -1;521522 while (currentSessionIndex < expectedSessionIndex) {523 524 currentSessionIndex = await this.withTimeout(new Promise(async (resolve) => {525 await this.newBlocks(1);526 const res = await (this.helper as DevUniqueHelper).session.getIndex();527 resolve(res);528 }), blockTimeout, 'The chain has stopped producing blocks!');529 }530 }531532 async forParachainBlockNumber(blockNumber: bigint | number, timeout?: number) {533 timeout = timeout ?? 30 * 60 * 1000;534 535 const promise = new Promise<void>(async (resolve) => {536 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads((data: any) => {537 if (data.number.toNumber() >= blockNumber) {538 unsubscribe();539 resolve();540 }541 });542 });543 await this.waitWithTimeout(promise, timeout);544 return promise;545 }546547 async forRelayBlockNumber(blockNumber: bigint | number, timeout?: number) {548 timeout = timeout ?? 30 * 60 * 1000;549 550 const promise = new Promise<void>(async (resolve) => {551 const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData((data: any) => {552 if (data.value.relayParentNumber.toNumber() >= blockNumber) {553 554 unsubscribe();555 resolve();556 }557 });558 });559 await this.waitWithTimeout(promise, timeout);560 return promise;561 }562563 noScheduledTasks() {564 const api = this.helper.getApi();565566 567 const promise = new Promise<void>(async resolve => {568 const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {569 const areThereScheduledTasks = await api.query.scheduler.lookup.entries();570571 if(areThereScheduledTasks.length == 0) {572 unsubscribe();573 resolve();574 }575 });576 });577578 return promise;579 }580581 event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {582 583 const promise = new Promise<EventRecord | null>(async (resolve) => {584 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {585 const blockNumber = header.number.toHuman();586 const blockHash = header.hash;587 const eventIdStr = `${eventSection}.${eventMethod}`;588 const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;589590 this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);591592 const apiAt = await this.helper.getApi().at(blockHash);593 const eventRecords = (await apiAt.query.system.events()) as any;594595 const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {596 return r.event.section == eventSection && r.event.method == eventMethod;597 });598599 if (neededEvent) {600 unsubscribe();601 resolve(neededEvent);602 } else if (maxBlocksToWait > 0) {603 maxBlocksToWait--;604 } else {605 this.helper.logger.log(`Event \`${eventIdStr}\` is NOT found`);606 unsubscribe();607 resolve(null);608 }609 });610 });611 return promise;612 }613}614615class SessionGroup {616 helper: ChainHelperBase;617618 constructor(helper: ChainHelperBase) {619 this.helper = helper;620 }621622 623 async getIndex(): Promise<number> {624 return (await this.helper.callRpc('api.query.session.currentIndex')).toNumber();625 }626627 newSessions(sessionCount = 1, blockTimeout = 24000): Promise<void> {628 return (this.helper as DevUniqueHelper).wait.newSessions(sessionCount, blockTimeout);629 }630631 setOwnKeys(signer: TSigner, key: string) {632 return this.helper.executeExtrinsic(633 signer,634 'api.tx.session.setKeys',635 [key, '0x0'],636 true,637 );638 }639640 setOwnKeysFromAddress(signer: TSigner) {641 return this.setOwnKeys(signer, '0x' + Buffer.from(signer.addressRaw).toString('hex'));642 }643}644645class TestUtilGroup {646 helper: DevUniqueHelper;647648 constructor(helper: DevUniqueHelper) {649 this.helper = helper;650 }651652 async enable() {653 if (this.helper.fetchMissingPalletNames([Pallets.TestUtils]).length != 0) {654 return;655 }656657 const signer = this.helper.util.fromSeed('//Alice');658 await this.helper.getSudo<DevUniqueHelper>().executeExtrinsic(signer, 'api.tx.testUtils.enable', [], true);659 }660661 async setTestValue(signer: TSigner, testVal: number) {662 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValue', [testVal], true);663 }664665 async incTestValue(signer: TSigner) {666 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.incTestValue', [], true);667 }668669 async setTestValueAndRollback(signer: TSigner, testVal: number) {670 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValueAndRollback', [testVal], true);671 }672673 async testValue(blockIdx?: number) {674 const api = blockIdx675 ? await this.helper.getApi().at(await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockIdx]))676 : this.helper.getApi();677678 return (await api.query.testUtils.testValue()).toJSON();679 }680681 async justTakeFee(signer: TSigner) {682 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.justTakeFee', [], true);683 }684685 async selfCancelingInc(signer: TSigner, scheduledId: string, maxTestVal: number) {686 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.selfCancelingInc', [scheduledId, maxTestVal], true);687 }688}689690class EventCapture {691 helper: DevUniqueHelper;692 eventSection: string;693 eventMethod: string;694 events: EventRecord[] = [];695 unsubscribe: VoidFn | null = null;696697 constructor(698 helper: DevUniqueHelper,699 eventSection: string,700 eventMethod: string,701 ) {702 this.helper = helper;703 this.eventSection = eventSection;704 this.eventMethod = eventMethod;705 }706707 async startCapture() {708 this.stopCapture();709 this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {710 const newEvents = eventRecords.filter(r => {711 return r.event.section == this.eventSection && r.event.method == this.eventMethod;712 });713714 this.events.push(...newEvents);715 })) as any;716 }717718 stopCapture() {719 if (this.unsubscribe !== null) {720 this.unsubscribe();721 }722 }723724 extractCapturedEvents() {725 return this.events;726 }727}728729class AdminGroup {730 helper: UniqueHelper;731732 constructor(helper: UniqueHelper) {733 this.helper = helper;734 }735736 async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {737 const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);738 return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {739 return {740 staker: e.event.data[0].toString(),741 stake: e.event.data[1].toBigInt(),742 payout: e.event.data[2].toBigInt(),743 };744 });745 }746}