git.delta.rocks / unique-network / refs/commits / 1b19b1f3b608

difftreelog

test untrusted reserve locations

Daniel Shiposha2023-04-12parent: #abe0498.patch.diff
in: master

4 files changed

modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {stringToU8a} from '@polkadot/util';5import {encodeAddress, mnemonicGenerate} from '@polkadot/util-crypto';6import {UniqueHelper, MoonbeamHelper, ChainHelperBase, AcalaHelper, RelayHelper, WestmintHelper, AstarHelper} 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  // TODO: Remove, this is temporary: Filter unneeded API output28  // (Jaco promised it will be removed in the next version)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  /**64   * Arrange methods for tests65   */66  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        DisableIdentityCalls: {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        eth: {110          feeHistory: {111            description: 'Dummy',112            params: [],113            type: 'u8',114          },115          maxPriorityFeePerGas: {116            description: 'Dummy',117            params: [],118            type: 'u8',119          },120        },121      },122    });123    await this.api.isReadyOrError;124    this.network = await UniqueHelper.detectNetwork(this.api);125    this.wsEndpoint = wsEndpoint;126  }127}128129export class DevRelayHelper extends RelayHelper {130  wait: WaitGroup;131132  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {133    options.helperBase = options.helperBase ?? DevRelayHelper;134135    super(logger, options);136    this.wait = new WaitGroup(this);137  }138}139140export class DevWestmintHelper extends WestmintHelper {141  wait: WaitGroup;142143  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {144    options.helperBase = options.helperBase ?? DevWestmintHelper;145146    super(logger, options);147    this.wait = new WaitGroup(this);148  }149}150151export class DevStatemineHelper extends DevWestmintHelper {}152153export class DevStatemintHelper extends DevWestmintHelper {}154155export class DevMoonbeamHelper extends MoonbeamHelper {156  account: MoonbeamAccountGroup;157  wait: WaitGroup;158159  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {160    options.helperBase = options.helperBase ?? DevMoonbeamHelper;161    options.notePreimagePallet = options.notePreimagePallet ?? 'preimage';162163    super(logger, options);164    this.account = new MoonbeamAccountGroup(this);165    this.wait = new WaitGroup(this);166  }167}168169export class DevMoonriverHelper extends DevMoonbeamHelper {170  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {171    options.notePreimagePallet = options.notePreimagePallet ?? 'preimage';172    super(logger, options);173  }174}175176export class DevAstarHelper extends AstarHelper {177  wait: WaitGroup;178179  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {180    options.helperBase = options.helperBase ?? DevAstarHelper;181182    super(logger, options);183    this.wait = new WaitGroup(this);184  }185}186187export class DevShidenHelper extends AstarHelper {188  wait: WaitGroup;189190  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {191    options.helperBase = options.helperBase ?? DevShidenHelper;192193    super(logger, options);194    this.wait = new WaitGroup(this);195  }196}197198export class DevAcalaHelper extends AcalaHelper {199  wait: WaitGroup;200201  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {202    options.helperBase = options.helperBase ?? DevAcalaHelper;203204    super(logger, options);205    this.wait = new WaitGroup(this);206  }207}208209export class DevKaruraHelper extends DevAcalaHelper {}210211export class ArrangeGroup {212  helper: DevUniqueHelper;213214  scheduledIdSlider = 0;215216  constructor(helper: DevUniqueHelper) {217    this.helper = helper;218  }219220  /**221   * Generates accounts with the specified UNQ token balance222   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.223   * @param donor donor account for balances224   * @returns array of newly created accounts225   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor);226   */227  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {228    let nonce = await this.helper.chain.getNonce(donor.address);229    const wait = new WaitGroup(this.helper);230    const ss58Format = this.helper.chain.getChainProperties().ss58Format;231    const tokenNominal = this.helper.balance.getOneTokenNominal();232    const transactions = [];233    const accounts: IKeyringPair[] = [];234    for (const balance of balances) {235      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);236      accounts.push(recipient);237      if (balance !== 0n) {238        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);239        transactions.push(this.helper.signTransaction(donor, tx, {nonce, era: 0}, 'account generation'));240        nonce++;241      }242    }243244    await Promise.all(transactions).catch(_e => {});245246    //#region TODO remove this region, when nonce problem will be solved247    const checkBalances = async () => {248      let isSuccess = true;249      for (let i = 0; i < balances.length; i++) {250        const balance = await this.helper.balance.getSubstrate(accounts[i].address);251        if (balance !== balances[i] * tokenNominal) {252          isSuccess = false;253          break;254        }255      }256      return isSuccess;257    };258259    let accountsCreated = false;260    const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;261    // checkBalances retry up to 5-50 blocks262    for (let index = 0; index < maxBlocksChecked; index++) {263      accountsCreated = await checkBalances();264      if(accountsCreated) break;265      await wait.newBlocks(1);266    }267268    if (!accountsCreated) throw Error('Accounts generation failed');269    //#endregion270271    return accounts;272  };273274  // TODO combine this method and createAccounts into one275  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {276    const createAsManyAsCan = async () => {277      let transactions: any = [];278      const accounts: IKeyringPair[] = [];279      let nonce = await this.helper.chain.getNonce(donor.address);280      const tokenNominal = this.helper.balance.getOneTokenNominal();281      const ss58Format = this.helper.chain.getChainProperties().ss58Format;282      for (let i = 0; i < accountsToCreate; i++) {283        if (i === 500) { // if there are too many accounts to create284          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled285          transactions = []; //286          nonce = await this.helper.chain.getNonce(donor.address); // update nonce287        }288        const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);289        accounts.push(recipient);290        if (withBalance !== 0n) {291          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, withBalance * tokenNominal]);292          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));293          nonce++;294        }295      }296297      const fullfilledAccounts = [];298      await Promise.allSettled(transactions);299      for (const account of accounts) {300        const accountBalance = await this.helper.balance.getSubstrate(account.address);301        if (accountBalance === withBalance * tokenNominal) {302          fullfilledAccounts.push(account);303        }304      }305      return fullfilledAccounts;306    };307308309    const crowd: IKeyringPair[] = [];310    // do up to 5 retries311    for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {312      const asManyAsCan = await createAsManyAsCan();313      crowd.push(...asManyAsCan);314      accountsToCreate -= asManyAsCan.length;315    }316317    if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);318319    return crowd;320  };321322  isDevNode = async () => {323    let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();324    if (blockNumber == 0) {325      await this.helper.wait.newBlocks(1);326      blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();327    }328    const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])]);329    const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber - 1])]);330    const findCreationDate = (block: any) => {331      const humanBlock = block.toHuman();332      let date;333      humanBlock.block.extrinsics.forEach((ext: any) => {334        if(ext.method.section === 'timestamp') {335          date = Number(ext.method.args.now.replaceAll(',', ''));336        }337      });338      return date;339    };340    const block1date = await findCreationDate(block1);341    const block2date = await findCreationDate(block2);342    if(block2date! - block1date! < 9000) return true;343  };344345  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {346    const address = payer.Substrate ? payer.Substrate : this.helper.address.ethToSubstrate(payer.Ethereum!);347    let balance = await this.helper.balance.getSubstrate(address);348349    await promise();350351    balance -= await this.helper.balance.getSubstrate(address);352353    return balance;354  }355356  async calculatePoVInfo(txs: any[]): Promise<IPovInfo> {357    const rawPovInfo = await this.helper.callRpc('api.rpc.povinfo.estimateExtrinsicPoV', [txs]);358359    const kvJson: {[key: string]: string} = {};360361    for (const kv of rawPovInfo.keyValues) {362      kvJson[kv.key.toHex()] = kv.value.toHex();363    }364365    const kvStr = JSON.stringify(kvJson);366367    const chainql = spawnSync(368      'chainql',369      [370        `--tla-code=data=${kvStr}`,371        '-e', `function(data) cql.dump(cql.chain("${this.helper.getEndpoint()}").latest._meta, data, {omit_empty:true})`,372      ],373    );374375    if (!chainql.stdout) {376      throw Error('unable to get an output from the `chainql`');377    }378379    return {380      proofSize: rawPovInfo.proofSize.toNumber(),381      compactProofSize: rawPovInfo.compactProofSize.toNumber(),382      compressedProofSize: rawPovInfo.compressedProofSize.toNumber(),383      results: rawPovInfo.results,384      kv: JSON.parse(chainql.stdout.toString()),385    };386  }387388  calculatePalletAddress(palletId: any) {389    const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));390    return encodeAddress(address, this.helper.chain.getChainProperties().ss58Format);391  }392393  makeScheduledIds(num: number): string[] {394    function makeId(slider: number) {395      const scheduledIdSize = 64;396      const hexId = slider.toString(16);397      const prefixSize = scheduledIdSize - hexId.length;398399      const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;400401      return scheduledId;402    }403404    const ids = [];405    for (let i = 0; i < num; i++) {406      ids.push(makeId(this.scheduledIdSlider));407      this.scheduledIdSlider += 1;408    }409410    return ids;411  }412413  makeScheduledId(): string {414    return (this.makeScheduledIds(1))[0];415  }416417  async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {418    const capture = new EventCapture(this.helper, eventSection, eventMethod);419    await capture.startCapture();420421    return capture;422  }423424  makeXcmProgramWithdrawDeposit(beneficiary: Uint8Array, amount: bigint | string) {425    return {426      V2: [427        {428          WithdrawAsset: [429            {430              id: {431                Concrete: {432                  parents: 0,433                  interior: 'Here',434                },435              },436              fun: {437                Fungible: amount,438              },439            },440          ],441        },442        {443          BuyExecution: {444            fees: {445              id: {446                Concrete: {447                  parents: 0,448                  interior: 'Here',449                },450              },451              fun: {452                Fungible: amount,453              },454            },455            weightLimit: 'Unlimited'456          },457        },458        {459          DepositAsset: {460            assets: {461              Wild: 'All'462            },463            maxAssets: 1,464            beneficiary: {465              parents: 0,466              interior: {467                X1: {468                  AccountId32: {469                    network: 'Any',470                    id: beneficiary471                  },472                },473              },474            },475          }476        },477      ],478    };479  }480}481482class MoonbeamAccountGroup {483  helper: MoonbeamHelper;484485  keyring: Keyring;486  _alithAccount: IKeyringPair;487  _baltatharAccount: IKeyringPair;488  _dorothyAccount: IKeyringPair;489490  constructor(helper: MoonbeamHelper) {491    this.helper = helper;492493    this.keyring = new Keyring({type: 'ethereum'});494    const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';495    const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';496    const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';497498    this._alithAccount = this.keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');499    this._baltatharAccount = this.keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');500    this._dorothyAccount = this.keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');501  }502503  alithAccount() {504    return this._alithAccount;505  }506507  baltatharAccount() {508    return this._baltatharAccount;509  }510511  dorothyAccount() {512    return this._dorothyAccount;513  }514515  create() {516    return this.keyring.addFromUri(mnemonicGenerate());517  }518}519520class WaitGroup {521  helper: ChainHelperBase;522523  constructor(helper: ChainHelperBase) {524    this.helper = helper;525  }526527  sleep(milliseconds: number) {528    return new Promise((resolve) => setTimeout(resolve, milliseconds));529  }530531  private async waitWithTimeout(promise: Promise<any>, timeout: number) {532    let isBlock = false;533    promise.then(() => isBlock = true).catch(() => isBlock = true);534    let totalTime = 0;535    const step = 100;536    while(!isBlock) {537      await this.sleep(step);538      totalTime += step;539      if(totalTime >= timeout) throw Error('Blocks production failed');540    }541    return promise;542  }543544  /**545   * Launch some async operation, or throw an error after some time. Note that it will still continue executing after the timeout.546   * @param promise async operation to race against the timeout547   * @param timeoutMS time after which to time out548   * @param timeoutError error message to throw549   * @returns promise of the same type the operation had550   */551  withTimeout<T>(552    promise: Promise<T>,553    timeoutMS = 30000,554    timeoutError = 'The operation has timed out!',555  ): Promise<T> {556    const timeout = new Promise<never>((_, reject) => {557      setTimeout(() => {558        reject(new Error(timeoutError));559      }, timeoutMS);560    });561562    return Promise.race<T>([promise, timeout]).catch(e => {throw new Error(e);});563  }564565  /**566   * Wait for specified number of blocks567   * @param blocksCount number of blocks to wait568   * @returns569   */570  async newBlocks(blocksCount = 1, timeout?: number): Promise<void> {571    timeout = timeout ?? blocksCount * 60_000;572    // eslint-disable-next-line no-async-promise-executor573    const promise = new Promise<void>(async (resolve) => {574      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {575        if (blocksCount > 0) {576          blocksCount--;577        } else {578          unsubscribe();579          resolve();580        }581      });582    });583    await this.waitWithTimeout(promise, timeout);584    return promise;585  }586587  /**588   * Wait for the specified number of sessions to pass.589   * Only applicable if the Session pallet is turned on.590   * @param sessionCount number of sessions to wait591   * @param blockTimeout time in ms until panicking that the chain has stopped producing blocks592   * @returns593   */594  async newSessions(sessionCount = 1, blockTimeout = 60000): Promise<void> {595    console.log(`Waiting for ${sessionCount} new session${sessionCount > 1 ? 's' : ''}.`596      + ' This might take a while -- check SessionPeriod in pallet_session::Config for session time.');597598    const expectedSessionIndex = await (this.helper as DevUniqueHelper).session.getIndex() + sessionCount;599    let currentSessionIndex = -1;600601    while (currentSessionIndex < expectedSessionIndex) {602      // eslint-disable-next-line no-async-promise-executor603      currentSessionIndex = await this.withTimeout(new Promise(async (resolve) => {604        await this.newBlocks(1);605        const res = await (this.helper as DevUniqueHelper).session.getIndex();606        resolve(res);607      }), blockTimeout, 'The chain has stopped producing blocks!');608    }609  }610611  async forParachainBlockNumber(blockNumber: bigint | number, timeout?: number) {612    timeout = timeout ?? 30 * 60 * 1000;613    // eslint-disable-next-line no-async-promise-executor614    const promise = new Promise<void>(async (resolve) => {615      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads((data: any) => {616        if (data.number.toNumber() >= blockNumber) {617          unsubscribe();618          resolve();619        }620      });621    });622    await this.waitWithTimeout(promise, timeout);623    return promise;624  }625626  async forRelayBlockNumber(blockNumber: bigint | number, timeout?: number) {627    timeout = timeout ?? 30 * 60 * 1000;628    // eslint-disable-next-line no-async-promise-executor629    const promise = new Promise<void>(async (resolve) => {630      const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData((data: any) => {631        if (data.value.relayParentNumber.toNumber() >= blockNumber) {632          // @ts-ignore633          unsubscribe();634          resolve();635        }636      });637    });638    await this.waitWithTimeout(promise, timeout);639    return promise;640  }641642  noScheduledTasks() {643    const api = this.helper.getApi();644645    // eslint-disable-next-line no-async-promise-executor646    const promise = new Promise<void>(async resolve => {647      const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {648        const areThereScheduledTasks = await api.query.scheduler.lookup.entries();649650        if(areThereScheduledTasks.length == 0) {651          unsubscribe();652          resolve();653        }654      });655    });656657    return promise;658  }659660  event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {661    // eslint-disable-next-line no-async-promise-executor662    const promise = new Promise<EventRecord | null>(async (resolve) => {663      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {664        const blockNumber = header.number.toHuman();665        const blockHash = header.hash;666        const eventIdStr = `${eventSection}.${eventMethod}`;667        const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;668669        this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);670671        const apiAt = await this.helper.getApi().at(blockHash);672        const eventRecords = (await apiAt.query.system.events()) as any;673674        const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {675          return r.event.section == eventSection && r.event.method == eventMethod;676        });677678        if (neededEvent) {679          unsubscribe();680          resolve(neededEvent);681        } else if (maxBlocksToWait > 0) {682          maxBlocksToWait--;683        } else {684          this.helper.logger.log(`Event \`${eventIdStr}\` is NOT found`);685          unsubscribe();686          resolve(null);687        }688      });689    });690    return promise;691  }692693  async eventOutcome<EventT>(maxBlocksToWait: number, eventSection: string, eventMethod: string) {694    const eventRecord = await this.event(maxBlocksToWait, eventSection, eventMethod);695696    if (eventRecord == null) {697      return null;698    }699700    const event = eventRecord!.event;701    const outcome = event.data[1] as EventT;702703    return outcome;704  }705}706707class SessionGroup {708  helper: ChainHelperBase;709710  constructor(helper: ChainHelperBase) {711    this.helper = helper;712  }713714  //todo:collator documentation715  async getIndex(): Promise<number> {716    return (await this.helper.callRpc('api.query.session.currentIndex')).toNumber();717  }718719  newSessions(sessionCount = 1, blockTimeout = 24000): Promise<void> {720    return (this.helper as DevUniqueHelper).wait.newSessions(sessionCount, blockTimeout);721  }722723  setOwnKeys(signer: TSigner, key: string) {724    return this.helper.executeExtrinsic(725      signer,726      'api.tx.session.setKeys',727      [key, '0x0'],728      true,729    );730  }731732  setOwnKeysFromAddress(signer: TSigner) {733    return this.setOwnKeys(signer, '0x' + Buffer.from(signer.addressRaw).toString('hex'));734  }735}736737class TestUtilGroup {738  helper: DevUniqueHelper;739740  constructor(helper: DevUniqueHelper) {741    this.helper = helper;742  }743744  async enable() {745    if (this.helper.fetchMissingPalletNames([Pallets.TestUtils]).length != 0) {746      return;747    }748749    const signer = this.helper.util.fromSeed('//Alice');750    await this.helper.getSudo<DevUniqueHelper>().executeExtrinsic(signer, 'api.tx.testUtils.enable', [], true);751  }752753  async setTestValue(signer: TSigner, testVal: number) {754    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValue', [testVal], true);755  }756757  async incTestValue(signer: TSigner) {758    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.incTestValue', [], true);759  }760761  async setTestValueAndRollback(signer: TSigner, testVal: number) {762    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValueAndRollback', [testVal], true);763  }764765  async testValue(blockIdx?: number) {766    const api = blockIdx767      ? await this.helper.getApi().at(await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockIdx]))768      : this.helper.getApi();769770    return (await api.query.testUtils.testValue()).toJSON();771  }772773  async justTakeFee(signer: TSigner) {774    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.justTakeFee', [], true);775  }776777  async selfCancelingInc(signer: TSigner, scheduledId: string, maxTestVal: number) {778    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.selfCancelingInc', [scheduledId, maxTestVal], true);779  }780}781782class EventCapture {783  helper: DevUniqueHelper;784  eventSection: string;785  eventMethod: string;786  events: EventRecord[] = [];787  unsubscribe: VoidFn | null = null;788789  constructor(790    helper: DevUniqueHelper,791    eventSection: string,792    eventMethod: string,793  ) {794    this.helper = helper;795    this.eventSection = eventSection;796    this.eventMethod = eventMethod;797  }798799  async startCapture() {800    this.stopCapture();801    this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {802      const newEvents = eventRecords.filter(r => {803        return r.event.section == this.eventSection && r.event.method == this.eventMethod;804      });805806      this.events.push(...newEvents);807    })) as any;808  }809810  stopCapture() {811    if (this.unsubscribe !== null) {812      this.unsubscribe();813    }814  }815816  extractCapturedEvents() {817    return this.events;818  }819}820821class AdminGroup {822  helper: UniqueHelper;823824  constructor(helper: UniqueHelper) {825    this.helper = helper;826  }827828  async payoutStakers(signer: IKeyringPair, stakersToPayout: number):  Promise<{staker: string, stake: bigint, payout: bigint}[]> {829    const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);830    return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {831      return {832        staker: e.event.data[0].toString(),833        stake: e.event.data[1].toBigInt(),834        payout: e.event.data[2].toBigInt(),835      };836    });837  }838}
after · tests/src/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {stringToU8a} from '@polkadot/util';5import {encodeAddress, mnemonicGenerate} from '@polkadot/util-crypto';6import {UniqueHelper, MoonbeamHelper, ChainHelperBase, AcalaHelper, RelayHelper, WestmintHelper, AstarHelper} 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  // TODO: Remove, this is temporary: Filter unneeded API output28  // (Jaco promised it will be removed in the next version)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  /**64   * Arrange methods for tests65   */66  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        DisableIdentityCalls: {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        eth: {110          feeHistory: {111            description: 'Dummy',112            params: [],113            type: 'u8',114          },115          maxPriorityFeePerGas: {116            description: 'Dummy',117            params: [],118            type: 'u8',119          },120        },121      },122    });123    await this.api.isReadyOrError;124    this.network = await UniqueHelper.detectNetwork(this.api);125    this.wsEndpoint = wsEndpoint;126  }127}128129export class DevRelayHelper extends RelayHelper {130  wait: WaitGroup;131132  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {133    options.helperBase = options.helperBase ?? DevRelayHelper;134135    super(logger, options);136    this.wait = new WaitGroup(this);137  }138}139140export class DevWestmintHelper extends WestmintHelper {141  wait: WaitGroup;142143  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {144    options.helperBase = options.helperBase ?? DevWestmintHelper;145146    super(logger, options);147    this.wait = new WaitGroup(this);148  }149}150151export class DevStatemineHelper extends DevWestmintHelper {}152153export class DevStatemintHelper extends DevWestmintHelper {}154155export class DevMoonbeamHelper extends MoonbeamHelper {156  account: MoonbeamAccountGroup;157  wait: WaitGroup;158159  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {160    options.helperBase = options.helperBase ?? DevMoonbeamHelper;161    options.notePreimagePallet = options.notePreimagePallet ?? 'preimage';162163    super(logger, options);164    this.account = new MoonbeamAccountGroup(this);165    this.wait = new WaitGroup(this);166  }167}168169export class DevMoonriverHelper extends DevMoonbeamHelper {170  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {171    options.notePreimagePallet = options.notePreimagePallet ?? 'preimage';172    super(logger, options);173  }174}175176export class DevAstarHelper extends AstarHelper {177  wait: WaitGroup;178179  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {180    options.helperBase = options.helperBase ?? DevAstarHelper;181182    super(logger, options);183    this.wait = new WaitGroup(this);184  }185}186187export class DevShidenHelper extends AstarHelper {188  wait: WaitGroup;189190  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {191    options.helperBase = options.helperBase ?? DevShidenHelper;192193    super(logger, options);194    this.wait = new WaitGroup(this);195  }196}197198export class DevAcalaHelper extends AcalaHelper {199  wait: WaitGroup;200201  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {202    options.helperBase = options.helperBase ?? DevAcalaHelper;203204    super(logger, options);205    this.wait = new WaitGroup(this);206  }207}208209export class DevKaruraHelper extends DevAcalaHelper {}210211export class ArrangeGroup {212  helper: DevUniqueHelper;213214  scheduledIdSlider = 0;215216  constructor(helper: DevUniqueHelper) {217    this.helper = helper;218  }219220  /**221   * Generates accounts with the specified UNQ token balance222   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.223   * @param donor donor account for balances224   * @returns array of newly created accounts225   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor);226   */227  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {228    let nonce = await this.helper.chain.getNonce(donor.address);229    const wait = new WaitGroup(this.helper);230    const ss58Format = this.helper.chain.getChainProperties().ss58Format;231    const tokenNominal = this.helper.balance.getOneTokenNominal();232    const transactions = [];233    const accounts: IKeyringPair[] = [];234    for (const balance of balances) {235      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);236      accounts.push(recipient);237      if (balance !== 0n) {238        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);239        transactions.push(this.helper.signTransaction(donor, tx, {nonce, era: 0}, 'account generation'));240        nonce++;241      }242    }243244    await Promise.all(transactions).catch(_e => {});245246    //#region TODO remove this region, when nonce problem will be solved247    const checkBalances = async () => {248      let isSuccess = true;249      for (let i = 0; i < balances.length; i++) {250        const balance = await this.helper.balance.getSubstrate(accounts[i].address);251        if (balance !== balances[i] * tokenNominal) {252          isSuccess = false;253          break;254        }255      }256      return isSuccess;257    };258259    let accountsCreated = false;260    const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;261    // checkBalances retry up to 5-50 blocks262    for (let index = 0; index < maxBlocksChecked; index++) {263      accountsCreated = await checkBalances();264      if(accountsCreated) break;265      await wait.newBlocks(1);266    }267268    if (!accountsCreated) throw Error('Accounts generation failed');269    //#endregion270271    return accounts;272  };273274  // TODO combine this method and createAccounts into one275  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {276    const createAsManyAsCan = async () => {277      let transactions: any = [];278      const accounts: IKeyringPair[] = [];279      let nonce = await this.helper.chain.getNonce(donor.address);280      const tokenNominal = this.helper.balance.getOneTokenNominal();281      const ss58Format = this.helper.chain.getChainProperties().ss58Format;282      for (let i = 0; i < accountsToCreate; i++) {283        if (i === 500) { // if there are too many accounts to create284          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled285          transactions = []; //286          nonce = await this.helper.chain.getNonce(donor.address); // update nonce287        }288        const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);289        accounts.push(recipient);290        if (withBalance !== 0n) {291          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, withBalance * tokenNominal]);292          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));293          nonce++;294        }295      }296297      const fullfilledAccounts = [];298      await Promise.allSettled(transactions);299      for (const account of accounts) {300        const accountBalance = await this.helper.balance.getSubstrate(account.address);301        if (accountBalance === withBalance * tokenNominal) {302          fullfilledAccounts.push(account);303        }304      }305      return fullfilledAccounts;306    };307308309    const crowd: IKeyringPair[] = [];310    // do up to 5 retries311    for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {312      const asManyAsCan = await createAsManyAsCan();313      crowd.push(...asManyAsCan);314      accountsToCreate -= asManyAsCan.length;315    }316317    if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);318319    return crowd;320  };321322  isDevNode = async () => {323    let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();324    if (blockNumber == 0) {325      await this.helper.wait.newBlocks(1);326      blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();327    }328    const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])]);329    const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber - 1])]);330    const findCreationDate = (block: any) => {331      const humanBlock = block.toHuman();332      let date;333      humanBlock.block.extrinsics.forEach((ext: any) => {334        if(ext.method.section === 'timestamp') {335          date = Number(ext.method.args.now.replaceAll(',', ''));336        }337      });338      return date;339    };340    const block1date = await findCreationDate(block1);341    const block2date = await findCreationDate(block2);342    if(block2date! - block1date! < 9000) return true;343  };344345  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {346    const address = payer.Substrate ? payer.Substrate : this.helper.address.ethToSubstrate(payer.Ethereum!);347    let balance = await this.helper.balance.getSubstrate(address);348349    await promise();350351    balance -= await this.helper.balance.getSubstrate(address);352353    return balance;354  }355356  async calculatePoVInfo(txs: any[]): Promise<IPovInfo> {357    const rawPovInfo = await this.helper.callRpc('api.rpc.povinfo.estimateExtrinsicPoV', [txs]);358359    const kvJson: {[key: string]: string} = {};360361    for (const kv of rawPovInfo.keyValues) {362      kvJson[kv.key.toHex()] = kv.value.toHex();363    }364365    const kvStr = JSON.stringify(kvJson);366367    const chainql = spawnSync(368      'chainql',369      [370        `--tla-code=data=${kvStr}`,371        '-e', `function(data) cql.dump(cql.chain("${this.helper.getEndpoint()}").latest._meta, data, {omit_empty:true})`,372      ],373    );374375    if (!chainql.stdout) {376      throw Error('unable to get an output from the `chainql`');377    }378379    return {380      proofSize: rawPovInfo.proofSize.toNumber(),381      compactProofSize: rawPovInfo.compactProofSize.toNumber(),382      compressedProofSize: rawPovInfo.compressedProofSize.toNumber(),383      results: rawPovInfo.results,384      kv: JSON.parse(chainql.stdout.toString()),385    };386  }387388  calculatePalletAddress(palletId: any) {389    const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));390    return encodeAddress(address, this.helper.chain.getChainProperties().ss58Format);391  }392393  makeScheduledIds(num: number): string[] {394    function makeId(slider: number) {395      const scheduledIdSize = 64;396      const hexId = slider.toString(16);397      const prefixSize = scheduledIdSize - hexId.length;398399      const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;400401      return scheduledId;402    }403404    const ids = [];405    for (let i = 0; i < num; i++) {406      ids.push(makeId(this.scheduledIdSlider));407      this.scheduledIdSlider += 1;408    }409410    return ids;411  }412413  makeScheduledId(): string {414    return (this.makeScheduledIds(1))[0];415  }416417  async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {418    const capture = new EventCapture(this.helper, eventSection, eventMethod);419    await capture.startCapture();420421    return capture;422  }423424  makeXcmProgramWithdrawDeposit(beneficiary: Uint8Array, id: any, amount: bigint | string) {425    return {426      V2: [427        {428          WithdrawAsset: [429            {430              id,431              fun: {432                Fungible: amount,433              },434            },435          ],436        },437        {438          BuyExecution: {439            fees: {440              id,441              fun: {442                Fungible: amount,443              },444            },445            weightLimit: 'Unlimited'446          },447        },448        {449          DepositAsset: {450            assets: {451              Wild: 'All'452            },453            maxAssets: 1,454            beneficiary: {455              parents: 0,456              interior: {457                X1: {458                  AccountId32: {459                    network: 'Any',460                    id: beneficiary461                  },462                },463              },464            },465          },466        },467      ],468    };469  }470471  makeXcmProgramReserveAssetDeposited(beneficiary: Uint8Array, id: any, amount: bigint | string) {472    return {473      V2: [474        {475          ReserveAssetDeposited: [476            {477              id,478              fun: {479                Fungible: amount,480              },481            },482          ],483        },484        {485          BuyExecution: {486            fees: {487              id,488              fun: {489                Fungible: amount,490              },491            },492            weightLimit: 'Unlimited'493          },494        },495        {496          DepositAsset: {497            assets: {498              Wild: 'All'499            },500            maxAssets: 1,501            beneficiary: {502              parents: 0,503              interior: {504                X1: {505                  AccountId32: {506                    network: 'Any',507                    id: beneficiary508                  },509                },510              },511            },512          },513        },514      ],515    };516  }517}518519class MoonbeamAccountGroup {520  helper: MoonbeamHelper;521522  keyring: Keyring;523  _alithAccount: IKeyringPair;524  _baltatharAccount: IKeyringPair;525  _dorothyAccount: IKeyringPair;526527  constructor(helper: MoonbeamHelper) {528    this.helper = helper;529530    this.keyring = new Keyring({type: 'ethereum'});531    const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';532    const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';533    const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';534535    this._alithAccount = this.keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');536    this._baltatharAccount = this.keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');537    this._dorothyAccount = this.keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');538  }539540  alithAccount() {541    return this._alithAccount;542  }543544  baltatharAccount() {545    return this._baltatharAccount;546  }547548  dorothyAccount() {549    return this._dorothyAccount;550  }551552  create() {553    return this.keyring.addFromUri(mnemonicGenerate());554  }555}556557class WaitGroup {558  helper: ChainHelperBase;559560  constructor(helper: ChainHelperBase) {561    this.helper = helper;562  }563564  sleep(milliseconds: number) {565    return new Promise((resolve) => setTimeout(resolve, milliseconds));566  }567568  private async waitWithTimeout(promise: Promise<any>, timeout: number) {569    let isBlock = false;570    promise.then(() => isBlock = true).catch(() => isBlock = true);571    let totalTime = 0;572    const step = 100;573    while(!isBlock) {574      await this.sleep(step);575      totalTime += step;576      if(totalTime >= timeout) throw Error('Blocks production failed');577    }578    return promise;579  }580581  /**582   * Launch some async operation, or throw an error after some time. Note that it will still continue executing after the timeout.583   * @param promise async operation to race against the timeout584   * @param timeoutMS time after which to time out585   * @param timeoutError error message to throw586   * @returns promise of the same type the operation had587   */588  withTimeout<T>(589    promise: Promise<T>,590    timeoutMS = 30000,591    timeoutError = 'The operation has timed out!',592  ): Promise<T> {593    const timeout = new Promise<never>((_, reject) => {594      setTimeout(() => {595        reject(new Error(timeoutError));596      }, timeoutMS);597    });598599    return Promise.race<T>([promise, timeout]).catch(e => {throw new Error(e);});600  }601602  /**603   * Wait for specified number of blocks604   * @param blocksCount number of blocks to wait605   * @returns606   */607  async newBlocks(blocksCount = 1, timeout?: number): Promise<void> {608    timeout = timeout ?? blocksCount * 60_000;609    // eslint-disable-next-line no-async-promise-executor610    const promise = new Promise<void>(async (resolve) => {611      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {612        if (blocksCount > 0) {613          blocksCount--;614        } else {615          unsubscribe();616          resolve();617        }618      });619    });620    await this.waitWithTimeout(promise, timeout);621    return promise;622  }623624  /**625   * Wait for the specified number of sessions to pass.626   * Only applicable if the Session pallet is turned on.627   * @param sessionCount number of sessions to wait628   * @param blockTimeout time in ms until panicking that the chain has stopped producing blocks629   * @returns630   */631  async newSessions(sessionCount = 1, blockTimeout = 60000): Promise<void> {632    console.log(`Waiting for ${sessionCount} new session${sessionCount > 1 ? 's' : ''}.`633      + ' This might take a while -- check SessionPeriod in pallet_session::Config for session time.');634635    const expectedSessionIndex = await (this.helper as DevUniqueHelper).session.getIndex() + sessionCount;636    let currentSessionIndex = -1;637638    while (currentSessionIndex < expectedSessionIndex) {639      // eslint-disable-next-line no-async-promise-executor640      currentSessionIndex = await this.withTimeout(new Promise(async (resolve) => {641        await this.newBlocks(1);642        const res = await (this.helper as DevUniqueHelper).session.getIndex();643        resolve(res);644      }), blockTimeout, 'The chain has stopped producing blocks!');645    }646  }647648  async forParachainBlockNumber(blockNumber: bigint | number, timeout?: number) {649    timeout = timeout ?? 30 * 60 * 1000;650    // eslint-disable-next-line no-async-promise-executor651    const promise = new Promise<void>(async (resolve) => {652      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads((data: any) => {653        if (data.number.toNumber() >= blockNumber) {654          unsubscribe();655          resolve();656        }657      });658    });659    await this.waitWithTimeout(promise, timeout);660    return promise;661  }662663  async forRelayBlockNumber(blockNumber: bigint | number, timeout?: number) {664    timeout = timeout ?? 30 * 60 * 1000;665    // eslint-disable-next-line no-async-promise-executor666    const promise = new Promise<void>(async (resolve) => {667      const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData((data: any) => {668        if (data.value.relayParentNumber.toNumber() >= blockNumber) {669          // @ts-ignore670          unsubscribe();671          resolve();672        }673      });674    });675    await this.waitWithTimeout(promise, timeout);676    return promise;677  }678679  noScheduledTasks() {680    const api = this.helper.getApi();681682    // eslint-disable-next-line no-async-promise-executor683    const promise = new Promise<void>(async resolve => {684      const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {685        const areThereScheduledTasks = await api.query.scheduler.lookup.entries();686687        if(areThereScheduledTasks.length == 0) {688          unsubscribe();689          resolve();690        }691      });692    });693694    return promise;695  }696697  event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {698    // eslint-disable-next-line no-async-promise-executor699    const promise = new Promise<EventRecord | null>(async (resolve) => {700      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {701        const blockNumber = header.number.toHuman();702        const blockHash = header.hash;703        const eventIdStr = `${eventSection}.${eventMethod}`;704        const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;705706        this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);707708        const apiAt = await this.helper.getApi().at(blockHash);709        const eventRecords = (await apiAt.query.system.events()) as any;710711        const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {712          return r.event.section == eventSection && r.event.method == eventMethod;713        });714715        if (neededEvent) {716          unsubscribe();717          resolve(neededEvent);718        } else if (maxBlocksToWait > 0) {719          maxBlocksToWait--;720        } else {721          this.helper.logger.log(`Event \`${eventIdStr}\` is NOT found`);722          unsubscribe();723          resolve(null);724        }725      });726    });727    return promise;728  }729730  async eventOutcome<EventT>(maxBlocksToWait: number, eventSection: string, eventMethod: string) {731    const eventRecord = await this.event(maxBlocksToWait, eventSection, eventMethod);732733    if (eventRecord == null) {734      return null;735    }736737    const event = eventRecord!.event;738    const outcome = event.data[1] as EventT;739740    return outcome;741  }742}743744class SessionGroup {745  helper: ChainHelperBase;746747  constructor(helper: ChainHelperBase) {748    this.helper = helper;749  }750751  //todo:collator documentation752  async getIndex(): Promise<number> {753    return (await this.helper.callRpc('api.query.session.currentIndex')).toNumber();754  }755756  newSessions(sessionCount = 1, blockTimeout = 24000): Promise<void> {757    return (this.helper as DevUniqueHelper).wait.newSessions(sessionCount, blockTimeout);758  }759760  setOwnKeys(signer: TSigner, key: string) {761    return this.helper.executeExtrinsic(762      signer,763      'api.tx.session.setKeys',764      [key, '0x0'],765      true,766    );767  }768769  setOwnKeysFromAddress(signer: TSigner) {770    return this.setOwnKeys(signer, '0x' + Buffer.from(signer.addressRaw).toString('hex'));771  }772}773774class TestUtilGroup {775  helper: DevUniqueHelper;776777  constructor(helper: DevUniqueHelper) {778    this.helper = helper;779  }780781  async enable() {782    if (this.helper.fetchMissingPalletNames([Pallets.TestUtils]).length != 0) {783      return;784    }785786    const signer = this.helper.util.fromSeed('//Alice');787    await this.helper.getSudo<DevUniqueHelper>().executeExtrinsic(signer, 'api.tx.testUtils.enable', [], true);788  }789790  async setTestValue(signer: TSigner, testVal: number) {791    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValue', [testVal], true);792  }793794  async incTestValue(signer: TSigner) {795    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.incTestValue', [], true);796  }797798  async setTestValueAndRollback(signer: TSigner, testVal: number) {799    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValueAndRollback', [testVal], true);800  }801802  async testValue(blockIdx?: number) {803    const api = blockIdx804      ? await this.helper.getApi().at(await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockIdx]))805      : this.helper.getApi();806807    return (await api.query.testUtils.testValue()).toJSON();808  }809810  async justTakeFee(signer: TSigner) {811    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.justTakeFee', [], true);812  }813814  async selfCancelingInc(signer: TSigner, scheduledId: string, maxTestVal: number) {815    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.selfCancelingInc', [scheduledId, maxTestVal], true);816  }817}818819class EventCapture {820  helper: DevUniqueHelper;821  eventSection: string;822  eventMethod: string;823  events: EventRecord[] = [];824  unsubscribe: VoidFn | null = null;825826  constructor(827    helper: DevUniqueHelper,828    eventSection: string,829    eventMethod: string,830  ) {831    this.helper = helper;832    this.eventSection = eventSection;833    this.eventMethod = eventMethod;834  }835836  async startCapture() {837    this.stopCapture();838    this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {839      const newEvents = eventRecords.filter(r => {840        return r.event.section == this.eventSection && r.event.method == this.eventMethod;841      });842843      this.events.push(...newEvents);844    })) as any;845  }846847  stopCapture() {848    if (this.unsubscribe !== null) {849      this.unsubscribe();850    }851  }852853  extractCapturedEvents() {854    return this.events;855  }856}857858class AdminGroup {859  helper: UniqueHelper;860861  constructor(helper: UniqueHelper) {862    this.helper = helper;863  }864865  async payoutStakers(signer: IKeyringPair, stakersToPayout: number):  Promise<{staker: string, stake: bigint, payout: bigint}[]> {866    const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);867    return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {868      return {869        staker: e.event.data[0].toString(),870        stake: e.event.data[1].toBigInt(),871        payout: e.event.data[2].toBigInt(),872      };873    });874  }875}
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -3021,6 +3021,18 @@
 
     await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);
   }
