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 };4849 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 {122 wait: WaitGroup;123124 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {125 options.helperBase = options.helperBase ?? DevRelayHelper;126127 super(logger, options);128 this.wait = new WaitGroup(this);129 }130}131132export class DevWestmintHelper extends WestmintHelper {133 wait: WaitGroup;134135 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {136 options.helperBase = options.helperBase ?? DevWestmintHelper;137138 super(logger, options);139 this.wait = new WaitGroup(this);140 }141}142143export class DevStatemineHelper extends DevWestmintHelper {}144145export class DevStatemintHelper extends DevWestmintHelper {}146147export class DevMoonbeamHelper extends MoonbeamHelper {148 account: MoonbeamAccountGroup;149 wait: WaitGroup;150151 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {152 options.helperBase = options.helperBase ?? DevMoonbeamHelper;153 options.notePreimagePallet = options.notePreimagePallet ?? 'democracy';154155 super(logger, options);156 this.account = new MoonbeamAccountGroup(this);157 this.wait = new WaitGroup(this);158 }159}160161export class DevMoonriverHelper extends DevMoonbeamHelper {162 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {163 options.notePreimagePallet = options.notePreimagePallet ?? 'preimage';164 super(logger, options);165 }166}167168export class DevAcalaHelper extends AcalaHelper {169 wait: WaitGroup;170171 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {172 options.helperBase = options.helperBase ?? DevAcalaHelper;173174 super(logger, options);175 this.wait = new WaitGroup(this);176 }177}178179export class DevKaruraHelper extends DevAcalaHelper {}180181class ArrangeGroup {182 helper: DevUniqueHelper;183184 scheduledIdSlider = 0;185186 constructor(helper: DevUniqueHelper) {187 this.helper = helper;188 }189190 191192193194195196197 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {198 let nonce = await this.helper.chain.getNonce(donor.address);199 const wait = new WaitGroup(this.helper);200 const ss58Format = this.helper.chain.getChainProperties().ss58Format;201 const tokenNominal = this.helper.balance.getOneTokenNominal();202 const transactions = [];203 const accounts: IKeyringPair[] = [];204 for (const balance of balances) {205 const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);206 accounts.push(recipient);207 if (balance !== 0n) {208 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);209 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));210 nonce++;211 }212 }213214 await Promise.all(transactions).catch(_e => {});215216 217 const checkBalances = async () => {218 let isSuccess = true;219 for (let i = 0; i < balances.length; i++) {220 const balance = await this.helper.balance.getSubstrate(accounts[i].address);221 if (balance !== balances[i] * tokenNominal) {222 isSuccess = false;223 break;224 }225 }226 return isSuccess;227 };228229 let accountsCreated = false;230 const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;231 232 for (let index = 0; index < maxBlocksChecked; index++) {233 accountsCreated = await checkBalances();234 if(accountsCreated) break;235 await wait.newBlocks(1);236 }237238 if (!accountsCreated) throw Error('Accounts generation failed');239 240241 return accounts;242 };243244 245 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {246 const createAsManyAsCan = async () => {247 let transactions: any = [];248 const accounts: IKeyringPair[] = [];249 let nonce = await this.helper.chain.getNonce(donor.address);250 const tokenNominal = this.helper.balance.getOneTokenNominal();251 for (let i = 0; i < accountsToCreate; i++) {252 if (i === 500) { 253 await Promise.allSettled(transactions); 254 transactions = []; 255 nonce = await this.helper.chain.getNonce(donor.address); 256 }257 const recepient = this.helper.util.fromSeed(mnemonicGenerate());258 accounts.push(recepient);259 if (withBalance !== 0n) {260 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);261 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));262 nonce++;263 }264 }265266 const fullfilledAccounts = [];267 await Promise.allSettled(transactions);268 for (const account of accounts) {269 const accountBalance = await this.helper.balance.getSubstrate(account.address);270 if (accountBalance === withBalance * tokenNominal) {271 fullfilledAccounts.push(account);272 }273 }274 return fullfilledAccounts;275 };276277278 const crowd: IKeyringPair[] = [];279 280 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {281 const asManyAsCan = await createAsManyAsCan();282 crowd.push(...asManyAsCan);283 accountsToCreate -= asManyAsCan.length;284 }285286 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);287288 return crowd;289 };290291 isDevNode = async () => {292 let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();293 if (blockNumber == 0) {294 await this.helper.wait.newBlocks(1);295 blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();296 }297 const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])]);298 const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber - 1])]);299 const findCreationDate = (block: any) => {300 const humanBlock = block.toHuman();301 let date;302 humanBlock.block.extrinsics.forEach((ext: any) => {303 if(ext.method.section === 'timestamp') {304 date = Number(ext.method.args.now.replaceAll(',', ''));305 }306 });307 return date;308 };309 const block1date = await findCreationDate(block1);310 const block2date = await findCreationDate(block2);311 if(block2date! - block1date! < 9000) return true;312 };313314 async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {315 const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);316 let balance = await this.helper.balance.getSubstrate(address);317318 await promise();319320 balance -= await this.helper.balance.getSubstrate(address);321322 return balance;323 }324325 calculatePalletAddress(palletId: any) {326 const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));327 return encodeAddress(address, this.helper.chain.getChainProperties().ss58Format);328 }329330 makeScheduledIds(num: number): string[] {331 function makeId(slider: number) {332 const scheduledIdSize = 64;333 const hexId = slider.toString(16);334 const prefixSize = scheduledIdSize - hexId.length;335336 const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;337338 return scheduledId;339 }340341 const ids = [];342 for (let i = 0; i < num; i++) {343 ids.push(makeId(this.scheduledIdSlider));344 this.scheduledIdSlider += 1;345 }346347 return ids;348 }349350 makeScheduledId(): string {351 return (this.makeScheduledIds(1))[0];352 }353354 async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {355 const capture = new EventCapture(this.helper, eventSection, eventMethod);356 await capture.startCapture();357358 return capture;359 }360}361362class MoonbeamAccountGroup {363 helper: MoonbeamHelper;364365 keyring: Keyring;366 _alithAccount: IKeyringPair;367 _baltatharAccount: IKeyringPair;368 _dorothyAccount: IKeyringPair;369370 constructor(helper: MoonbeamHelper) {371 this.helper = helper;372373 this.keyring = new Keyring({type: 'ethereum'});374 const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';375 const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';376 const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';377378 this._alithAccount = this.keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');379 this._baltatharAccount = this.keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');380 this._dorothyAccount = this.keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');381 }382383 alithAccount() {384 return this._alithAccount;385 }386387 baltatharAccount() {388 return this._baltatharAccount;389 }390391 dorothyAccount() {392 return this._dorothyAccount;393 }394395 create() {396 return this.keyring.addFromUri(mnemonicGenerate());397 }398}399400class WaitGroup {401 helper: ChainHelperBase;402403 constructor(helper: ChainHelperBase) {404 this.helper = helper;405 }406407 sleep(milliseconds: number) {408 return new Promise((resolve) => setTimeout(resolve, milliseconds));409 }410411 private async waitWithTimeout(promise: Promise<any>, timeout: number) {412 let isBlock = false;413 promise.then(() => isBlock = true).catch(() => isBlock = true);414 let totalTime = 0;415 const step = 100;416 while(!isBlock) {417 await this.sleep(step);418 totalTime += step;419 if(totalTime >= timeout) throw Error('Blocks production failed');420 }421 return promise;422 }423424 425426427428429 async newBlocks(blocksCount = 1, timeout?: number): Promise<void> {430 timeout = timeout ?? blocksCount * 60_000;431 432 const promise = new Promise<void>(async (resolve) => {433 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {434 if (blocksCount > 0) {435 blocksCount--;436 } else {437 unsubscribe();438 resolve();439 }440 });441 });442 await this.waitWithTimeout(promise, timeout);443 return promise;444 }445446 async forParachainBlockNumber(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().rpc.chain.subscribeNewHeads((data: any) => {451 if (data.number.toNumber() >= blockNumber) {452 unsubscribe();453 resolve();454 }455 });456 });457 await this.waitWithTimeout(promise, timeout);458 return promise;459 }460461 async forRelayBlockNumber(blockNumber: bigint | number, timeout?: number) {462 timeout = timeout ?? 30 * 60 * 1000;463 464 const promise = new Promise<void>(async (resolve) => {465 const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData((data: any) => {466 if (data.value.relayParentNumber.toNumber() >= blockNumber) {467 468 unsubscribe();469 resolve();470 }471 });472 });473 await this.waitWithTimeout(promise, timeout);474 return promise;475 }476477 noScheduledTasks() {478 const api = this.helper.getApi();479480 481 const promise = new Promise<void>(async resolve => {482 const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {483 const areThereScheduledTasks = await api.query.scheduler.lookup.entries();484485 if(areThereScheduledTasks.length == 0) {486 unsubscribe();487 resolve();488 }489 });490 });491492 return promise;493 }494495 event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {496 497 const promise = new Promise<EventRecord | null>(async (resolve) => {498 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {499 const blockNumber = header.number.toHuman();500 const blockHash = header.hash;501 const eventIdStr = `${eventSection}.${eventMethod}`;502 const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;503504 this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);505506 const apiAt = await this.helper.getApi().at(blockHash);507 const eventRecords = (await apiAt.query.system.events()) as any;508509 const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {510 return r.event.section == eventSection && r.event.method == eventMethod;511 });512513 if (neededEvent) {514 unsubscribe();515 resolve(neededEvent);516 } else if (maxBlocksToWait > 0) {517 maxBlocksToWait--;518 } else {519 this.helper.logger.log(`Event \`${eventIdStr}\` is NOT found`);520 unsubscribe();521 resolve(null);522 }523 });524 });525 return promise;526 }527}528529class TestUtilGroup {530 helper: DevUniqueHelper;531532 constructor(helper: DevUniqueHelper) {533 this.helper = helper;534 }535536 async enable() {537 if (this.helper.fetchMissingPalletNames([Pallets.TestUtils]).length != 0) {538 return;539 }540541 const signer = this.helper.util.fromSeed('//Alice');542 await this.helper.getSudo<DevUniqueHelper>().executeExtrinsic(signer, 'api.tx.testUtils.enable', [], true);543 }544545 async setTestValue(signer: TSigner, testVal: number) {546 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValue', [testVal], true);547 }548549 async incTestValue(signer: TSigner) {550 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.incTestValue', [], true);551 }552553 async setTestValueAndRollback(signer: TSigner, testVal: number) {554 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValueAndRollback', [testVal], true);555 }556557 async testValue(blockIdx?: number) {558 const api = blockIdx559 ? await this.helper.getApi().at(await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockIdx]))560 : this.helper.getApi();561562 return (await api.query.testUtils.testValue()).toJSON();563 }564565 async justTakeFee(signer: TSigner) {566 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.justTakeFee', [], true);567 }568569 async selfCancelingInc(signer: TSigner, scheduledId: string, maxTestVal: number) {570 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.selfCancelingInc', [scheduledId, maxTestVal], true);571 }572}573574class EventCapture {575 helper: DevUniqueHelper;576 eventSection: string;577 eventMethod: string;578 events: EventRecord[] = [];579 unsubscribe: VoidFn | null = null;580581 constructor(582 helper: DevUniqueHelper,583 eventSection: string,584 eventMethod: string,585 ) {586 this.helper = helper;587 this.eventSection = eventSection;588 this.eventMethod = eventMethod;589 }590591 async startCapture() {592 this.stopCapture();593 this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {594 const newEvents = eventRecords.filter(r => {595 return r.event.section == this.eventSection && r.event.method == this.eventMethod;596 });597598 this.events.push(...newEvents);599 })) as any;600 }601602 stopCapture() {603 if (this.unsubscribe !== null) {604 this.unsubscribe();605 }606 }607608 extractCapturedEvents() {609 return this.events;610 }611}612613class AdminGroup {614 helper: UniqueHelper;615616 constructor(helper: UniqueHelper) {617 this.helper = helper;618 }619620 async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {621 const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);622 return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {623 return {624 staker: e.event.data[0].toString(),625 stake: e.event.data[1].toBigInt(),626 payout: e.event.data[2].toBigInt(),627 };628 });629 }630}