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 DevMoonbeamHelper extends MoonbeamHelper {135 account: MoonbeamAccountGroup;136 wait: WaitGroup;137138 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {139 options.helperBase = options.helperBase ?? DevMoonbeamHelper;140141 super(logger, options);142 this.account = new MoonbeamAccountGroup(this);143 this.wait = new WaitGroup(this);144 }145}146147export class DevMoonriverHelper extends DevMoonbeamHelper {}148149export class DevAcalaHelper extends AcalaHelper {150 wait: WaitGroup;151152 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {153 options.helperBase = options.helperBase ?? DevAcalaHelper;154155 super(logger, options);156 this.wait = new WaitGroup(this);157 }158}159160export class DevKaruraHelper extends DevAcalaHelper {}161162class ArrangeGroup {163 helper: DevUniqueHelper;164165 scheduledIdSlider = 0;166167 constructor(helper: DevUniqueHelper) {168 this.helper = helper;169 }170171 172173174175176177178 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {179 let nonce = await this.helper.chain.getNonce(donor.address);180 const wait = new WaitGroup(this.helper);181 const ss58Format = this.helper.chain.getChainProperties().ss58Format;182 const tokenNominal = this.helper.balance.getOneTokenNominal();183 const transactions = [];184 const accounts: IKeyringPair[] = [];185 for (const balance of balances) {186 const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);187 accounts.push(recipient);188 if (balance !== 0n) {189 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);190 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));191 nonce++;192 }193 }194195 await Promise.all(transactions).catch(_e => {});196 197 198 const checkBalances = async () => {199 let isSuccess = true;200 for (let i = 0; i < balances.length; i++) {201 const balance = await this.helper.balance.getSubstrate(accounts[i].address);202 if (balance !== balances[i] * tokenNominal) {203 isSuccess = false;204 break;205 }206 }207 return isSuccess;208 };209210 let accountsCreated = false;211 const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;212 213 for (let index = 0; index < maxBlocksChecked; index++) {214 accountsCreated = await checkBalances();215 if(accountsCreated) break;216 await wait.newBlocks(1);217 }218219 if (!accountsCreated) throw Error('Accounts generation failed');220 221222 return accounts;223 };224225 226 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 227 const createAsManyAsCan = async () => {228 let transactions: any = [];229 const accounts: IKeyringPair[] = [];230 let nonce = await this.helper.chain.getNonce(donor.address);231 const tokenNominal = this.helper.balance.getOneTokenNominal();232 for (let i = 0; i < accountsToCreate; i++) {233 if (i === 500) { 234 await Promise.allSettled(transactions); 235 transactions = []; 236 nonce = await this.helper.chain.getNonce(donor.address); 237 }238 const recepient = this.helper.util.fromSeed(mnemonicGenerate());239 accounts.push(recepient);240 if (withBalance !== 0n) {241 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);242 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));243 nonce++;244 }245 }246 247 const fullfilledAccounts = [];248 await Promise.allSettled(transactions);249 for (const account of accounts) {250 const accountBalance = await this.helper.balance.getSubstrate(account.address);251 if (accountBalance === withBalance * tokenNominal) {252 fullfilledAccounts.push(account);253 }254 }255 return fullfilledAccounts;256 };257258 259 const crowd: IKeyringPair[] = [];260 261 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {262 const asManyAsCan = await createAsManyAsCan();263 crowd.push(...asManyAsCan);264 accountsToCreate -= asManyAsCan.length;265 }266267 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);268269 return crowd;270 };271272 isDevNode = async () => {273 let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();274 if (blockNumber == 0) {275 await this.helper.wait.newBlocks(1); 276 blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();277 }278 const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])]);279 const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber - 1])]);280 const findCreationDate = (block: any) => {281 const humanBlock = block.toHuman();282 let date;283 humanBlock.block.extrinsics.forEach((ext: any) => {284 if(ext.method.section === 'timestamp') {285 date = Number(ext.method.args.now.replaceAll(',', ''));286 }287 });288 return date;289 };290 const block1date = await findCreationDate(block1);291 const block2date = await findCreationDate(block2);292 if(block2date! - block1date! < 9000) return true;293 };294 295 async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {296 const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);297 let balance = await this.helper.balance.getSubstrate(address); 298 299 await promise();300 301 balance -= await this.helper.balance.getSubstrate(address);302 303 return balance;304 }305306 calculatePalletAddress(palletId: any) {307 const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));308 return encodeAddress(address);309 }310311 async makeScheduledIds(num: number): Promise<string[]> {312 await this.helper.wait.noScheduledTasks();313314 function makeId(slider: number) {315 const scheduledIdSize = 64;316 const hexId = slider.toString(16);317 const prefixSize = scheduledIdSize - hexId.length;318319 const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;320321 return scheduledId; 322 }323324 const ids = [];325 for (let i = 0; i < num; i++) {326 ids.push(makeId(this.scheduledIdSlider));327 this.scheduledIdSlider += 1;328 }329330 return ids;331 }332333 async makeScheduledId(): Promise<string> {334 return (await this.makeScheduledIds(1))[0];335 }336337 async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {338 const capture = new EventCapture(this.helper, eventSection, eventMethod);339 await capture.startCapture();340341 return capture;342 }343}344345class MoonbeamAccountGroup {346 helper: MoonbeamHelper;347348 keyring: Keyring;349 _alithAccount: IKeyringPair;350 _baltatharAccount: IKeyringPair;351 _dorothyAccount: IKeyringPair;352353 constructor(helper: MoonbeamHelper) {354 this.helper = helper;355356 this.keyring = new Keyring({type: 'ethereum'});357 const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';358 const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';359 const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';360361 this._alithAccount = this.keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');362 this._baltatharAccount = this.keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');363 this._dorothyAccount = this.keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');364 }365366 alithAccount() {367 return this._alithAccount;368 }369370 baltatharAccount() {371 return this._baltatharAccount;372 }373374 dorothyAccount() {375 return this._dorothyAccount;376 }377378 create() {379 return this.keyring.addFromUri(mnemonicGenerate());380 }381}382383class WaitGroup {384 helper: ChainHelperBase;385386 constructor(helper: ChainHelperBase) {387 this.helper = helper;388 }389390 sleep(milliseconds: number) {391 return new Promise((resolve) => setTimeout(resolve, milliseconds));392 }393394 private async waitWithTimeout(promise: Promise<any>, timeout: number) {395 let isBlock = false;396 promise.then(() => isBlock = true).catch(() => isBlock = true);397 let totalTime = 0;398 const step = 100;399 while(!isBlock) {400 await this.sleep(step);401 totalTime += step;402 if(totalTime >= timeout) throw Error('Blocks production failed');403 }404 return promise;405 }406407 408409410411412 async newBlocks(blocksCount = 1, timeout?: number): Promise<void> {413 timeout = timeout ?? blocksCount * 60_000;414 415 const promise = new Promise<void>(async (resolve) => {416 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {417 if (blocksCount > 0) {418 blocksCount--;419 } else {420 unsubscribe();421 resolve();422 }423 });424 });425 await this.waitWithTimeout(promise, timeout);426 return promise;427 }428429 async forParachainBlockNumber(blockNumber: bigint | number, timeout?: number) {430 timeout = timeout ?? 30 * 60 * 1000;431 432 const promise = new Promise<void>(async (resolve) => {433 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads((data: any) => {434 if (data.number.toNumber() >= blockNumber) {435 unsubscribe();436 resolve();437 }438 });439 });440 await this.waitWithTimeout(promise, timeout);441 return promise;442 }443 444 async forRelayBlockNumber(blockNumber: bigint | number, timeout?: number) {445 timeout = timeout ?? 30 * 60 * 1000;446 447 const promise = new Promise<void>(async (resolve) => {448 const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData((data: any) => {449 if (data.value.relayParentNumber.toNumber() >= blockNumber) {450 451 unsubscribe();452 resolve();453 }454 });455 });456 await this.waitWithTimeout(promise, timeout);457 return promise;458 }459460 noScheduledTasks() {461 const api = this.helper.getApi();462 463 464 const promise = new Promise<void>(async resolve => {465 const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {466 const areThereScheduledTasks = await api.query.scheduler.lookup.entries();467468 if(areThereScheduledTasks.length == 0) {469 unsubscribe();470 resolve();471 }472 }); 473 });474475 return promise;476 }477478 event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {479 480 const promise = new Promise<EventRecord | null>(async (resolve) => {481 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {482 const blockNumber = header.number.toHuman();483 const blockHash = header.hash;484 const eventIdStr = `${eventSection}.${eventMethod}`;485 const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;486 487 this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);488 489 const apiAt = await this.helper.getApi().at(blockHash);490 const eventRecords = (await apiAt.query.system.events()) as any;491 492 const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {493 return r.event.section == eventSection && r.event.method == eventMethod;494 });495 496 if (neededEvent) {497 unsubscribe();498 resolve(neededEvent);499 } else if (maxBlocksToWait > 0) {500 maxBlocksToWait--;501 } else {502 this.helper.logger.log(`Event \`${eventIdStr}\` is NOT found`);503 unsubscribe();504 resolve(null);505 }506 });507 });508 return promise;509 }510}511512class TestUtilGroup {513 helper: DevUniqueHelper;514515 constructor(helper: DevUniqueHelper) {516 this.helper = helper;517 }518519 async enable() {520 if (this.helper.fetchMissingPalletNames([Pallets.TestUtils]).length != 0) {521 return;522 }523524 const signer = this.helper.util.fromSeed('//Alice');525 await this.helper.getSudo<DevUniqueHelper>().executeExtrinsic(signer, 'api.tx.testUtils.enable', [], true);526 }527528 async setTestValue(signer: TSigner, testVal: number) {529 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValue', [testVal], true);530 }531532 async incTestValue(signer: TSigner) {533 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.incTestValue', [], true);534 }535536 async setTestValueAndRollback(signer: TSigner, testVal: number) {537 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValueAndRollback', [testVal], true);538 }539540 async testValue(blockIdx?: number) {541 const api = blockIdx542 ? await this.helper.getApi().at(await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockIdx]))543 : this.helper.getApi();544545 return (await api.query.testUtils.testValue()).toJSON();546 }547548 async justTakeFee(signer: TSigner) {549 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.justTakeFee', [], true);550 }551552 async selfCancelingInc(signer: TSigner, scheduledId: string, maxTestVal: number) {553 await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.selfCancelingInc', [scheduledId, maxTestVal], true);554 }555}556557class EventCapture {558 helper: DevUniqueHelper;559 eventSection: string;560 eventMethod: string;561 events: EventRecord[] = [];562 unsubscribe: VoidFn | null = null;563564 constructor(565 helper: DevUniqueHelper,566 eventSection: string,567 eventMethod: string,568 ) {569 this.helper = helper;570 this.eventSection = eventSection;571 this.eventMethod = eventMethod;572 }573574 async startCapture() {575 this.stopCapture();576 this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {577 const newEvents = eventRecords.filter(r => {578 return r.event.section == this.eventSection && r.event.method == this.eventMethod;579 });580581 this.events.push(...newEvents);582 })) as any;583 }584585 stopCapture() {586 if (this.unsubscribe !== null) {587 this.unsubscribe();588 }589 }590591 extractCapturedEvents() {592 return this.events;593 }594}595596class AdminGroup {597 helper: UniqueHelper;598599 constructor(helper: UniqueHelper) {600 this.helper = helper;601 }602603 async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {604 const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);605 return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {606 return {607 staker: e.event.data[0].toString(),608 stake: e.event.data[1].toBigInt(),609 payout: e.event.data[2].toBigInt(),610 };611 });612 }613}