+
+  async send(signer: IKeyringPair, destination: any, message: any) {
+    await this.helper.executeExtrinsic(
+      signer,
+      `api.tx.${this.palletName}.send`,
+      [
+        destination,
+        message,
+      ],
+      true,
+    ); 
+  }
 }
 
 class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {
@@ -3284,6 +3296,7 @@
   assetRegistry: AcalaAssetRegistryGroup;
   xTokens: XTokensGroup<AcalaHelper>;
   tokens: TokensGroup<AcalaHelper>;
+  xcm: XcmGroup<AcalaHelper>;
 
   constructor(logger?: ILogger, options: {[key: string]: any} = {}) {
     super(logger, options.helperBase ?? AcalaHelper);
@@ -3292,6 +3305,7 @@
     this.assetRegistry = new AcalaAssetRegistryGroup(this);
     this.xTokens = new XTokensGroup(this);
     this.tokens = new TokensGroup(this);
+    this.xcm = new XcmGroup(this, 'polkadotXcm');
   }
 
   getSudo<T extends AcalaHelper>() {
modifiedtests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth
--- a/tests/src/xcm/xcmQuartz.test.ts
+++ b/tests/src/xcm/xcmQuartz.test.ts
@@ -663,19 +663,20 @@
       },
     };
 
-    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, moreThanKaruraHas);
+    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 0,
+          interior: 'Here',
+        },
+      },
+      moreThanKaruraHas,
+    );
 
     // Try to trick Quartz
     await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
