difftreelog
feat westmint playgrounds
in: master
3 files changed
tests/src/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -9,7 +9,7 @@
import '../../interfaces/augment-api-events';
import {ChainHelperBase} from './unique';
import {ILogger} from './types';
-import {DevUniqueHelper, SilentLogger, SilentConsole, DevMoonbeamHelper, DevMoonriverHelper, DevAcalaHelper, DevKaruraHelper, DevRelayHelper} from './unique.dev';
+import {DevUniqueHelper, SilentLogger, SilentConsole, DevMoonbeamHelper, DevMoonriverHelper, DevAcalaHelper, DevKaruraHelper, DevRelayHelper, DevWestmintHelper} from './unique.dev';
chai.use(chaiAsPromised);
export const expect = chai.expect;
@@ -36,9 +36,8 @@
return usingPlaygroundsGeneral<DevUniqueHelper>(DevUniqueHelper, url, code);
};
-// TODO specific type
-export const usingStatemintPlaygrounds = async (url: string, code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
- return usingPlaygroundsGeneral<DevUniqueHelper>(DevUniqueHelper, url, code);
+export const usingWestmintPlaygrounds = async (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
+ return usingPlaygroundsGeneral<DevWestmintHelper>(DevWestmintHelper, url, code);
};
export const usingRelayPlaygrounds = async (url: string, code: (helper: DevRelayHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
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, MoonbeamHelper, ChainHelperBase, AcalaHelper, RelayHelper} from './unique';6import {ApiPromise, Keyring, WsProvider} from '@polkadot/api';7import * as defs from '../../interfaces/definitions';8import {IKeyringPair} from '@polkadot/types/types';9import {EventRecord} from '@polkadot/types/interfaces';10import {ICrossAccountId} from './types';1112export 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}5657export 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}110111export class DevRelayHelper extends RelayHelper {}112113export class DevMoonbeamHelper extends MoonbeamHelper {114 account: MoonbeamAccountGroup;115 wait: WaitGroup;116117 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {118 options.helperBase = options.helperBase ?? DevMoonbeamHelper;119120 super(logger, options);121 this.account = new MoonbeamAccountGroup(this);122 this.wait = new WaitGroup(this);123 }124}125126export class DevMoonriverHelper extends DevMoonbeamHelper {}127128export class DevAcalaHelper extends AcalaHelper {129 wait: WaitGroup;130131 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {132 options.helperBase = options.helperBase ?? DevAcalaHelper;133134 super(logger, options);135 this.wait = new WaitGroup(this);136 }137}138139export class DevKaruraHelper extends DevAcalaHelper {}140141class ArrangeGroup {142 helper: DevUniqueHelper;143144 constructor(helper: DevUniqueHelper) {145 this.helper = helper;146 }147148 /**149 * Generates accounts with the specified UNQ token balance 150 * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.151 * @param donor donor account for balances152 * @returns array of newly created accounts153 * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 154 */155 createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {156 let nonce = await this.helper.chain.getNonce(donor.address);157 const wait = new WaitGroup(this.helper);158 const ss58Format = this.helper.chain.getChainProperties().ss58Format;159 const tokenNominal = this.helper.balance.getOneTokenNominal();160 const transactions = [];161 const accounts: IKeyringPair[] = [];162 for (const balance of balances) {163 const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);164 accounts.push(recipient);165 if (balance !== 0n) {166 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);167 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));168 nonce++;169 }170 }171172 await Promise.all(transactions).catch(_e => {});173 174 //#region TODO remove this region, when nonce problem will be solved175 const checkBalances = async () => {176 let isSuccess = true;177 for (let i = 0; i < balances.length; i++) {178 const balance = await this.helper.balance.getSubstrate(accounts[i].address);179 if (balance !== balances[i] * tokenNominal) {180 isSuccess = false;181 break;182 }183 }184 return isSuccess;185 };186187 let accountsCreated = false;188 // checkBalances retry up to 5 blocks189 for (let index = 0; index < 5; index++) {190 accountsCreated = await checkBalances();191 if(accountsCreated) break;192 await wait.newBlocks(1);193 }194195 if (!accountsCreated) throw Error('Accounts generation failed');196 //#endregion197198 return accounts;199 };200201 // TODO combine this method and createAccounts into one202 createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => { 203 const createAsManyAsCan = async () => {204 let transactions: any = [];205 const accounts: IKeyringPair[] = [];206 let nonce = await this.helper.chain.getNonce(donor.address);207 const tokenNominal = this.helper.balance.getOneTokenNominal();208 for (let i = 0; i < accountsToCreate; i++) {209 if (i === 500) { // if there are too many accounts to create210 await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 211 transactions = []; //212 nonce = await this.helper.chain.getNonce(donor.address); // update nonce 213 }214 const recepient = this.helper.util.fromSeed(mnemonicGenerate());215 accounts.push(recepient);216 if (withBalance !== 0n) {217 const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);218 transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));219 nonce++;220 }221 }222 223 const fullfilledAccounts = [];224 await Promise.allSettled(transactions);225 for (const account of accounts) {226 const accountBalance = await this.helper.balance.getSubstrate(account.address);227 if (accountBalance === withBalance * tokenNominal) {228 fullfilledAccounts.push(account);229 }230 }231 return fullfilledAccounts;232 };233234 235 const crowd: IKeyringPair[] = [];236 // do up to 5 retries237 for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {238 const asManyAsCan = await createAsManyAsCan();239 crowd.push(...asManyAsCan);240 accountsToCreate -= asManyAsCan.length;241 }242243 if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);244245 return crowd;246 };247248 isDevNode = async () => {249 const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [1])]);250 const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [2])]);251 const findCreationDate = async (block: any) => {252 const humanBlock = block.toHuman();253 let date;254 humanBlock.block.extrinsics.forEach((ext: any) => {255 if(ext.method.section === 'timestamp') {256 date = Number(ext.method.args.now.replaceAll(',', ''));257 }258 });259 return date;260 };261 const block1date = await findCreationDate(block1);262 const block2date = await findCreationDate(block2);263 if(block2date! - block1date! < 9000) return true;264 };265 266 async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {267 const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);268 let balance = await this.helper.balance.getSubstrate(address); 269 270 await promise();271 272 balance -= await this.helper.balance.getSubstrate(address);273 274 return balance;275 }276}277278class MoonbeamAccountGroup {279 helper: MoonbeamHelper;280281 _alithAccount: IKeyringPair;282 _baltatharAccount: IKeyringPair;283 _dorothyAccount: IKeyringPair;284285 constructor(helper: MoonbeamHelper) {286 this.helper = helper;287288 const keyring = new Keyring({type: 'ethereum'});289 const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';290 const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';291 const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';292293 this._alithAccount = keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');294 this._baltatharAccount = keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');295 this._dorothyAccount = keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');296 }297298 alithAccount() {299 return this._alithAccount;300 }301302 baltatharAccount() {303 return this._baltatharAccount;304 }305306 dorothyAccount() {307 return this._dorothyAccount;308 }309}310311class WaitGroup {312 helper: ChainHelperBase;313314 constructor(helper: ChainHelperBase) {315 this.helper = helper;316 }317318 /**319 * Wait for specified number of blocks320 * @param blocksCount number of blocks to wait321 * @returns 322 */323 async newBlocks(blocksCount = 1): Promise<void> {324 // eslint-disable-next-line no-async-promise-executor325 const promise = new Promise<void>(async (resolve) => {326 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {327 if (blocksCount > 0) {328 blocksCount--;329 } else {330 unsubscribe();331 resolve();332 }333 });334 });335 return promise;336 }337338 async forParachainBlockNumber(blockNumber: bigint) {339 // eslint-disable-next-line no-async-promise-executor340 return new Promise<void>(async (resolve) => {341 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {342 if (data.number.toNumber() >= blockNumber) {343 unsubscribe();344 resolve();345 }346 });347 });348 }349 350 async forRelayBlockNumber(blockNumber: bigint) {351 // eslint-disable-next-line no-async-promise-executor352 return new Promise<void>(async (resolve) => {353 const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {354 if (data.value.relayParentNumber.toNumber() >= blockNumber) {355 // @ts-ignore356 unsubscribe();357 resolve();358 }359 });360 });361 }362363 async event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {364 // eslint-disable-next-line no-async-promise-executor365 const promise = new Promise<EventRecord | null>(async (resolve) => {366 const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {367 const blockNumber = header.number.toHuman();368 const blockHash = header.hash;369 const eventIdStr = `${eventSection}.${eventMethod}`;370 const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;371 372 console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);373 374 const apiAt = await this.helper.getApi().at(blockHash);375 const eventRecords = await apiAt.query.system.events();376 377 const neededEvent = eventRecords.find(r => {378 return r.event.section == eventSection && r.event.method == eventMethod;379 });380 381 if (neededEvent) {382 unsubscribe();383 resolve(neededEvent);384 } else if (maxBlocksToWait > 0) {385 maxBlocksToWait--;386 } else {387 console.log(`Event \`${eventIdStr}\` is NOT found`);388 389 unsubscribe();390 resolve(null);391 }392 });393 });394 return promise;395 }396}397398class AdminGroup {399 helper: UniqueHelper;400401 constructor(helper: UniqueHelper) {402 this.helper = helper;403 }404405 async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {406 const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);407 return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {408 return {409 staker: e.event.data[0].toString(),410 stake: e.event.data[1].toBigInt(),411 payout: e.event.data[2].toBigInt(),412 };413 });414 }415}tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -2468,6 +2468,10 @@
async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {
await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);
}
+
+ async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);
+ }
}
class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {
@@ -2477,6 +2481,32 @@
}
}
+class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);
+ }
+
+ async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);
+ }
+
+ async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);
+ }
+
+ async account(assetId: string | number, address: string) {
+ const accountAsset = (
+ await this.helper.callRpc('api.query.assets.account', [assetId, address])
+ ).toJSON()! as any;
+
+ if (accountAsset !== null) {
+ return BigInt(accountAsset['balance']);
+ } else {
+ return null;
+ }
+ }
+}
+
class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {
async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {
await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);
@@ -2504,20 +2534,6 @@
async assetTypeId(location: any) {
return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);
- }
-}
-
-class MoonbeamAssetsGroup extends HelperGroup<MoonbeamHelper> {
- async account(assetId: string, address: string) {
- const accountAsset = (
- await this.helper.callRpc('api.query.assets.account', [assetId, address])
- ).toJSON()! as any;
-
- if (accountAsset !== null) {
- return BigInt(accountAsset['balance']);
- } else {
- return null;
- }
}
}
@@ -2626,10 +2642,26 @@
}
}
+export class WestmintHelper extends XcmChainHelper {
+ balance: SubstrateBalanceGroup<WestmintHelper>;
+ xcm: XcmGroup<WestmintHelper>;
+ assets: AssetsGroup<WestmintHelper>;
+ xTokens: XTokensGroup<WestmintHelper>;
+
+ constructor(logger?: ILogger, options: {[key: string]: any} = {}) {
+ super(logger, options.helperBase ?? WestmintHelper);
+
+ this.balance = new SubstrateBalanceGroup(this);
+ this.xcm = new XcmGroup(this, 'polkadotXcm');
+ this.assets = new AssetsGroup(this);
+ this.xTokens = new XTokensGroup(this);
+ }
+}
+
export class MoonbeamHelper extends XcmChainHelper {
balance: EthereumBalanceGroup<MoonbeamHelper>;
assetManager: MoonbeamAssetManagerGroup;
- assets: MoonbeamAssetsGroup;
+ assets: AssetsGroup<MoonbeamHelper>;
xTokens: XTokensGroup<MoonbeamHelper>;
democracy: MoonbeamDemocracyGroup;
collective: {
@@ -2642,7 +2674,7 @@
this.balance = new EthereumBalanceGroup(this);
this.assetManager = new MoonbeamAssetManagerGroup(this);
- this.assets = new MoonbeamAssetsGroup(this);
+ this.assets = new AssetsGroup(this);
this.xTokens = new XTokensGroup(this);
this.democracy = new MoonbeamDemocracyGroup(this);
this.collective = {