git.delta.rocks / unique-network / refs/commits / 0f67e15c3f4a

difftreelog

test relay does root ops

Daniel Shiposha2023-09-28parent: #f61ec5a.patch.diff
in: master

3 files changed

modifiedtests/src/xcm/lowLevelXcmQuartz.test.tsdiffbeforeafterboth
--- a/tests/src/xcm/lowLevelXcmQuartz.test.ts
+++ b/tests/src/xcm/lowLevelXcmQuartz.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {IKeyringPair} from '@polkadot/types/types';
-import {itSub, expect, describeXCM, usingPlaygrounds, usingKaruraPlaygrounds,  usingMoonriverPlaygrounds, usingShidenPlaygrounds} from '../util';
+import {itSub, expect, describeXCM, usingPlaygrounds, usingKaruraPlaygrounds,  usingMoonriverPlaygrounds, usingShidenPlaygrounds, usingRelayPlaygrounds} from '../util';
 import {DevUniqueHelper, Event} from '../util/playgrounds/unique.dev';
 import {STATEMINE_CHAIN, QUARTZ_CHAIN, KARURA_CHAIN, MOONRIVER_CHAIN, SHIDEN_CHAIN, STATEMINE_DECIMALS, KARURA_DECIMALS, QTZ_DECIMALS, RELAY_DECIMALS, SHIDEN_DECIMALS, karuraUrl, moonriverUrl, relayUrl, shidenUrl, statemineUrl, SAFE_XCM_VERSION, XcmTestHelper, TRANSFER_AMOUNT} from './xcm.types';
 
@@ -379,3 +379,67 @@
     await testHelper.reserveTransferUNQfrom('shiden', alice);
   });
 });
+
+describeXCM('[XCMLL] Integration test: The relay can do some root ops', () => {
+  let sudoer: IKeyringPair;
+
+  before(async function () {
+    await usingRelayPlaygrounds(relayUrl, async (_, privateKey) => {
+      sudoer = await privateKey('//Alice');
+    });
+  });
+
+  // At the moment there is no reliable way
+  // to establish the correspondence between the `ExecutedDownward` event
+  // and the relay's sent message due to `SetTopic` instruction
+  // containing an unpredictable topic silently added by the relay on the router level.
+  // This changes the message hash on arrival to our chain.
+  //
+  // See:
+  // * The relay's router: https://github.com/paritytech/polkadot-sdk/blob/f60318f68687e601c47de5ad5ca88e2c3f8139a7/polkadot/runtime/westend/src/xcm_config.rs#L83
+  // * The `WithUniqueTopic` helper: https://github.com/paritytech/polkadot-sdk/blob/945ebbbcf66646be13d5b1d1bc26c8b0d3296d9e/polkadot/xcm/xcm-builder/src/routing.rs#L36
+  //
+  // Because of this, we insert time gaps between tests so
+  // different `ExecutedDownward` events won't interfere with each other.
+  afterEach(async () => {
+    await usingPlaygrounds(async (helper) => {
+      await helper.wait.newBlocks(3);
+    });
+  });
+
+  itSub('The relay can set storage', async () => {
+    await testHelper.relayIsPermittedToSetStorage(sudoer, 'plain');
+  });
+
+  itSub('The relay can batch set storage', async () => {
+    await testHelper.relayIsPermittedToSetStorage(sudoer, 'batch');
+  });
+
+  itSub('The relay can batchAll set storage', async () => {
+    await testHelper.relayIsPermittedToSetStorage(sudoer, 'batchAll');
+  });
+
+  itSub('The relay can forceBatch set storage', async () => {
+    await testHelper.relayIsPermittedToSetStorage(sudoer, 'forceBatch');
+  });
+
+  itSub('[negative] The relay cannot set balance', async () => {
+    await testHelper.relayIsNotPermittedToSetBalance(sudoer, 'plain');
+  });
+
+  itSub('[negative] The relay cannot set balance via batch', async () => {
+    await testHelper.relayIsNotPermittedToSetBalance(sudoer, 'batch');
+  });
+
+  itSub('[negative] The relay cannot set balance via batchAll', async () => {
+    await testHelper.relayIsNotPermittedToSetBalance(sudoer, 'batchAll');
+  });
+
+  itSub('[negative] The relay cannot set balance via forceBatch', async () => {
+    await testHelper.relayIsNotPermittedToSetBalance(sudoer, 'forceBatch');
+  });
+
+  itSub('[negative] The relay cannot set balance via dispatchAs', async () => {
+    await testHelper.relayIsNotPermittedToSetBalance(sudoer, 'dispatchAs');
+  });
+});
modifiedtests/src/xcm/lowLevelXcmUnique.test.tsdiffbeforeafterboth
--- a/tests/src/xcm/lowLevelXcmUnique.test.ts
+++ b/tests/src/xcm/lowLevelXcmUnique.test.ts
@@ -16,11 +16,11 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import config from '../config';
-import {itSub, expect, describeXCM, usingPlaygrounds, usingAcalaPlaygrounds, usingMoonbeamPlaygrounds, usingAstarPlaygrounds, usingPolkadexPlaygrounds} from '../util';
+import {itSub, expect, describeXCM, usingPlaygrounds, usingAcalaPlaygrounds, usingMoonbeamPlaygrounds, usingAstarPlaygrounds, usingPolkadexPlaygrounds, usingRelayPlaygrounds, requirePalletsOrSkip, Pallets} from '../util';
 import {Event} from '../util/playgrounds/unique.dev';
 import {nToBigInt} from '@polkadot/util';
 import {hexToString} from '@polkadot/util';