-      await helper.getSudo().executeExtrinsic(
-        alice,
-        'api.tx.polkadotXcm.send',
-        [
-          quartzMultilocation,
-          maliciousXcmProgram,
-        ],
-        true,
-      );
+      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);
     });
 
     const maxWaitBlocks = 3;
@@ -701,18 +702,19 @@
 
     // But Karura still can send the correct amount
     const validTransferAmount = karuraBalance / 2n;
-    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, validTransferAmount);
+    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 0,
+          interior: 'Here',
+        },
+      },
+      validTransferAmount,
+    );
 
     await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
-      await helper.getSudo().executeExtrinsic(
-        alice,
-        'api.tx.polkadotXcm.send',
-        [
-          quartzMultilocation,
-          validXcmProgram,
-        ],
-        true,
-      );
+      await helper.getSudo().xcm.send(alice, quartzMultilocation, validXcmProgram);
     });
 
     await helper.wait.newBlocks(maxWaitBlocks);
@@ -720,6 +722,62 @@
     targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
     expect(targetAccountBalance).to.be.equal(validTransferAmount);
   });
+
+  itSub('Should not accept reserve transfer of QTZ from Karura', async ({helper}) => {
+    const testAmount = 10_000n * (10n ** QTZ_DECIMALS);
+    const [targetAccount] = await helper.arrange.createAccounts([0n], alice);
+
+    const quartzMultilocation = {
+      V1: {
+        parents: 1,
+        interior: {
+          X1: {
+            Parachain: QUARTZ_CHAIN,
+          },
+        },
+      },
+    };
+
+    const maliciousXcmProgram = helper.arrange.makeXcmProgramReserveAssetDeposited(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 1,
+          interior: {
+            X1: {
+              Parachain: QUARTZ_CHAIN,
+            },
+          },
+        },
+      },
+      testAmount,
+    );
+
+    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
+      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);
+    });
+
+    const maxWaitBlocks = 3;
+
+    const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+      maxWaitBlocks,
+      'xcmpQueue',
+      'Fail',
+    );
+
+    expect(
+      xcmpQueueFailEvent != null,
+      `'xcmpQueue.FailEvent' event is expected`,
+    ).to.be.true;
+
+    expect(
+      xcmpQueueFailEvent!.isUntrustedReserveLocation,
+      `The XCM error should be 'isUntrustedReserveLocation'`,
+    ).to.be.true;
+
+    const accountBalance = await helper.balance.getSubstrate(targetAccount.address);
+    expect(accountBalance).to.be.equal(0n);
+  });
 });
 
 // These tests are relevant only when
@@ -1142,6 +1200,10 @@
   itSub.skip('Moonriver can send only up to its balance', async ({helper}) => {
     throw Error("Not yet implemented");
   });
+
+  itSub.skip('Should not accept reserve transfer of QTZ from Moonriver', async ({helper}) => {
+    throw Error("Not yet implemented");
+  });
 });
 
 describeXCM('[XCM] Integration test: Exchanging tokens with Shiden', () => {
@@ -1375,19 +1437,20 @@
       },
     };
 
-    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, moreThanShidenHas);
+    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 0,
+          interior: 'Here',
+        },
+      },
+      moreThanShidenHas,
+    );
 
     // Try to trick Quartz
     await usingShidenPlaygrounds(shidenUrl, async (helper) => {
-      await helper.getSudo().executeExtrinsic(
-        alice,
-        'api.tx.polkadotXcm.send',
-        [
-          quartzMultilocation,
-          maliciousXcmProgram,
-        ],
-        true,
-      );
+      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);
     });
 
     const maxWaitBlocks = 3;
@@ -1413,18 +1476,19 @@
 
     // But Shiden still can send the correct amount
     const validTransferAmount = shidenBalance / 2n;
-    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, validTransferAmount);
+    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 0,
+          interior: 'Here',
+        },
+      },
+      validTransferAmount,
+    );
 
     await usingShidenPlaygrounds(shidenUrl, async (helper) => {
-      await helper.getSudo().executeExtrinsic(
-        alice,
-        'api.tx.polkadotXcm.send',
-        [
-          quartzMultilocation,
-          validXcmProgram,
-        ],
-        true,
-      );
+      await helper.getSudo().xcm.send(alice, quartzMultilocation, validXcmProgram);
     });
 
     await helper.wait.newBlocks(maxWaitBlocks);