-import {ASTAR_DECIMALS, NETWORKS, SAFE_XCM_VERSION, UNIQUE_CHAIN, UNQ_DECIMALS, XcmTestHelper, acalaUrl, astarUrl, expectFailedToTransact, expectUntrustedReserveLocationFail, getDevPlayground, mapToChainId, mapToChainUrl, maxWaitBlocks, moonbeamUrl, polkadexUrl, uniqueAssetId, uniqueVersionedMultilocation} from './xcm.types';
+import {ASTAR_DECIMALS, NETWORKS, SAFE_XCM_VERSION, UNIQUE_CHAIN, UNQ_DECIMALS, XcmTestHelper, acalaUrl, astarUrl, expectFailedToTransact, expectUntrustedReserveLocationFail, getDevPlayground, mapToChainId, mapToChainUrl, maxWaitBlocks, moonbeamUrl, polkadexUrl, relayUrl, uniqueAssetId, uniqueVersionedMultilocation} from './xcm.types';
 
 
 const TRANSFER_AMOUNT = 2000000_000_000_000_000_000_000n;
@@ -672,3 +672,67 @@
     await genericReserveTransferUNQfrom('astar', alice);
   });
 });
+
+describeXCM('[XCMLL] Integration test: The relay can do some root ops', () => {
+  let sudoer: IKeyringPair;
+
+  before(async function () {
+    await usingRelayPlaygrounds(relayUrl, async (_, privateKey) => {
+      sudoer = await privateKey('//Alice');
+    });
+  });
+
+  // At the moment there is no reliable way
+  // to establish the correspondence between the `ExecutedDownward` event
+  // and the relay's sent message due to `SetTopic` instruction
+  // containing an unpredictable topic silently added by the relay on the router level.
+  // This changes the message hash on arrival to our chain.
+  //
+  // See:
+  // * The relay's router: https://github.com/paritytech/polkadot-sdk/blob/f60318f68687e601c47de5ad5ca88e2c3f8139a7/polkadot/runtime/westend/src/xcm_config.rs#L83
+  // * The `WithUniqueTopic` helper: https://github.com/paritytech/polkadot-sdk/blob/945ebbbcf66646be13d5b1d1bc26c8b0d3296d9e/polkadot/xcm/xcm-builder/src/routing.rs#L36
+  //
+  // Because of this, we insert time gaps between tests so
+  // different `ExecutedDownward` events won't interfere with each other.
+  afterEach(async () => {
+    await usingPlaygrounds(async (helper) => {
+      await helper.wait.newBlocks(3);
+    });
+  });
+
+  itSub('The relay can set storage', async () => {
+    await testHelper.relayIsPermittedToSetStorage(sudoer, 'plain');
+  });
+
+  itSub('The relay can batch set storage', async () => {
+    await testHelper.relayIsPermittedToSetStorage(sudoer, 'batch');
+  });
+
+  itSub('The relay can batchAll set storage', async () => {
+    await testHelper.relayIsPermittedToSetStorage(sudoer, 'batchAll');
+  });
+
+  itSub('The relay can forceBatch set storage', async () => {
+    await testHelper.relayIsPermittedToSetStorage(sudoer, 'forceBatch');
+  });
+
+  itSub('[negative] The relay cannot set balance', async () => {
+    await testHelper.relayIsNotPermittedToSetBalance(sudoer, 'plain');
+  });
+
+  itSub('[negative] The relay cannot set balance via batch', async () => {
+    await testHelper.relayIsNotPermittedToSetBalance(sudoer, 'batch');
+  });
+
+  itSub('[negative] The relay cannot set balance via batchAll', async () => {
+    await testHelper.relayIsNotPermittedToSetBalance(sudoer, 'batchAll');
+  });
+
+  itSub('[negative] The relay cannot set balance via forceBatch', async () => {
+    await testHelper.relayIsNotPermittedToSetBalance(sudoer, 'forceBatch');
+  });
+
+  itSub('[negative] The relay cannot set balance via dispatchAs', async () => {
+    await testHelper.relayIsNotPermittedToSetBalance(sudoer, 'dispatchAs');
+  });
+});
modifiedtests/src/xcm/xcm.types.tsdiffbeforeafterboth
before · tests/src/xcm/xcm.types.ts
1import {IKeyringPair} from '@polkadot/types/types';2import {expect, usingAcalaPlaygrounds, usingAstarPlaygrounds, usingKaruraPlaygrounds, usingMoonbeamPlaygrounds, usingMoonriverPlaygrounds, usingPlaygrounds, usingPolkadexPlaygrounds, usingShidenPlaygrounds} from '../util';3import {DevUniqueHelper, Event} from '../util/playgrounds/unique.dev';4import config from '../config';56export const UNIQUE_CHAIN = +(process.env.RELAY_UNIQUE_ID || 2037);7export const STATEMINT_CHAIN = +(process.env.RELAY_STATEMINT_ID || 1000);8export const ACALA_CHAIN = +(process.env.RELAY_ACALA_ID || 2000);9export const MOONBEAM_CHAIN = +(process.env.RELAY_MOONBEAM_ID || 2004);10export const ASTAR_CHAIN = +(process.env.RELAY_ASTAR_ID || 2006);11export const POLKADEX_CHAIN = +(process.env.RELAY_POLKADEX_ID || 2040);1213export const QUARTZ_CHAIN = +(process.env.RELAY_QUARTZ_ID || 2095);14export const STATEMINE_CHAIN = +(process.env.RELAY_STATEMINE_ID || 1000);15export const KARURA_CHAIN = +(process.env.RELAY_KARURA_ID || 2000);16export const MOONRIVER_CHAIN = +(process.env.RELAY_MOONRIVER_ID || 2023);17export const SHIDEN_CHAIN = +(process.env.RELAY_SHIDEN_ID || 2007);1819export const relayUrl = config.relayUrl;20export const statemintUrl = config.statemintUrl;21export const statemineUrl = config.statemineUrl;2223export const acalaUrl = config.acalaUrl;24export const moonbeamUrl = config.moonbeamUrl;25export const astarUrl = config.astarUrl;26export const polkadexUrl = config.polkadexUrl;2728export const karuraUrl = config.karuraUrl;29export const moonriverUrl = config.moonriverUrl;30export const shidenUrl = config.shidenUrl;3132export const SAFE_XCM_VERSION = 3;333435export const RELAY_DECIMALS = 12;36export const STATEMINE_DECIMALS = 12;37export const KARURA_DECIMALS = 12;38export const SHIDEN_DECIMALS = 18n;39export const QTZ_DECIMALS = 18n;4041export const ASTAR_DECIMALS = 18n;42export const UNQ_DECIMALS = 18n;4344export const maxWaitBlocks = 6;4546export const uniqueMultilocation = {47  parents: 1,48  interior: {49    X1: {50      Parachain: UNIQUE_CHAIN,51    },52  },53};54export const uniqueVersionedMultilocation = {55  V3: uniqueMultilocation,56};5758export const uniqueAssetId = {59  Concrete: uniqueMultilocation,60};6162export const expectFailedToTransact = async (helper: DevUniqueHelper, messageSent: any) => {63  await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash64        && event.outcome.isFailedToTransactAsset);65};66export const expectUntrustedReserveLocationFail = async (helper: DevUniqueHelper, messageSent: any) => {67  await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash68         && event.outcome.isUntrustedReserveLocation);69};7071export const NETWORKS = {72  acala: usingAcalaPlaygrounds,73  astar: usingAstarPlaygrounds,74  polkadex: usingPolkadexPlaygrounds,75  moonbeam: usingMoonbeamPlaygrounds,76  moonriver: usingMoonriverPlaygrounds,77  karura: usingKaruraPlaygrounds,78  shiden: usingShidenPlaygrounds,79} as const;80type NetworkNames = keyof typeof NETWORKS;8182type NativeRuntime = 'opal' | 'quartz' | 'unique';8384export function mapToChainId(networkName: keyof typeof NETWORKS): number {85  switch (networkName) {86    case 'acala':87      return ACALA_CHAIN;88    case 'astar':89      return ASTAR_CHAIN;90    case 'moonbeam':91      return MOONBEAM_CHAIN;92    case 'polkadex':93      return POLKADEX_CHAIN;94    case 'moonriver':95      return MOONRIVER_CHAIN;96    case 'karura':97      return KARURA_CHAIN;98    case 'shiden':99      return SHIDEN_CHAIN;100  }101}102103export function mapToChainUrl(networkName: NetworkNames): string {104  switch (networkName) {105    case 'acala':106      return acalaUrl;107    case 'astar':108      return astarUrl;109    case 'moonbeam':110      return moonbeamUrl;111    case 'polkadex':112      return polkadexUrl;113    case 'moonriver':114      return moonriverUrl;115    case 'karura':116      return karuraUrl;117    case 'shiden':118      return shidenUrl;119  }120}121122export function getDevPlayground(name: NetworkNames) {123  return NETWORKS[name];124}125126export const TRANSFER_AMOUNT = 2000000_000_000_000_000_000_000n;127const SENDER_BUDGET = 2n * TRANSFER_AMOUNT;128const SENDBACK_AMOUNT = TRANSFER_AMOUNT / 2n;129const STAYED_ON_TARGET_CHAIN = TRANSFER_AMOUNT - SENDBACK_AMOUNT;130const TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT = 100_000_000_000n;131132export class XcmTestHelper {133  private _balanceUniqueTokenInit: bigint = 0n;134  private _balanceUniqueTokenMiddle: bigint = 0n;135  private _balanceUniqueTokenFinal: bigint = 0n;136  private _unqFees: bigint = 0n;137  private _nativeRuntime: NativeRuntime;138139  constructor(runtime: NativeRuntime) {140    this._nativeRuntime = runtime;141  }142143  private _getNativeId() {144    switch (this._nativeRuntime) {145      case 'opal':146        // To-Do147        return 10;148      case 'quartz':149        return QUARTZ_CHAIN;150      case 'unique':151        return UNIQUE_CHAIN;152    }153  }154  private _isAddress20FormatFor(network: NetworkNames) {155    switch (network) {156      case 'moonbeam':157      case 'moonriver':158        return true;159      default:160        return false;161    }162  }163164  async sendUnqTo(165    networkName: keyof typeof NETWORKS,166    randomAccount: IKeyringPair,167    randomAccountOnTargetChain = randomAccount,168  ) {169    const networkUrl = mapToChainUrl(networkName);170    const targetPlayground = getDevPlayground(networkName);171    await usingPlaygrounds(async (helper) => {172      this._balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);173      const destination = {174        V2: {175          parents: 1,176          interior: {177            X1: {178              Parachain: mapToChainId(networkName),179            },180          },181        },182      };183184      const beneficiary = {185        V2: {186          parents: 0,187          interior: {188            X1: (189              this._isAddress20FormatFor(networkName) ?190                {191                  AccountKey20: {192                    network: 'Any',193                    key: randomAccountOnTargetChain.address,194                  },195                }196                :197                {198                  AccountId32: {199                    network: 'Any',200                    id: randomAccountOnTargetChain.addressRaw,201                  },202                }203            ),204          },205        },206      };207208      const assets = {209        V2: [210          {211            id: {212              Concrete: {213                parents: 0,214                interior: 'Here',215              },216            },217            fun: {218              Fungible: TRANSFER_AMOUNT,219            },220          },221        ],222      };223      const feeAssetItem = 0;224225      await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');226      const messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);227      this._balanceUniqueTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);228229      this._unqFees = this._balanceUniqueTokenInit - this._balanceUniqueTokenMiddle - TRANSFER_AMOUNT;230      console.log('[Unique -> %s] transaction fees on Unique: %s UNQ', networkName, helper.util.bigIntToDecimals(this._unqFees));231      expect(this._unqFees > 0n, 'Negative fees UNQ, looks like nothing was transferred').to.be.true;232233      await targetPlayground(networkUrl, async (helper) => {234      /*235        Since only the parachain part of the Polkadex236        infrastructure is launched (without their237        solochain validators), processing incoming238        assets will lead to an error.239        This error indicates that the Polkadex chain240        received a message from the Unique network,241        since the hash is being checked to ensure242        it matches what was sent.243      */244        if(networkName == 'polkadex') {245          await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash);246        } else {247          await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == messageSent.messageHash);248        }249      });250251    });252  }253254  async sendUnqBack(255    networkName: keyof typeof NETWORKS,256    sudoer: IKeyringPair,257    randomAccountOnUnq: IKeyringPair,258  ) {259    const networkUrl = mapToChainUrl(networkName);260261    const targetPlayground = getDevPlayground(networkName);262    await usingPlaygrounds(async (helper) => {263264      const xcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(265        randomAccountOnUnq.addressRaw,266        {267          Concrete: {268            parents: 1,269            interior: {270              X1: {Parachain: this._getNativeId()},271            },272          },273        },274        SENDBACK_AMOUNT,275      );276277      let xcmProgramSent: any;278279280      await targetPlayground(networkUrl, async (helper) => {281        if('getSudo' in helper) {282          await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, xcmProgram);283          xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);284        } else if('fastDemocracy' in helper) {285          const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, xcmProgram]);286          // Needed to bypass the call filter.287          const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);288          await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);289          xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);290        }291      });292293      await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == xcmProgramSent.messageHash);294295      this._balanceUniqueTokenFinal = await helper.balance.getSubstrate(randomAccountOnUnq.address);296297      expect(this._balanceUniqueTokenFinal).to.be.equal(this._balanceUniqueTokenInit - this._unqFees - STAYED_ON_TARGET_CHAIN);298299    });300  }301302  async sendOnlyOwnedBalance(303    networkName: keyof typeof NETWORKS,304    sudoer: IKeyringPair,305  ) {306    const networkUrl = mapToChainUrl(networkName);307    const targetPlayground = getDevPlayground(networkName);308309    const targetChainBalance = 10000n * (10n ** UNQ_DECIMALS);310311    await usingPlaygrounds(async (helper) => {312      const targetChainSovereignAccount = helper.address.paraSiblingSovereignAccount(mapToChainId(networkName));313      await helper.getSudo().balance.setBalanceSubstrate(sudoer, targetChainSovereignAccount, targetChainBalance);314      const moreThanTargetChainHas = 2n * targetChainBalance;315316      const targetAccount = helper.arrange.createEmptyAccount();317318      const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(319        targetAccount.addressRaw,320        {321          Concrete: {322            parents: 0,323            interior: 'Here',324          },325        },326        moreThanTargetChainHas,327      );328329      let maliciousXcmProgramSent: any;330331332      await targetPlayground(networkUrl, async (helper) => {333        if('getSudo' in helper) {334          await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgram);335          maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);336        } else if('fastDemocracy' in helper) {337          const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgram]);338          // Needed to bypass the call filter.339          const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);340          await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);341          maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);342        }343      });344345      await expectFailedToTransact(helper, maliciousXcmProgramSent);346347      const targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);348      expect(targetAccountBalance).to.be.equal(0n);349    });350  }351352  async reserveTransferUNQfrom(netwokrName: keyof typeof NETWORKS, sudoer: IKeyringPair) {353    const networkUrl = mapToChainUrl(netwokrName);354    const targetPlayground = getDevPlayground(netwokrName);355356    await usingPlaygrounds(async (helper) => {357      const testAmount = 10_000n * (10n ** UNQ_DECIMALS);358      const targetAccount = helper.arrange.createEmptyAccount();359360      const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(361        targetAccount.addressRaw,362        {363          Concrete: {364            parents: 1,365            interior: {366              X1: {367                Parachain: this._getNativeId(),368              },369            },370          },371        },372        testAmount,373      );374375      const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(376        targetAccount.addressRaw,377        {378          Concrete: {379            parents: 0,380            interior: 'Here',381          },382        },383        testAmount,384      );385386      let maliciousXcmProgramFullIdSent: any;387      let maliciousXcmProgramHereIdSent: any;388      const maxWaitBlocks = 3;389390      // Try to trick Unique using full UNQ identification391      await targetPlayground(networkUrl, async (helper) => {392        if('getSudo' in helper) {393          await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgramFullId);394          maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);395        }396        // Moonbeam case397        else if('fastDemocracy' in helper) {398          const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramFullId]);399          // Needed to bypass the call filter.400          const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);401          await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using path asset identification`,batchCall);402403          maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);404        }405      });406407408      await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramFullIdSent);409410      let accountBalance = await helper.balance.getSubstrate(targetAccount.address);411      expect(accountBalance).to.be.equal(0n);412413      // Try to trick Unique using shortened UNQ identification414      await targetPlayground(networkUrl, async (helper) => {415        if('getSudo' in helper) {416          await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgramHereId);417          maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);418        }419        else if('fastDemocracy' in helper) {420          const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramHereId]);421          // Needed to bypass the call filter.422          const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);423          await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using "here" asset identification`, batchCall);424425          maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);426        }427      });428429      await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramHereIdSent);430431      accountBalance = await helper.balance.getSubstrate(targetAccount.address);432      expect(accountBalance).to.be.equal(0n);433    });434  }435436  async rejectNativeTokensFrom(networkName: keyof typeof NETWORKS, sudoerOnTargetChain: IKeyringPair) {437    const networkUrl = mapToChainUrl(networkName);438    const targetPlayground = getDevPlayground(networkName);439    let messageSent: any;440441    await usingPlaygrounds(async (helper) => {442      const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(443        helper.arrange.createEmptyAccount().addressRaw,444        {445          Concrete: {446            parents: 1,447            interior: {448              X1: {449                Parachain: mapToChainId(networkName),450              },451            },452          },453        },454        TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT,455      );456      await targetPlayground(networkUrl, async (helper) => {457        if('getSudo' in helper) {458          await helper.getSudo().xcm.send(sudoerOnTargetChain, uniqueVersionedMultilocation, maliciousXcmProgramFullId);459          messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);460        } else if('fastDemocracy' in helper) {461          const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramFullId]);462          // Needed to bypass the call filter.463          const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);464          await helper.fastDemocracy.executeProposal(`${networkName} sending native tokens to the Unique via fast democracy`, batchCall);465466          messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);467        }468      });469      await expectFailedToTransact(helper, messageSent);470    });471  }472473}
after · tests/src/xcm/xcm.types.ts
1import {IKeyringPair} from '@polkadot/types/types';2import {hexToString} from '@polkadot/util';3import {expect, usingAcalaPlaygrounds, usingAstarPlaygrounds, usingKaruraPlaygrounds, usingMoonbeamPlaygrounds, usingMoonriverPlaygrounds, usingPlaygrounds, usingPolkadexPlaygrounds, usingRelayPlaygrounds, usingShidenPlaygrounds} from '../util';4import {DevUniqueHelper, Event} from '../util/playgrounds/unique.dev';5import config from '../config';6import {blake2AsHex} from '@polkadot/util-crypto';78export const UNIQUE_CHAIN = +(process.env.RELAY_UNIQUE_ID || 2037);9export const STATEMINT_CHAIN = +(process.env.RELAY_STATEMINT_ID || 1000);10export const ACALA_CHAIN = +(process.env.RELAY_ACALA_ID || 2000);11export const MOONBEAM_CHAIN = +(process.env.RELAY_MOONBEAM_ID || 2004);12export const ASTAR_CHAIN = +(process.env.RELAY_ASTAR_ID || 2006);13export const POLKADEX_CHAIN = +(process.env.RELAY_POLKADEX_ID || 2040);1415export const QUARTZ_CHAIN = +(process.env.RELAY_QUARTZ_ID || 2095);16export const STATEMINE_CHAIN = +(process.env.RELAY_STATEMINE_ID || 1000);17export const KARURA_CHAIN = +(process.env.RELAY_KARURA_ID || 2000);18export const MOONRIVER_CHAIN = +(process.env.RELAY_MOONRIVER_ID || 2023);19export const SHIDEN_CHAIN = +(process.env.RELAY_SHIDEN_ID || 2007);2021export const relayUrl = config.relayUrl;22export const statemintUrl = config.statemintUrl;23export const statemineUrl = config.statemineUrl;2425export const acalaUrl = config.acalaUrl;26export const moonbeamUrl = config.moonbeamUrl;27export const astarUrl = config.astarUrl;28export const polkadexUrl = config.polkadexUrl;2930export const karuraUrl = config.karuraUrl;31export const moonriverUrl = config.moonriverUrl;32export const shidenUrl = config.shidenUrl;3334export const SAFE_XCM_VERSION = 3;353637export const RELAY_DECIMALS = 12;38export const STATEMINE_DECIMALS = 12;39export const KARURA_DECIMALS = 12;40export const SHIDEN_DECIMALS = 18n;41export const QTZ_DECIMALS = 18n;4243export const ASTAR_DECIMALS = 18n;44export const UNQ_DECIMALS = 18n;4546export const maxWaitBlocks = 6;4748export const uniqueMultilocation = {49  parents: 1,50  interior: {51    X1: {52      Parachain: UNIQUE_CHAIN,53    },54  },55};56export const uniqueVersionedMultilocation = {57  V3: uniqueMultilocation,58};5960export const uniqueAssetId = {61  Concrete: uniqueMultilocation,62};6364export const expectFailedToTransact = async (helper: DevUniqueHelper, messageSent: any) => {65  await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash66        && event.outcome.isFailedToTransactAsset);67};68export const expectUntrustedReserveLocationFail = async (helper: DevUniqueHelper, messageSent: any) => {69  await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash70         && event.outcome.isUntrustedReserveLocation);71};7273export const expectDownwardXcmNoPermission = async (helper: DevUniqueHelper) => {74  // The correct messageHash for downward messages can't be reliably obtained75  await helper.wait.expectEvent(maxWaitBlocks, Event.DmpQueue.ExecutedDownward, event => event.outcome.asIncomplete[1].isNoPermission);76};7778export const expectDownwardXcmComplete = async (helper: DevUniqueHelper) => {79  // The correct messageHash for downward messages can't be reliably obtained80  await helper.wait.expectEvent(maxWaitBlocks, Event.DmpQueue.ExecutedDownward, event => event.outcome.isComplete);81};8283export const NETWORKS = {84  acala: usingAcalaPlaygrounds,85  astar: usingAstarPlaygrounds,86  polkadex: usingPolkadexPlaygrounds,87  moonbeam: usingMoonbeamPlaygrounds,88  moonriver: usingMoonriverPlaygrounds,89  karura: usingKaruraPlaygrounds,90  shiden: usingShidenPlaygrounds,91} as const;92type NetworkNames = keyof typeof NETWORKS;9394type NativeRuntime = 'opal' | 'quartz' | 'unique';9596export function mapToChainId(networkName: keyof typeof NETWORKS): number {97  switch (networkName) {98    case 'acala':99      return ACALA_CHAIN;100    case 'astar':101      return ASTAR_CHAIN;102    case 'moonbeam':103      return MOONBEAM_CHAIN;104    case 'polkadex':105      return POLKADEX_CHAIN;106    case 'moonriver':107      return MOONRIVER_CHAIN;108    case 'karura':109      return KARURA_CHAIN;110    case 'shiden':111      return SHIDEN_CHAIN;112  }113}114115export function mapToChainUrl(networkName: NetworkNames): string {116  switch (networkName) {117    case 'acala':118      return acalaUrl;119    case 'astar':120      return astarUrl;121    case 'moonbeam':122      return moonbeamUrl;123    case 'polkadex':124      return polkadexUrl;125    case 'moonriver':126      return moonriverUrl;127    case 'karura':128      return karuraUrl;129    case 'shiden':130      return shidenUrl;131  }132}133134export function getDevPlayground(name: NetworkNames) {135  return NETWORKS[name];136}137138export const TRANSFER_AMOUNT = 2000000_000_000_000_000_000_000n;139const SENDER_BUDGET = 2n * TRANSFER_AMOUNT;140const SENDBACK_AMOUNT = TRANSFER_AMOUNT / 2n;141const STAYED_ON_TARGET_CHAIN = TRANSFER_AMOUNT - SENDBACK_AMOUNT;142const TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT = 100_000_000_000n;143144export class XcmTestHelper {145  private _balanceUniqueTokenInit: bigint = 0n;146  private _balanceUniqueTokenMiddle: bigint = 0n;147  private _balanceUniqueTokenFinal: bigint = 0n;148  private _unqFees: bigint = 0n;149  private _nativeRuntime: NativeRuntime;150151  constructor(runtime: NativeRuntime) {152    this._nativeRuntime = runtime;153  }154155  private _getNativeId() {156    switch (this._nativeRuntime) {157      case 'opal':158        // To-Do159        return 10;160      case 'quartz':161        return QUARTZ_CHAIN;162      case 'unique':163        return UNIQUE_CHAIN;164    }165  }166  private _isAddress20FormatFor(network: NetworkNames) {167    switch (network) {168      case 'moonbeam':169      case 'moonriver':170        return true;171      default:172        return false;173    }174  }175176  uniqueChainMultilocationForRelay() {177    return {178      V3: {179        parents: 0,180        interior: {181          X1: {Parachain: this._getNativeId()},182        },183      },184    };185  }186187  async sendUnqTo(188    networkName: keyof typeof NETWORKS,189    randomAccount: IKeyringPair,190    randomAccountOnTargetChain = randomAccount,191  ) {192    const networkUrl = mapToChainUrl(networkName);193    const targetPlayground = getDevPlayground(networkName);194    await usingPlaygrounds(async (helper) => {195      this._balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);196      const destination = {197        V2: {198          parents: 1,199          interior: {200            X1: {201              Parachain: mapToChainId(networkName),202            },203          },204        },205      };206207      const beneficiary = {208        V2: {209          parents: 0,210          interior: {211            X1: (212              this._isAddress20FormatFor(networkName) ?213                {214                  AccountKey20: {215                    network: 'Any',216                    key: randomAccountOnTargetChain.address,217                  },218                }219                :220                {221                  AccountId32: {222                    network: 'Any',223                    id: randomAccountOnTargetChain.addressRaw,224                  },225                }226            ),227          },228        },229      };230231      const assets = {232        V2: [233          {234            id: {235              Concrete: {236                parents: 0,237                interior: 'Here',238              },239            },240            fun: {241              Fungible: TRANSFER_AMOUNT,242            },243          },244        ],245      };246      const feeAssetItem = 0;247248      await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');249      const messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);250      this._balanceUniqueTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);251252      this._unqFees = this._balanceUniqueTokenInit - this._balanceUniqueTokenMiddle - TRANSFER_AMOUNT;253      console.log('[Unique -> %s] transaction fees on Unique: %s UNQ', networkName, helper.util.bigIntToDecimals(this._unqFees));254      expect(this._unqFees > 0n, 'Negative fees UNQ, looks like nothing was transferred').to.be.true;255256      await targetPlayground(networkUrl, async (helper) => {257      /*258        Since only the parachain part of the Polkadex259        infrastructure is launched (without their260        solochain validators), processing incoming261        assets will lead to an error.262        This error indicates that the Polkadex chain263        received a message from the Unique network,264        since the hash is being checked to ensure265        it matches what was sent.266      */267        if(networkName == 'polkadex') {268          await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash);269        } else {270          await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == messageSent.messageHash);271        }272      });273274    });275  }276277  async sendUnqBack(278    networkName: keyof typeof NETWORKS,279    sudoer: IKeyringPair,280    randomAccountOnUnq: IKeyringPair,281  ) {282    const networkUrl = mapToChainUrl(networkName);283284    const targetPlayground = getDevPlayground(networkName);285    await usingPlaygrounds(async (helper) => {286287      const xcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(288        randomAccountOnUnq.addressRaw,289        {290          Concrete: {291            parents: 1,292            interior: {293              X1: {Parachain: this._getNativeId()},294            },295          },296        },297        SENDBACK_AMOUNT,298      );299300      let xcmProgramSent: any;301302303      await targetPlayground(networkUrl, async (helper) => {304        if('getSudo' in helper) {305          await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, xcmProgram);306          xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);307        } else if('fastDemocracy' in helper) {308          const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, xcmProgram]);309          // Needed to bypass the call filter.310          const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);311          await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);312          xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);313        }314      });315316      await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == xcmProgramSent.messageHash);317318      this._balanceUniqueTokenFinal = await helper.balance.getSubstrate(randomAccountOnUnq.address);319320      expect(this._balanceUniqueTokenFinal).to.be.equal(this._balanceUniqueTokenInit - this._unqFees - STAYED_ON_TARGET_CHAIN);321322    });323  }324325  async sendOnlyOwnedBalance(326    networkName: keyof typeof NETWORKS,327    sudoer: IKeyringPair,328  ) {329    const networkUrl = mapToChainUrl(networkName);330    const targetPlayground = getDevPlayground(networkName);331332    const targetChainBalance = 10000n * (10n ** UNQ_DECIMALS);333334    await usingPlaygrounds(async (helper) => {335      const targetChainSovereignAccount = helper.address.paraSiblingSovereignAccount(mapToChainId(networkName));336      await helper.getSudo().balance.setBalanceSubstrate(sudoer, targetChainSovereignAccount, targetChainBalance);337      const moreThanTargetChainHas = 2n * targetChainBalance;338339      const targetAccount = helper.arrange.createEmptyAccount();340341      const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(342        targetAccount.addressRaw,343        {344          Concrete: {345            parents: 0,346            interior: 'Here',347          },348        },349        moreThanTargetChainHas,350      );351352      let maliciousXcmProgramSent: any;353354355      await targetPlayground(networkUrl, async (helper) => {356        if('getSudo' in helper) {357          await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgram);358          maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);359        } else if('fastDemocracy' in helper) {360          const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgram]);361          // Needed to bypass the call filter.362          const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);363          await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);364          maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);365        }366      });367368      await expectFailedToTransact(helper, maliciousXcmProgramSent);369370      const targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);371      expect(targetAccountBalance).to.be.equal(0n);372    });373  }374375  async reserveTransferUNQfrom(netwokrName: keyof typeof NETWORKS, sudoer: IKeyringPair) {376    const networkUrl = mapToChainUrl(netwokrName);377    const targetPlayground = getDevPlayground(netwokrName);378379    await usingPlaygrounds(async (helper) => {380      const testAmount = 10_000n * (10n ** UNQ_DECIMALS);381      const targetAccount = helper.arrange.createEmptyAccount();382383      const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(384        targetAccount.addressRaw,385        {386          Concrete: {387            parents: 1,388            interior: {389              X1: {390                Parachain: this._getNativeId(),391              },392            },393          },394        },395        testAmount,396      );397398      const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(399        targetAccount.addressRaw,400        {401          Concrete: {402            parents: 0,403            interior: 'Here',404          },405        },406        testAmount,407      );408409      let maliciousXcmProgramFullIdSent: any;410      let maliciousXcmProgramHereIdSent: any;411      const maxWaitBlocks = 3;412413      // Try to trick Unique using full UNQ identification414      await targetPlayground(networkUrl, async (helper) => {415        if('getSudo' in helper) {416          await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgramFullId);417          maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);418        }419        // Moonbeam case420        else if('fastDemocracy' in helper) {421          const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramFullId]);422          // Needed to bypass the call filter.423          const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);424          await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using path asset identification`,batchCall);425426          maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);427        }428      });429430431      await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramFullIdSent);432433      let accountBalance = await helper.balance.getSubstrate(targetAccount.address);434      expect(accountBalance).to.be.equal(0n);435436      // Try to trick Unique using shortened UNQ identification437      await targetPlayground(networkUrl, async (helper) => {438        if('getSudo' in helper) {439          await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgramHereId);440          maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);441        }442        else if('fastDemocracy' in helper) {443          const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramHereId]);444          // Needed to bypass the call filter.445          const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);446          await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using "here" asset identification`, batchCall);447448          maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);449        }450      });451452      await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramHereIdSent);453454      accountBalance = await helper.balance.getSubstrate(targetAccount.address);455      expect(accountBalance).to.be.equal(0n);456    });457  }458459  async rejectNativeTokensFrom(networkName: keyof typeof NETWORKS, sudoerOnTargetChain: IKeyringPair) {460    const networkUrl = mapToChainUrl(networkName);461    const targetPlayground = getDevPlayground(networkName);462    let messageSent: any;463464    await usingPlaygrounds(async (helper) => {465      const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(466        helper.arrange.createEmptyAccount().addressRaw,467        {468          Concrete: {469            parents: 1,470            interior: {471              X1: {472                Parachain: mapToChainId(networkName),473              },474            },475          },476        },477        TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT,478      );479      await targetPlayground(networkUrl, async (helper) => {480        if('getSudo' in helper) {481          await helper.getSudo().xcm.send(sudoerOnTargetChain, uniqueVersionedMultilocation, maliciousXcmProgramFullId);482          messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);483        } else if('fastDemocracy' in helper) {484          const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramFullId]);485          // Needed to bypass the call filter.486          const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);487          await helper.fastDemocracy.executeProposal(`${networkName} sending native tokens to the Unique via fast democracy`, batchCall);488489          messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);490        }491      });492      await expectFailedToTransact(helper, messageSent);493    });494  }495496  private async _relayXcmTransactSetStorage(variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch') {497    // eslint-disable-next-line require-await498    return await usingPlaygrounds(async (helper) => {499      const relayForceKV = () => {500        const random = Math.random();501        const key = `relay-forced-key (instance: ${random})`;502        const val = `relay-forced-value (instance: ${random})`;503        const call = helper.constructApiCall('api.tx.system.setStorage', [[[key, val]]]).method.toHex();504505        return {506          call,507          key,508          val,509        };510      };511512      if(variant == 'plain') {513        const kv = relayForceKV();514        return {515          program: helper.arrange.makeTransactProgram({516            weightMultiplier: 1,517            call: kv.call,518          }),519          kvs: [kv],520        };521      } else {522        const kv0 = relayForceKV();523        const kv1 = relayForceKV();524525        const batchCall = helper.constructApiCall(`api.tx.utility.${variant}`, [[kv0.call, kv1.call]]).method.toHex();526        return {527          program: helper.arrange.makeTransactProgram({528            weightMultiplier: 2,529            call: batchCall,530          }),531          kvs: [kv0, kv1],532        };533      }534    });535  }536537  async relayIsPermittedToSetStorage(relaySudoer: IKeyringPair, variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch') {538    const {program, kvs} = await this._relayXcmTransactSetStorage(variant);539540    await usingRelayPlaygrounds(relayUrl, async (helper) => {541      await helper.getSudo().executeExtrinsic(relaySudoer, 'api.tx.xcmPallet.send', [542        this.uniqueChainMultilocationForRelay(),543        program,544      ]);545    });546547    await usingPlaygrounds(async (helper) => {548      await expectDownwardXcmComplete(helper);549550      for(const kv of kvs) {551        const forcedValue = await helper.callRpc('api.rpc.state.getStorage', [kv.key]);552        expect(hexToString(forcedValue.toHex())).to.be.equal(kv.val);553      }554    });555  }556557  private async _relayXcmTransactSetBalance(variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch' | 'dispatchAs') {558    // eslint-disable-next-line require-await559    return await usingPlaygrounds(async (helper) => {560      const emptyAccount = helper.arrange.createEmptyAccount().address;561562      const forceSetBalanceCall = helper.constructApiCall('api.tx.balances.forceSetBalance', [emptyAccount, 10_000n]).method.toHex();563564      let call;565566      if(variant == 'plain') {567        call = forceSetBalanceCall;568569      } else if(variant == 'dispatchAs') {570        call = helper.constructApiCall('api.tx.utility.dispatchAs', [571          {572            system: 'Root',573          },574          forceSetBalanceCall,575        ]).method.toHex();576      } else {577        call = helper.constructApiCall(`api.tx.utility.${variant}`, [[forceSetBalanceCall]]).method.toHex();578      }579580      return {581        program: helper.arrange.makeTransactProgram({582          weightMultiplier: 1,583          call,584        }),585        emptyAccount,586      };587    });588  }589590  async relayIsNotPermittedToSetBalance(591    relaySudoer: IKeyringPair,592    variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch' | 'dispatchAs',593  ) {594    const {program, emptyAccount} = await this._relayXcmTransactSetBalance(variant);595596    await usingRelayPlaygrounds(relayUrl, async (helper) => {597      await helper.getSudo().executeExtrinsic(relaySudoer, 'api.tx.xcmPallet.send', [598        this.uniqueChainMultilocationForRelay(),599        program,600      ]);601    });602603    await usingPlaygrounds(async (helper) => {604      await expectDownwardXcmNoPermission(helper);605      expect(await helper.balance.getSubstrate(emptyAccount)).to.be.equal(0n);606    });607  }608}