@@ -1432,4 +1496,60 @@
     targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
     expect(targetAccountBalance).to.be.equal(validTransferAmount);
   });
+
+  itSub('Should not accept reserve transfer of QTZ from Shiden', async ({helper}) => {
+    const testAmount = 10_000n * (10n ** QTZ_DECIMALS);
+    const [targetAccount] = await helper.arrange.createAccounts([0n], alice);
+
+    const quartzMultilocation = {
+      V1: {
+        parents: 1,
+        interior: {
+          X1: {
+            Parachain: QUARTZ_CHAIN,
+          },
+        },
+      },
+    };
+
+    const maliciousXcmProgram = helper.arrange.makeXcmProgramReserveAssetDeposited(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 1,
+          interior: {
+            X1: {
+              Parachain: QUARTZ_CHAIN,
+            },
+          },
+        },
+      },
+      testAmount,
+    );
+
+    await usingShidenPlaygrounds(shidenUrl, async (helper) => {
+      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);
+    });
+
+    const maxWaitBlocks = 3;
+
+    const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+      maxWaitBlocks,
+      'xcmpQueue',
+      'Fail',
+    );
+
+    expect(
+      xcmpQueueFailEvent != null,
+      `'xcmpQueue.FailEvent' event is expected`,
+    ).to.be.true;
+
+    expect(
+      xcmpQueueFailEvent!.isUntrustedReserveLocation,
+      `The XCM error should be 'isUntrustedReserveLocation'`,
+    ).to.be.true;
+
+    const accountBalance = await helper.balance.getSubstrate(targetAccount.address);
+    expect(accountBalance).to.be.equal(0n);
+  });
 });
modifiedtests/src/xcm/xcmUnique.test.tsdiffbeforeafterboth
--- a/tests/src/xcm/xcmUnique.test.ts
+++ b/tests/src/xcm/xcmUnique.test.ts
@@ -665,19 +665,20 @@
       },
     };
 
-    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, moreThanAcalaHas);
+    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 0,
+          interior: 'Here',
+        },
+      },
+      moreThanAcalaHas,
+    );
 
     // Try to trick Unique
     await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
-      await helper.getSudo().executeExtrinsic(
-        alice,
-        'api.tx.polkadotXcm.send',
-        [
-          uniqueMultilocation,
-          maliciousXcmProgram,
-        ],
-        true,
-      );
+      await helper.getSudo().xcm.send(alice, uniqueMultilocation, maliciousXcmProgram);
     });
 
     const maxWaitBlocks = 3;
@@ -703,18 +704,19 @@
 
     // But Acala still can send the correct amount
     const validTransferAmount = acalaBalance / 2n;
-    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, validTransferAmount);
+    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 0,
+          interior: 'Here',
+        },
+      },
+      validTransferAmount,
+    );
 
     await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
-      await helper.getSudo().executeExtrinsic(
-        alice,
-        'api.tx.polkadotXcm.send',
-        [
-          uniqueMultilocation,
-          validXcmProgram,
-        ],
-        true,
-      );
+      await helper.getSudo().xcm.send(alice, uniqueMultilocation, validXcmProgram);
     });
 
     await helper.wait.newBlocks(maxWaitBlocks);
@@ -722,6 +724,62 @@
     targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
     expect(targetAccountBalance).to.be.equal(validTransferAmount);
   });
+
+  itSub('Should not accept reserve transfer of UNQ from Acala', async ({helper}) => {
+    const testAmount = 10_000n * (10n ** UNQ_DECIMALS);
+    const [targetAccount] = await helper.arrange.createAccounts([0n], alice);
+
+    const uniqueMultilocation = {
+      V1: {
+        parents: 1,
+        interior: {
+          X1: {
+            Parachain: UNIQUE_CHAIN,
+          },
+        },
+      },
+    };
+
+    const maliciousXcmProgram = helper.arrange.makeXcmProgramReserveAssetDeposited(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 1,
+          interior: {
+            X1: {
+              Parachain: UNIQUE_CHAIN,
+            },
+          },
+        },
+      },
+      testAmount,
+    );
+
+    await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
+      await helper.getSudo().xcm.send(alice, uniqueMultilocation, maliciousXcmProgram);
+    });
+
+    const maxWaitBlocks = 3;
+
+    const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+      maxWaitBlocks,
+      'xcmpQueue',
+      'Fail',
+    );
+
+    expect(
+      xcmpQueueFailEvent != null,
+      `'xcmpQueue.FailEvent' event is expected`,
+    ).to.be.true;
+
+    expect(
+      xcmpQueueFailEvent!.isUntrustedReserveLocation,
+      `The XCM error should be 'isUntrustedReserveLocation'`,
+    ).to.be.true;
+
+    const accountBalance = await helper.balance.getSubstrate(targetAccount.address);
+    expect(accountBalance).to.be.equal(0n);
+  });
 });
 
 // These tests are relevant only when
@@ -1145,6 +1203,10 @@
   itSub.skip('Moonbeam can send only up to its balance', async ({helper}) => {
     throw Error("Not yet implemented");
   });
+
+  itSub.skip('Should not accept reserve transfer of UNQ from Moonbeam', async ({helper}) => {
+    throw Error("Not yet implemented");
+  });
 });
 
 describeXCM('[XCM] Integration test: Exchanging tokens with Astar', () => {
@@ -1356,63 +1418,7 @@
     console.log(`UNQ Balance on Unique after XCM is: ${balanceUNQ}`);
     expect(balanceUNQ).to.eq(balanceAfterUniqueToAstarXCM + unqFromAstarTransfered);
   });
-
-  itSub.skip('Should not accept limitedReserveTransfer of UNQ from ASTAR', async ({helper}) => {
-    await usingAstarPlaygrounds(astarUrl, async (helper) => {
-      const destination = {
-        V1: {
-          parents: 1,
-          interior: {
-            X1: {
-              Parachain: UNIQUE_CHAIN,
-            },
-          },
-        },
-      };
-
-      const beneficiary = {
-        V1: {
-          parents: 0,
-          interior: {
-            X1: {
-              AccountId32: {
-                network: 'Any',
-                id: randomAccount.addressRaw,
-              },
-            },
-          },
-        },
-      };
 
-      const assets = {
-        V1: [
-          {
-            id: {
-              Concrete: {
-                parents: 1,
-                interior: {
-                  X1: {
-                    Parachain: UNIQUE_CHAIN,
-                  },
-                },
-              },
-            },
-            fun: {
-              Fungible: unqFromAstarTransfered,
-            },
-          },
-        ],
-      };
-
-      // Initial balance is 1 ASTAR
-      expect(await helper.balance.getSubstrate(randomAccount.address)).to.eq(astarInitialBalance);
-
-      const feeAssetItem = 0;
-      // TODO: expect rejected:
-      await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');
-    });
-  });
-
   itSub('Astar can send only up to its balance', async ({helper}) => {
     // set Astar's sovereign account's balance
     const astarBalance = 10000n * (10n ** UNQ_DECIMALS);
@@ -1433,19 +1439,20 @@
       },
     };
 
-    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, moreThanShidenHas);
+    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 0,
+          interior: 'Here',
+        },
+      },
+      moreThanShidenHas,
+    );
 
     // Try to trick Unique
     await usingAstarPlaygrounds(astarUrl, async (helper) => {
-      await helper.getSudo().executeExtrinsic(
-        alice,
-        'api.tx.polkadotXcm.send',
-        [
-          uniqueMultilocation,
-          maliciousXcmProgram,
-        ],
-        true,
-      );
+      await helper.getSudo().xcm.send(alice, uniqueMultilocation, maliciousXcmProgram);
     });
 
     const maxWaitBlocks = 3;
@@ -1471,18 +1478,19 @@
 
     // But Astar still can send the correct amount
     const validTransferAmount = astarBalance / 2n;
-    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, validTransferAmount);
+    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 0,
+          interior: 'Here',
+        },
+      },
+      validTransferAmount,
+    );
 
     await usingAstarPlaygrounds(astarUrl, async (helper) => {
-      await helper.getSudo().executeExtrinsic(
-        alice,
-        'api.tx.polkadotXcm.send',
-        [
-          uniqueMultilocation,
-          validXcmProgram,
-        ],
-        true,
-      );
+      await helper.getSudo().xcm.send(alice, uniqueMultilocation, validXcmProgram);
     });
 
     await helper.wait.newBlocks(maxWaitBlocks);
@@ -1490,4 +1498,61 @@
     targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
     expect(targetAccountBalance).to.be.equal(validTransferAmount);
   });
+
+  itSub('Should not accept reserve transfer of UNQ from Astar', async ({helper}) => {
+    const testAmount = 10_000n * (10n ** UNQ_DECIMALS);
+    const [targetAccount] = await helper.arrange.createAccounts([0n], alice);
+
+    const uniqueMultilocation = {
+      V1: {
+        parents: 1,
+        interior: {
+          X1: {
+            Parachain: UNIQUE_CHAIN,
+          },
+        },
+      },
+    };
+
+    const maliciousXcmProgram = helper.arrange.makeXcmProgramReserveAssetDeposited(
+      targetAccount.addressRaw,
+      {
+        Concrete: {
+          parents: 1,
+          interior: {
+            X1: {
+              Parachain: UNIQUE_CHAIN,
+            },
+          },
+        },
+      },
+      testAmount,
+    );
+
+    await usingAstarPlaygrounds(astarUrl, async (helper) => {
+      await helper.getSudo().xcm.send(alice, uniqueMultilocation, maliciousXcmProgram);
+    });
+
+    const maxWaitBlocks = 3;
+
+    const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(
+      maxWaitBlocks,
+      'xcmpQueue',
+      'Fail',
+    );
+
+    expect(
+      xcmpQueueFailEvent != null,
+      `'xcmpQueue.FailEvent' event is expected`,
+    ).to.be.true;
+
+    expect(
+      xcmpQueueFailEvent!.isUntrustedReserveLocation,
+      `The XCM error should be 'isUntrustedReserveLocation'`,
+    ).to.be.true;
+
+    const accountBalance = await helper.balance.getSubstrate(targetAccount.address);
+    expect(accountBalance).to.be.equal(0n);
+  });
+
 });