git.delta.rocks / unique-network / refs/commits / abe0498b88a3

difftreelog

test other chains can spend only up to balance

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

4 files changed

modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -420,6 +420,63 @@
 
     return capture;
   }
+
+  makeXcmProgramWithdrawDeposit(beneficiary: Uint8Array, amount: bigint | string) {
+    return {
+      V2: [
+        {
+          WithdrawAsset: [
+            {
+              id: {
+                Concrete: {
+                  parents: 0,
+                  interior: 'Here',
+                },
+              },
+              fun: {
+                Fungible: amount,
+              },
+            },
+          ],
+        },
+        {
+          BuyExecution: {
+            fees: {
+              id: {
+                Concrete: {
+                  parents: 0,
+                  interior: 'Here',
+                },
+              },
+              fun: {
+                Fungible: amount,
+              },
+            },
+            weightLimit: 'Unlimited'
+          },
+        },
+        {
+          DepositAsset: {
+            assets: {
+              Wild: 'All'
+            },
+            maxAssets: 1,
+            beneficiary: {
+              parents: 0,
+              interior: {
+                X1: {
+                  AccountId32: {
+                    network: 'Any',
+                    id: beneficiary
+                  },
+                },
+              },
+            },
+          }
+        },
+      ],
+    };
+  }
 }
 
 class MoonbeamAccountGroup {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -2446,6 +2446,10 @@
     return this.ethBalanceGroup.getEthereum(address);
   }
 
+  async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string, reservedAmount: bigint | string = 0n) {
+    await this.helper.executeExtrinsic(signer, 'api.tx.balances.setBalance', [address, amount, reservedAmount], true);
+  }
+
   /**
    * Transfer tokens to substrate address
    * @param signer keyring of signer
modifiedtests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth
before · tests/src/xcm/xcmQuartz.test.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {blake2AsHex} from '@polkadot/util-crypto';19import config from '../config';20import {XcmV2TraitsError} from '../interfaces';21import {itSub, expect, describeXCM, usingPlaygrounds, usingKaruraPlaygrounds, usingRelayPlaygrounds, usingMoonriverPlaygrounds, usingStateminePlaygrounds, usingShidenPlaygrounds} from '../util';22import {DevUniqueHelper} from '../util/playgrounds/unique.dev';2324const QUARTZ_CHAIN = 2095;25const STATEMINE_CHAIN = 1000;26const KARURA_CHAIN = 2000;27const MOONRIVER_CHAIN = 2023;28const SHIDEN_CHAIN = 2007;2930const STATEMINE_PALLET_INSTANCE = 50;3132const relayUrl = config.relayUrl;33const statemineUrl = config.statemineUrl;34const karuraUrl = config.karuraUrl;35const moonriverUrl = config.moonriverUrl;36const shidenUrl = config.shidenUrl;3738const RELAY_DECIMALS = 12;39const STATEMINE_DECIMALS = 12;40const KARURA_DECIMALS = 12;41const SHIDEN_DECIMALS = 18n;42const QTZ_DECIMALS = 18n;4344const TRANSFER_AMOUNT = 2000000000000000000000000n;4546const FUNDING_AMOUNT = 3_500_000_0000_000_000n;4748const TRANSFER_AMOUNT_RELAY = 50_000_000_000_000_000n;4950const USDT_ASSET_ID = 100;51const USDT_ASSET_METADATA_DECIMALS = 18;52const USDT_ASSET_METADATA_NAME = 'USDT';53const USDT_ASSET_METADATA_DESCRIPTION = 'USDT';54const USDT_ASSET_METADATA_MINIMAL_BALANCE = 1n;55const USDT_ASSET_AMOUNT = 10_000_000_000_000_000_000_000_000n;5657const SAFE_XCM_VERSION = 2;5859describeXCM('[XCM] Integration test: Exchanging USDT with Statemine', () => {60  let alice: IKeyringPair;61  let bob: IKeyringPair;6263  let balanceStmnBefore: bigint;64  let balanceStmnAfter: bigint;6566  let balanceQuartzBefore: bigint;67  let balanceQuartzAfter: bigint;68  let balanceQuartzFinal: bigint;6970  let balanceBobBefore: bigint;71  let balanceBobAfter: bigint;72  let balanceBobFinal: bigint;7374  let balanceBobRelayTokenBefore: bigint;75  let balanceBobRelayTokenAfter: bigint;767778  before(async () => {79    await usingPlaygrounds(async (helper, privateKey) => {80      alice = await privateKey('//Alice');81      bob = await privateKey('//Bob'); // sovereign account on Statemine(t) funds donor8283      // Set the default version to wrap the first message to other chains.84      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);85    });8687    await usingRelayPlaygrounds(relayUrl, async (helper) => {88      // Fund accounts on Statemine(t)89      await helper.xcm.teleportNativeAsset(alice, STATEMINE_CHAIN, alice.addressRaw, FUNDING_AMOUNT);90      await helper.xcm.teleportNativeAsset(alice, STATEMINE_CHAIN, bob.addressRaw, FUNDING_AMOUNT);91    });9293    await usingStateminePlaygrounds(statemineUrl, async (helper) => {94      const sovereignFundingAmount = 3_500_000_000n;9596      await helper.assets.create(97        alice,98        USDT_ASSET_ID,99        alice.address,100        USDT_ASSET_METADATA_MINIMAL_BALANCE,101      );102      await helper.assets.setMetadata(103        alice,104        USDT_ASSET_ID,105        USDT_ASSET_METADATA_NAME,106        USDT_ASSET_METADATA_DESCRIPTION,107        USDT_ASSET_METADATA_DECIMALS,108      );109      await helper.assets.mint(110        alice,111        USDT_ASSET_ID,112        alice.address,113        USDT_ASSET_AMOUNT,114      );115116      // funding parachain sovereing account on Statemine(t).117      // The sovereign account should be created before any action118      // (the assets pallet on Statemine(t) check if the sovereign account exists)119      const parachainSovereingAccount = helper.address.paraSiblingSovereignAccount(QUARTZ_CHAIN);120      await helper.balance.transferToSubstrate(bob, parachainSovereingAccount, sovereignFundingAmount);121    });122123124    await usingPlaygrounds(async (helper) => {125      const location = {126        V2: {127          parents: 1,128          interior: {X3: [129            {130              Parachain: STATEMINE_CHAIN,131            },132            {133              PalletInstance: STATEMINE_PALLET_INSTANCE,134            },135            {136              GeneralIndex: USDT_ASSET_ID,137            },138          ]},139        },140      };141142      const metadata =143      {144        name: USDT_ASSET_ID,145        symbol: USDT_ASSET_METADATA_NAME,146        decimals: USDT_ASSET_METADATA_DECIMALS,147        minimalBalance: USDT_ASSET_METADATA_MINIMAL_BALANCE,148      };149      await helper.getSudo().foreignAssets.register(alice, alice.address, location, metadata);150      balanceQuartzBefore = await helper.balance.getSubstrate(alice.address);151    });152153154    // Providing the relay currency to the quartz sender account155    // (fee for USDT XCM are paid in relay tokens)156    await usingRelayPlaygrounds(relayUrl, async (helper) => {157      const destination = {158        V2: {159          parents: 0,160          interior: {X1: {161            Parachain: QUARTZ_CHAIN,162          },163          },164        }};165166      const beneficiary = {167        V2: {168          parents: 0,169          interior: {X1: {170            AccountId32: {171              network: 'Any',172              id: alice.addressRaw,173            },174          }},175        },176      };177178      const assets = {179        V2: [180          {181            id: {182              Concrete: {183                parents: 0,184                interior: 'Here',185              },186            },187            fun: {188              Fungible: TRANSFER_AMOUNT_RELAY,189            },190          },191        ],192      };193194      const feeAssetItem = 0;195196      await helper.xcm.limitedReserveTransferAssets(alice, destination, beneficiary, assets, feeAssetItem, 'Unlimited');197    });198199  });200201  itSub('Should connect and send USDT from Statemine to Quartz', async ({helper}) => {202    await usingStateminePlaygrounds(statemineUrl, async (helper) => {203      const dest = {204        V2: {205          parents: 1,206          interior: {X1: {207            Parachain: QUARTZ_CHAIN,208          },209          },210        }};211212      const beneficiary = {213        V2: {214          parents: 0,215          interior: {X1: {216            AccountId32: {217              network: 'Any',218              id: alice.addressRaw,219            },220          }},221        },222      };223224      const assets = {225        V2: [226          {227            id: {228              Concrete: {229                parents: 0,230                interior: {231                  X2: [232                    {233                      PalletInstance: STATEMINE_PALLET_INSTANCE,234                    },235                    {236                      GeneralIndex: USDT_ASSET_ID,237                    },238                  ]},239              },240            },241            fun: {242              Fungible: TRANSFER_AMOUNT,243            },244          },245        ],246      };247248      const feeAssetItem = 0;249250      balanceStmnBefore = await helper.balance.getSubstrate(alice.address);251      await helper.xcm.limitedReserveTransferAssets(alice, dest, beneficiary, assets, feeAssetItem, 'Unlimited');252253      balanceStmnAfter = await helper.balance.getSubstrate(alice.address);254255      // common good parachain take commission in it native token256      console.log(257        '[Statemine -> Quartz] transaction fees on Statemine: %s WND',258        helper.util.bigIntToDecimals(balanceStmnBefore - balanceStmnAfter, STATEMINE_DECIMALS),259      );260      expect(balanceStmnBefore > balanceStmnAfter).to.be.true;261262    });263264265    // ensure that asset has been delivered266    await helper.wait.newBlocks(3);267268    // expext collection id will be with id 1269    const free = await helper.ft.getBalance(1, {Substrate: alice.address});270271    balanceQuartzAfter = await helper.balance.getSubstrate(alice.address);272273    console.log(274      '[Statemine -> Quartz] transaction fees on Quartz: %s USDT',275      helper.util.bigIntToDecimals(TRANSFER_AMOUNT - free, USDT_ASSET_METADATA_DECIMALS),276    );277    console.log(278      '[Statemine -> Quartz] transaction fees on Quartz: %s QTZ',279      helper.util.bigIntToDecimals(balanceQuartzAfter - balanceQuartzBefore),280    );281    // commission has not paid in USDT token282    expect(free).to.be.equal(TRANSFER_AMOUNT);283    // ... and parachain native token284    expect(balanceQuartzAfter == balanceQuartzBefore).to.be.true;285  });286287  itSub('Should connect and send USDT from Quartz to Statemine back', async ({helper}) => {288    const destination = {289      V2: {290        parents: 1,291        interior: {X2: [292          {293            Parachain: STATEMINE_CHAIN,294          },295          {296            AccountId32: {297              network: 'Any',298              id: alice.addressRaw,299            },300          },301        ]},302      },303    };304305    const relayFee = 400_000_000_000_000n;306    const currencies: [any, bigint][] = [307      [308        {309          ForeignAssetId: 0,310        },311        TRANSFER_AMOUNT,312      ],313      [314        {315          NativeAssetId: 'Parent',316        },317        relayFee,318      ],319    ];320321    const feeItem = 1;322323    await helper.xTokens.transferMulticurrencies(alice, currencies, feeItem, destination, 'Unlimited');324325    // the commission has been paid in parachain native token326    balanceQuartzFinal = await helper.balance.getSubstrate(alice.address);327    console.log('[Quartz -> Statemine] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(balanceQuartzAfter - balanceQuartzFinal));328    expect(balanceQuartzAfter > balanceQuartzFinal).to.be.true;329330    await usingStateminePlaygrounds(statemineUrl, async (helper) => {331      await helper.wait.newBlocks(3);332333      // The USDT token never paid fees. Its amount not changed from begin value.334      // Also check that xcm transfer has been succeeded335      expect((await helper.assets.account(USDT_ASSET_ID, alice.address))! == USDT_ASSET_AMOUNT).to.be.true;336    });337  });338339  itSub('Should connect and send Relay token to Quartz', async ({helper}) => {340    balanceBobBefore = await helper.balance.getSubstrate(bob.address);341    balanceBobRelayTokenBefore = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});342343    await usingRelayPlaygrounds(relayUrl, async (helper) => {344      const destination = {345        V2: {346          parents: 0,347          interior: {X1: {348            Parachain: QUARTZ_CHAIN,349          },350          },351        }};352353      const beneficiary = {354        V2: {355          parents: 0,356          interior: {X1: {357            AccountId32: {358              network: 'Any',359              id: bob.addressRaw,360            },361          }},362        },363      };364365      const assets = {366        V2: [367          {368            id: {369              Concrete: {370                parents: 0,371                interior: 'Here',372              },373            },374            fun: {375              Fungible: TRANSFER_AMOUNT_RELAY,376            },377          },378        ],379      };380381      const feeAssetItem = 0;382383      await helper.xcm.limitedReserveTransferAssets(bob, destination, beneficiary, assets, feeAssetItem, 'Unlimited');384    });385386    await helper.wait.newBlocks(3);387388    balanceBobAfter = await helper.balance.getSubstrate(bob.address);389    balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});390391    const wndFeeOnQuartz = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;392    const wndDiffOnQuartz = balanceBobRelayTokenAfter - balanceBobRelayTokenBefore;393    console.log(394      '[Relay (Westend) -> Quartz] transaction fees: %s QTZ',395      helper.util.bigIntToDecimals(balanceBobAfter - balanceBobBefore),396    );397    console.log(398      '[Relay (Westend) -> Quartz] transaction fees: %s WND',399      helper.util.bigIntToDecimals(wndFeeOnQuartz, STATEMINE_DECIMALS),400    );401    console.log('[Relay (Westend) -> Quartz] actually delivered: %s WND', wndDiffOnQuartz);402    expect(wndFeeOnQuartz == 0n, 'No incoming WND fees should be taken').to.be.true;403    expect(balanceBobBefore == balanceBobAfter, 'No incoming QTZ fees should be taken').to.be.true;404  });405406  itSub('Should connect and send Relay token back', async ({helper}) => {407    let relayTokenBalanceBefore: bigint;408    let relayTokenBalanceAfter: bigint;409    await usingRelayPlaygrounds(relayUrl, async (helper) => {410      relayTokenBalanceBefore = await helper.balance.getSubstrate(bob.address);411    });412413    const destination = {414      V2: {415        parents: 1,416        interior: {417          X1:{418            AccountId32: {419              network: 'Any',420              id: bob.addressRaw,421            },422          },423        },424      },425    };426427    const currencies: any = [428      [429        {430          NativeAssetId: 'Parent',431        },432        TRANSFER_AMOUNT_RELAY,433      ],434    ];435436    const feeItem = 0;437438    await helper.xTokens.transferMulticurrencies(bob, currencies, feeItem, destination, 'Unlimited');439440    balanceBobFinal = await helper.balance.getSubstrate(bob.address);441    console.log('[Quartz -> Relay (Westend)] transaction fees: %s QTZ',  helper.util.bigIntToDecimals(balanceBobAfter - balanceBobFinal));442443    await usingRelayPlaygrounds(relayUrl, async (helper) => {444      await helper.wait.newBlocks(10);445      relayTokenBalanceAfter = await helper.balance.getSubstrate(bob.address);446447      const diff = relayTokenBalanceAfter - relayTokenBalanceBefore;448      console.log('[Quartz -> Relay (Westend)] actually delivered: %s WND', helper.util.bigIntToDecimals(diff, RELAY_DECIMALS));449      expect(diff > 0, 'Relay tokens was not delivered back').to.be.true;450    });451  });452});453454describeXCM('[XCM] Integration test: Exchanging tokens with Karura', () => {455  let alice: IKeyringPair;456  let randomAccount: IKeyringPair;457458  let balanceQuartzTokenInit: bigint;459  let balanceQuartzTokenMiddle: bigint;460  let balanceQuartzTokenFinal: bigint;461  let balanceKaruraTokenInit: bigint;462  let balanceKaruraTokenMiddle: bigint;463  let balanceKaruraTokenFinal: bigint;464  let balanceQuartzForeignTokenInit: bigint;465  let balanceQuartzForeignTokenMiddle: bigint;466  let balanceQuartzForeignTokenFinal: bigint;467468  // computed by a test transfer from prod Quartz to prod Karura.469  // 2 QTZ sent https://quartz.subscan.io/xcm_message/kusama-f60d821b049f8835a3005ce7102285006f5b61e9470  // 1.919176000000000000 QTZ received (you can check Karura's chain state in the corresponding block)471  const expectedKaruraIncomeFee = 2000000000000000000n - 1919176000000000000n;472473  const KARURA_BACKWARD_TRANSFER_AMOUNT = TRANSFER_AMOUNT - expectedKaruraIncomeFee;474475  before(async () => {476    await usingPlaygrounds(async (helper, privateKey) => {477      alice = await privateKey('//Alice');478      [randomAccount] = await helper.arrange.createAccounts([0n], alice);479480      // Set the default version to wrap the first message to other chains.481      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);482    });483484    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {485      const destination = {486        V1: {487          parents: 1,488          interior: {489            X1: {490              Parachain: QUARTZ_CHAIN,491            },492          },493        },494      };495496      const metadata = {497        name: 'Quartz',498        symbol: 'QTZ',499        decimals: 18,500        minimalBalance: 1000000000000000000n,501      };502503      await helper.getSudo().assetRegistry.registerForeignAsset(alice, destination, metadata);504      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);505      balanceKaruraTokenInit = await helper.balance.getSubstrate(randomAccount.address);506      balanceQuartzForeignTokenInit = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});507    });508509    await usingPlaygrounds(async (helper) => {510      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10n * TRANSFER_AMOUNT);511      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccount.address);512    });513  });514515  itSub('Should connect and send QTZ to Karura', async ({helper}) => {516    const destination = {517      V2: {518        parents: 1,519        interior: {520          X1: {521            Parachain: KARURA_CHAIN,522          },523        },524      },525    };526527    const beneficiary = {528      V2: {529        parents: 0,530        interior: {531          X1: {532            AccountId32: {533              network: 'Any',534              id: randomAccount.addressRaw,535            },536          },537        },538      },539    };540541    const assets = {542      V2: [543        {544          id: {545            Concrete: {546              parents: 0,547              interior: 'Here',548            },549          },550          fun: {551            Fungible: TRANSFER_AMOUNT,552          },553        },554      ],555    };556557    const feeAssetItem = 0;558559    await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');560    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);561562    const qtzFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;563    expect(qtzFees > 0n, 'Negative fees QTZ, looks like nothing was transferred').to.be.true;564    console.log('[Quartz -> Karura] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));565566    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {567      await helper.wait.newBlocks(3);568569      balanceQuartzForeignTokenMiddle = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});570      balanceKaruraTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);571572      const karFees = balanceKaruraTokenInit - balanceKaruraTokenMiddle;573      const qtzIncomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenInit;574      const karUnqFees = TRANSFER_AMOUNT - qtzIncomeTransfer;575576      console.log(577        '[Quartz -> Karura] transaction fees on Karura: %s KAR',578        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),579      );580      console.log(581        '[Quartz -> Karura] transaction fees on Karura: %s QTZ',582        helper.util.bigIntToDecimals(karUnqFees),583      );584      console.log('[Quartz -> Karura] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));585      expect(karFees == 0n).to.be.true;586      expect(587        karUnqFees == expectedKaruraIncomeFee,588        'Karura took different income fee, check the Karura foreign asset config',589      ).to.be.true;590    });591  });592593  itSub('Should connect to Karura and send QTZ back', async ({helper}) => {594    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {595      const destination = {596        V1: {597          parents: 1,598          interior: {599            X2: [600              {Parachain: QUARTZ_CHAIN},601              {602                AccountId32: {603                  network: 'Any',604                  id: randomAccount.addressRaw,605                },606              },607            ],608          },609        },610      };611612      const id = {613        ForeignAsset: 0,614      };615616      await helper.xTokens.transfer(randomAccount, id, KARURA_BACKWARD_TRANSFER_AMOUNT, destination, 'Unlimited');617      balanceKaruraTokenFinal = await helper.balance.getSubstrate(randomAccount.address);618      balanceQuartzForeignTokenFinal = await helper.tokens.accounts(randomAccount.address, id);619620      const karFees = balanceKaruraTokenMiddle - balanceKaruraTokenFinal;621      const qtzOutcomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenFinal;622623      console.log(624        '[Karura -> Quartz] transaction fees on Karura: %s KAR',625        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),626      );627      console.log('[Karura -> Quartz] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));628629      expect(karFees > 0, 'Negative fees KAR, looks like nothing was transferred').to.be.true;630      expect(qtzOutcomeTransfer == KARURA_BACKWARD_TRANSFER_AMOUNT).to.be.true;631    });632633    await helper.wait.newBlocks(3);634635    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccount.address);636    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;637    expect(actuallyDelivered > 0).to.be.true;638639    console.log('[Karura -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));640641    const qtzFees = KARURA_BACKWARD_TRANSFER_AMOUNT - actuallyDelivered;642    console.log('[Karura -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));643    expect(qtzFees == 0n).to.be.true;644  });645});646647// These tests are relevant only when648// the the corresponding foreign assets are not registered649describeXCM('[XCM] Integration test: Quartz rejects non-native tokens', () => {650  let alice: IKeyringPair;651  let alith: IKeyringPair;652653  const testAmount = 100_000_000_000n;654  let quartzParachainJunction;655  let quartzAccountJunction;656657  let quartzParachainMultilocation: any;658  let quartzAccountMultilocation: any;659  let quartzCombinedMultilocation: any;660661  before(async () => {662    await usingPlaygrounds(async (helper, privateKey) => {663      alice = await privateKey('//Alice');664665      quartzParachainJunction = {Parachain: QUARTZ_CHAIN};666      quartzAccountJunction = {667        AccountId32: {668          network: 'Any',669          id: alice.addressRaw,670        },671      };672673      quartzParachainMultilocation = {674        V1: {675          parents: 1,676          interior: {677            X1: quartzParachainJunction,678          },679        },680      };681682      quartzAccountMultilocation = {683        V1: {684          parents: 0,685          interior: {686            X1: quartzAccountJunction,687          },688        },689      };690691      quartzCombinedMultilocation = {692        V1: {693          parents: 1,694          interior: {695            X2: [quartzParachainJunction, quartzAccountJunction],696          },697        },698      };699700      // Set the default version to wrap the first message to other chains.701      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);702    });703704    // eslint-disable-next-line require-await705    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {706      alith = helper.account.alithAccount();707    });708  });709710  const expectFailedToTransact = async (network: string, helper: DevUniqueHelper) => {711    const maxWaitBlocks = 3;712713    const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(714      maxWaitBlocks,715      'xcmpQueue',716      'Fail',717    );718719    expect(720      xcmpQueueFailEvent != null,721      `[reject ${network} tokens] 'xcmpQueue.FailEvent' event is expected`,722    ).to.be.true;723724    expect(725      xcmpQueueFailEvent!.isFailedToTransactAsset,726      `[reject ${network} tokens] The XCM error should be 'FailedToTransactAsset'`,727    ).to.be.true;728  };729730  itSub('Quartz rejects KAR tokens from Karura', async ({helper}) => {731    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {732      const id = {733        Token: 'KAR',734      };735      const destination = quartzCombinedMultilocation;736      await helper.xTokens.transfer(alice, id, testAmount, destination, 'Unlimited');737    });738739    await expectFailedToTransact('KAR', helper);740  });741742  itSub('Quartz rejects MOVR tokens from Moonriver', async ({helper}) => {743    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {744      const id = 'SelfReserve';745      const destination = quartzCombinedMultilocation;746      await helper.xTokens.transfer(alith, id, testAmount, destination, 'Unlimited');747    });748749    await expectFailedToTransact('MOVR', helper);750  });751752  itSub('Quartz rejects SDN tokens from Shiden', async ({helper}) => {753    await usingShidenPlaygrounds(shidenUrl, async (helper) => {754      const destinationParachain = quartzParachainMultilocation;755      const beneficiary = quartzAccountMultilocation;756      const assets = {757        V1: [{758          id: {759            Concrete: {760              parents: 0,761              interior: 'Here',762            },763          },764          fun: {765            Fungible: testAmount,766          },767        }],768      };769      const feeAssetItem = 0;770771      await helper.executeExtrinsic(alice, 'api.tx.polkadotXcm.reserveWithdrawAssets', [772        destinationParachain,773        beneficiary,774        assets,775        feeAssetItem,776      ]);777    });778779    await expectFailedToTransact('SDN', helper);780  });781});782783describeXCM('[XCM] Integration test: Exchanging QTZ with Moonriver', () => {784  // Quartz constants785  let quartzDonor: IKeyringPair;786  let quartzAssetLocation;787788  let randomAccountQuartz: IKeyringPair;789  let randomAccountMoonriver: IKeyringPair;790791  // Moonriver constants792  let assetId: string;793794  const councilVotingThreshold = 2;795  const technicalCommitteeThreshold = 2;796  const votingPeriod = 3;797  const delayPeriod = 0;798799  const quartzAssetMetadata = {800    name: 'xcQuartz',801    symbol: 'xcQTZ',802    decimals: 18,803    isFrozen: false,804    minimalBalance: 1n,805  };806807  let balanceQuartzTokenInit: bigint;808  let balanceQuartzTokenMiddle: bigint;809  let balanceQuartzTokenFinal: bigint;810  let balanceForeignQtzTokenInit: bigint;811  let balanceForeignQtzTokenMiddle: bigint;812  let balanceForeignQtzTokenFinal: bigint;813  let balanceMovrTokenInit: bigint;814  let balanceMovrTokenMiddle: bigint;815  let balanceMovrTokenFinal: bigint;816817  before(async () => {818    await usingPlaygrounds(async (helper, privateKey) => {819      quartzDonor = await privateKey('//Alice');820      [randomAccountQuartz] = await helper.arrange.createAccounts([0n], quartzDonor);821822      balanceForeignQtzTokenInit = 0n;823824      // Set the default version to wrap the first message to other chains.825      const alice = quartzDonor;826      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);827    });828829    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {830      const alithAccount = helper.account.alithAccount();831      const baltatharAccount = helper.account.baltatharAccount();832      const dorothyAccount = helper.account.dorothyAccount();833834      randomAccountMoonriver = helper.account.create();835836      // >>> Sponsoring Dorothy >>>837      console.log('Sponsoring Dorothy.......');838      await helper.balance.transferToEthereum(alithAccount, dorothyAccount.address, 11_000_000_000_000_000_000n);839      console.log('Sponsoring Dorothy.......DONE');840      // <<< Sponsoring Dorothy <<<841842      quartzAssetLocation = {843        XCM: {844          parents: 1,845          interior: {X1: {Parachain: QUARTZ_CHAIN}},846        },847      };848      const existentialDeposit = 1n;849      const isSufficient = true;850      const unitsPerSecond = 1n;851      const numAssetsWeightHint = 0;852853      const encodedProposal = helper.assetManager.makeRegisterForeignAssetProposal({854        location: quartzAssetLocation,855        metadata: quartzAssetMetadata,856        existentialDeposit,857        isSufficient,858        unitsPerSecond,859        numAssetsWeightHint,860      });861      const proposalHash = blake2AsHex(encodedProposal);862863      console.log('Encoded proposal for registerForeignAsset & setAssetUnitsPerSecond is %s', encodedProposal);864      console.log('Encoded length %d', encodedProposal.length);865      console.log('Encoded proposal hash for batch utility after schedule is %s', proposalHash);866867      // >>> Note motion preimage >>>868      console.log('Note motion preimage.......');869      await helper.democracy.notePreimage(baltatharAccount, encodedProposal);870      console.log('Note motion preimage.......DONE');871      // <<< Note motion preimage <<<872873      // >>> Propose external motion through council >>>874      console.log('Propose external motion through council.......');875      const externalMotion = helper.democracy.externalProposeMajority({Legacy: proposalHash});876      const encodedMotion = externalMotion?.method.toHex() || '';877      const motionHash = blake2AsHex(encodedMotion);878      console.log('Motion hash is %s', motionHash);879880      await helper.collective.council.propose(baltatharAccount, councilVotingThreshold, externalMotion, externalMotion.encodedLength);881882      const councilProposalIdx = await helper.collective.council.proposalCount() - 1;883      await helper.collective.council.vote(dorothyAccount, motionHash, councilProposalIdx, true);884      await helper.collective.council.vote(baltatharAccount, motionHash, councilProposalIdx, true);885886      await helper.collective.council.close(887        dorothyAccount,888        motionHash,889        councilProposalIdx,890        {891          refTime: 1_000_000_000,892          proofSize: 1_000_000,893        },894        externalMotion.encodedLength,895      );896      console.log('Propose external motion through council.......DONE');897      // <<< Propose external motion through council <<<898899      // >>> Fast track proposal through technical committee >>>900      console.log('Fast track proposal through technical committee.......');901      const fastTrack = helper.democracy.fastTrack(proposalHash, votingPeriod, delayPeriod);902      const encodedFastTrack = fastTrack?.method.toHex() || '';903      const fastTrackHash = blake2AsHex(encodedFastTrack);904      console.log('FastTrack hash is %s', fastTrackHash);905906      await helper.collective.techCommittee.propose(alithAccount, technicalCommitteeThreshold, fastTrack, fastTrack.encodedLength);907908      const techProposalIdx = await helper.collective.techCommittee.proposalCount() - 1;909      await helper.collective.techCommittee.vote(baltatharAccount, fastTrackHash, techProposalIdx, true);910      await helper.collective.techCommittee.vote(alithAccount, fastTrackHash, techProposalIdx, true);911912      await helper.collective.techCommittee.close(913        baltatharAccount,914        fastTrackHash,915        techProposalIdx,916        {917          refTime: 1_000_000_000,918          proofSize: 1_000_000,919        },920        fastTrack.encodedLength,921      );922      console.log('Fast track proposal through technical committee.......DONE');923      // <<< Fast track proposal through technical committee <<<924925      // >>> Referendum voting >>>926      console.log('Referendum voting.......');927      await helper.democracy.referendumVote(dorothyAccount, 0, {928        balance: 10_000_000_000_000_000_000n,929        vote: {aye: true, conviction: 1},930      });931      console.log('Referendum voting.......DONE');932      // <<< Referendum voting <<<933934      // >>> Acquire Quartz AssetId Info on Moonriver >>>935      console.log('Acquire Quartz AssetId Info on Moonriver.......');936937      // Wait for the democracy execute938      await helper.wait.newBlocks(5);939940      assetId = (await helper.assetManager.assetTypeId(quartzAssetLocation)).toString();941942      console.log('QTZ asset ID is %s', assetId);943      console.log('Acquire Quartz AssetId Info on Moonriver.......DONE');944      // >>> Acquire Quartz AssetId Info on Moonriver >>>945946      // >>> Sponsoring random Account >>>947      console.log('Sponsoring random Account.......');948      await helper.balance.transferToEthereum(baltatharAccount, randomAccountMoonriver.address, 11_000_000_000_000_000_000n);949      console.log('Sponsoring random Account.......DONE');950      // <<< Sponsoring random Account <<<951952      balanceMovrTokenInit = await helper.balance.getEthereum(randomAccountMoonriver.address);953    });954955    await usingPlaygrounds(async (helper) => {956      await helper.balance.transferToSubstrate(quartzDonor, randomAccountQuartz.address, 10n * TRANSFER_AMOUNT);957      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccountQuartz.address);958    });959  });960961  itSub('Should connect and send QTZ to Moonriver', async ({helper}) => {962    const currencyId = {963      NativeAssetId: 'Here',964    };965    const dest = {966      V2: {967        parents: 1,968        interior: {969          X2: [970            {Parachain: MOONRIVER_CHAIN},971            {AccountKey20: {network: 'Any', key: randomAccountMoonriver.address}},972          ],973        },974      },975    };976    const amount = TRANSFER_AMOUNT;977978    await helper.xTokens.transfer(randomAccountQuartz, currencyId, amount, dest, 'Unlimited');979980    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccountQuartz.address);981    expect(balanceQuartzTokenMiddle < balanceQuartzTokenInit).to.be.true;982983    const transactionFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;984    console.log('[Quartz -> Moonriver] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(transactionFees));985    expect(transactionFees > 0, 'Negative fees QTZ, looks like nothing was transferred').to.be.true;986987    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {988      await helper.wait.newBlocks(3);989990      balanceMovrTokenMiddle = await helper.balance.getEthereum(randomAccountMoonriver.address);991992      const movrFees = balanceMovrTokenInit - balanceMovrTokenMiddle;993      console.log('[Quartz -> Moonriver] transaction fees on Moonriver: %s MOVR',helper.util.bigIntToDecimals(movrFees));994      expect(movrFees == 0n).to.be.true;995996      balanceForeignQtzTokenMiddle = (await helper.assets.account(assetId, randomAccountMoonriver.address))!; // BigInt(qtzRandomAccountAsset['balance']);997      const qtzIncomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenInit;998      console.log('[Quartz -> Moonriver] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));999      expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;1000    });1001  });10021003  itSub('Should connect to Moonriver and send QTZ back', async ({helper}) => {1004    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1005      const asset = {1006        V1: {1007          id: {1008            Concrete: {1009              parents: 1,1010              interior: {1011                X1: {Parachain: QUARTZ_CHAIN},1012              },1013            },1014          },1015          fun: {1016            Fungible: TRANSFER_AMOUNT,1017          },1018        },1019      };1020      const destination = {1021        V1: {1022          parents: 1,1023          interior: {1024            X2: [1025              {Parachain: QUARTZ_CHAIN},1026              {AccountId32: {network: 'Any', id: randomAccountQuartz.addressRaw}},1027            ],1028          },1029        },1030      };10311032      await helper.xTokens.transferMultiasset(randomAccountMoonriver, asset, destination, 'Unlimited');10331034      balanceMovrTokenFinal = await helper.balance.getEthereum(randomAccountMoonriver.address);10351036      const movrFees = balanceMovrTokenMiddle - balanceMovrTokenFinal;1037      console.log('[Moonriver -> Quartz] transaction fees on Moonriver: %s MOVR', helper.util.bigIntToDecimals(movrFees));1038      expect(movrFees > 0, 'Negative fees MOVR, looks like nothing was transferred').to.be.true;10391040      const qtzRandomAccountAsset = await helper.assets.account(assetId, randomAccountMoonriver.address);10411042      expect(qtzRandomAccountAsset).to.be.null;10431044      balanceForeignQtzTokenFinal = 0n;10451046      const qtzOutcomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenFinal;1047      console.log('[Quartz -> Moonriver] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));1048      expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;1049    });10501051    await helper.wait.newBlocks(3);10521053    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccountQuartz.address);1054    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;1055    expect(actuallyDelivered > 0).to.be.true;10561057    console.log('[Moonriver -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));10581059    const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;1060    console.log('[Moonriver -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));1061    expect(qtzFees == 0n).to.be.true;1062  });1063});10641065describeXCM('[XCM] Integration test: Exchanging tokens with Shiden', () => {1066  let alice: IKeyringPair;1067  let sender: IKeyringPair;10681069  const QTZ_ASSET_ID_ON_SHIDEN = 1;1070  const QTZ_MINIMAL_BALANCE_ON_SHIDEN = 1n;10711072  // Quartz -> Shiden1073  const shidenInitialBalance = 1n * (10n ** SHIDEN_DECIMALS); // 1 SHD, existential deposit required to actually create the account on Shiden1074  const unitsPerSecond = 228_000_000_000n; // This is Phala's value. What will be ours?1075  const qtzToShidenTransferred = 10n * (10n ** QTZ_DECIMALS); // 10 QTZ1076  const qtzToShidenArrived = 9_999_999_999_088_000_000n; // 9.999 ... QTZ, Shiden takes a commision in foreign tokens10771078  // Shiden -> Quartz1079  const qtzFromShidenTransfered = 5n * (10n ** QTZ_DECIMALS); // 5 QTZ1080  const qtzOnShidenLeft = qtzToShidenArrived - qtzFromShidenTransfered; // 4.999_999_999_088_000_000n QTZ10811082  let balanceAfterQuartzToShidenXCM: bigint;10831084  before(async () => {1085    await usingPlaygrounds(async (helper, privateKey) => {1086      alice = await privateKey('//Alice');1087      [sender] = await helper.arrange.createAccounts([100n], alice);1088      console.log('sender', sender.address);10891090      // Set the default version to wrap the first message to other chains.1091      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);1092    });10931094    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1095      console.log('1. Create foreign asset and metadata');1096      // TODO update metadata with values from production1097      await helper.assets.create(1098        alice,1099        QTZ_ASSET_ID_ON_SHIDEN,1100        alice.address,1101        QTZ_MINIMAL_BALANCE_ON_SHIDEN,1102      );11031104      await helper.assets.setMetadata(1105        alice,1106        QTZ_ASSET_ID_ON_SHIDEN,1107        'Cross chain QTZ',1108        'xcQTZ',1109        Number(QTZ_DECIMALS),1110      );11111112      console.log('2. Register asset location on Shiden');1113      const assetLocation = {1114        V1: {1115          parents: 1,1116          interior: {1117            X1: {1118              Parachain: QUARTZ_CHAIN,1119            },1120          },1121        },1122      };11231124      await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.registerAssetLocation', [assetLocation, QTZ_ASSET_ID_ON_SHIDEN]);11251126      console.log('3. Set QTZ payment for XCM execution on Shiden');1127      await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.setAssetUnitsPerSecond', [assetLocation, unitsPerSecond]);11281129      console.log('4. Transfer 1 SDN to recipient to create the account (needed due to existential balance)');1130      await helper.balance.transferToSubstrate(alice, sender.address, shidenInitialBalance);1131    });1132  });11331134  itSub('Should connect and send QTZ to Shiden', async ({helper}) => {1135    const destination = {1136      V2: {1137        parents: 1,1138        interior: {1139          X1: {1140            Parachain: SHIDEN_CHAIN,1141          },1142        },1143      },1144    };11451146    const beneficiary = {1147      V2: {1148        parents: 0,1149        interior: {1150          X1: {1151            AccountId32: {1152              network: 'Any',1153              id: sender.addressRaw,1154            },1155          },1156        },1157      },1158    };11591160    const assets = {1161      V2: [1162        {1163          id: {1164            Concrete: {1165              parents: 0,1166              interior: 'Here',1167            },1168          },1169          fun: {1170            Fungible: qtzToShidenTransferred,1171          },1172        },1173      ],1174    };11751176    // Initial balance is 100 QTZ1177    const balanceBefore = await helper.balance.getSubstrate(sender.address);1178    console.log(`Initial balance is: ${balanceBefore}`);11791180    const feeAssetItem = 0;1181    await helper.xcm.limitedReserveTransferAssets(sender, destination, beneficiary, assets, feeAssetItem, 'Unlimited');11821183    // Balance after reserve transfer is less than 901184    balanceAfterQuartzToShidenXCM = await helper.balance.getSubstrate(sender.address);1185    console.log(`QTZ Balance on Quartz after XCM is: ${balanceAfterQuartzToShidenXCM}`);1186    console.log(`Quartz's QTZ commission is: ${balanceBefore - balanceAfterQuartzToShidenXCM}`);1187    expect(balanceBefore - balanceAfterQuartzToShidenXCM > 0).to.be.true;11881189    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1190      await helper.wait.newBlocks(3);1191      const xcQTZbalance = await helper.assets.account(QTZ_ASSET_ID_ON_SHIDEN, sender.address);1192      const shidenBalance = await helper.balance.getSubstrate(sender.address);11931194      console.log(`xcQTZ balance on Shiden after XCM is: ${xcQTZbalance}`);1195      console.log(`Shiden's QTZ commission is: ${qtzToShidenTransferred - xcQTZbalance!}`);11961197      expect(xcQTZbalance).to.eq(qtzToShidenArrived);1198      // SHD balance does not changed:1199      expect(shidenBalance).to.eq(shidenInitialBalance);1200    });1201  });12021203  itSub('Should connect to Shiden and send QTZ back', async ({helper}) => {1204    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1205      const destination = {1206        V1: {1207          parents: 1,1208          interior: {1209            X1: {1210              Parachain: QUARTZ_CHAIN,1211            },1212          },1213        },1214      };12151216      const beneficiary = {1217        V1: {1218          parents: 0,1219          interior: {1220            X1: {1221              AccountId32: {1222                network: 'Any',1223                id: sender.addressRaw,1224              },1225            },1226          },1227        },1228      };12291230      const assets = {1231        V1: [1232          {1233            id: {1234              Concrete: {1235                parents: 1,1236                interior: {1237                  X1: {1238                    Parachain: QUARTZ_CHAIN,1239                  },1240                },1241              },1242            },1243            fun: {1244              Fungible: qtzFromShidenTransfered,1245            },1246          },1247        ],1248      };12491250      // Initial balance is 1 SDN1251      const balanceSDNbefore = await helper.balance.getSubstrate(sender.address);1252      console.log(`SDN balance is: ${balanceSDNbefore}, it does not changed`);1253      expect(balanceSDNbefore).to.eq(shidenInitialBalance);12541255      const feeAssetItem = 0;1256      // this is non-standard polkadotXcm extension for Astar only. It calls InitiateReserveWithdraw1257      await helper.executeExtrinsic(sender, 'api.tx.polkadotXcm.reserveWithdrawAssets', [destination, beneficiary, assets, feeAssetItem]);12581259      // Balance after reserve transfer is less than 1 SDN1260      const xcQTZbalance = await helper.assets.account(QTZ_ASSET_ID_ON_SHIDEN, sender.address);1261      const balanceSDN = await helper.balance.getSubstrate(sender.address);1262      console.log(`xcQTZ balance on Shiden after XCM is: ${xcQTZbalance}`);12631264      // Assert: xcQTZ balance correctly decreased1265      expect(xcQTZbalance).to.eq(qtzOnShidenLeft);1266      // Assert: SDN balance is 0.996...1267      expect(balanceSDN / (10n ** (SHIDEN_DECIMALS - 3n))).to.eq(996n);1268    });12691270    await helper.wait.newBlocks(3);1271    const balanceQTZ = await helper.balance.getSubstrate(sender.address);1272    console.log(`QTZ Balance on Quartz after XCM is: ${balanceQTZ}`);1273    expect(balanceQTZ).to.eq(balanceAfterQuartzToShidenXCM + qtzFromShidenTransfered);1274  });1275});
after · tests/src/xcm/xcmQuartz.test.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {blake2AsHex} from '@polkadot/util-crypto';19import config from '../config';20import {XcmV2TraitsError} from '../interfaces';21import {itSub, expect, describeXCM, usingPlaygrounds, usingKaruraPlaygrounds, usingRelayPlaygrounds, usingMoonriverPlaygrounds, usingStateminePlaygrounds, usingShidenPlaygrounds} from '../util';22import {DevUniqueHelper} from '../util/playgrounds/unique.dev';2324const QUARTZ_CHAIN = 2095;25const STATEMINE_CHAIN = 1000;26const KARURA_CHAIN = 2000;27const MOONRIVER_CHAIN = 2023;28const SHIDEN_CHAIN = 2007;2930const STATEMINE_PALLET_INSTANCE = 50;3132const relayUrl = config.relayUrl;33const statemineUrl = config.statemineUrl;34const karuraUrl = config.karuraUrl;35const moonriverUrl = config.moonriverUrl;36const shidenUrl = config.shidenUrl;3738const RELAY_DECIMALS = 12;39const STATEMINE_DECIMALS = 12;40const KARURA_DECIMALS = 12;41const SHIDEN_DECIMALS = 18n;42const QTZ_DECIMALS = 18n;4344const TRANSFER_AMOUNT = 2000000000000000000000000n;4546const FUNDING_AMOUNT = 3_500_000_0000_000_000n;4748const TRANSFER_AMOUNT_RELAY = 50_000_000_000_000_000n;4950const USDT_ASSET_ID = 100;51const USDT_ASSET_METADATA_DECIMALS = 18;52const USDT_ASSET_METADATA_NAME = 'USDT';53const USDT_ASSET_METADATA_DESCRIPTION = 'USDT';54const USDT_ASSET_METADATA_MINIMAL_BALANCE = 1n;55const USDT_ASSET_AMOUNT = 10_000_000_000_000_000_000_000_000n;5657const SAFE_XCM_VERSION = 2;5859describeXCM('[XCM] Integration test: Exchanging USDT with Statemine', () => {60  let alice: IKeyringPair;61  let bob: IKeyringPair;6263  let balanceStmnBefore: bigint;64  let balanceStmnAfter: bigint;6566  let balanceQuartzBefore: bigint;67  let balanceQuartzAfter: bigint;68  let balanceQuartzFinal: bigint;6970  let balanceBobBefore: bigint;71  let balanceBobAfter: bigint;72  let balanceBobFinal: bigint;7374  let balanceBobRelayTokenBefore: bigint;75  let balanceBobRelayTokenAfter: bigint;767778  before(async () => {79    await usingPlaygrounds(async (helper, privateKey) => {80      alice = await privateKey('//Alice');81      bob = await privateKey('//Bob'); // sovereign account on Statemine(t) funds donor8283      // Set the default version to wrap the first message to other chains.84      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);85    });8687    await usingRelayPlaygrounds(relayUrl, async (helper) => {88      // Fund accounts on Statemine(t)89      await helper.xcm.teleportNativeAsset(alice, STATEMINE_CHAIN, alice.addressRaw, FUNDING_AMOUNT);90      await helper.xcm.teleportNativeAsset(alice, STATEMINE_CHAIN, bob.addressRaw, FUNDING_AMOUNT);91    });9293    await usingStateminePlaygrounds(statemineUrl, async (helper) => {94      const sovereignFundingAmount = 3_500_000_000n;9596      await helper.assets.create(97        alice,98        USDT_ASSET_ID,99        alice.address,100        USDT_ASSET_METADATA_MINIMAL_BALANCE,101      );102      await helper.assets.setMetadata(103        alice,104        USDT_ASSET_ID,105        USDT_ASSET_METADATA_NAME,106        USDT_ASSET_METADATA_DESCRIPTION,107        USDT_ASSET_METADATA_DECIMALS,108      );109      await helper.assets.mint(110        alice,111        USDT_ASSET_ID,112        alice.address,113        USDT_ASSET_AMOUNT,114      );115116      // funding parachain sovereing account on Statemine(t).117      // The sovereign account should be created before any action118      // (the assets pallet on Statemine(t) check if the sovereign account exists)119      const parachainSovereingAccount = helper.address.paraSiblingSovereignAccount(QUARTZ_CHAIN);120      await helper.balance.transferToSubstrate(bob, parachainSovereingAccount, sovereignFundingAmount);121    });122123124    await usingPlaygrounds(async (helper) => {125      const location = {126        V2: {127          parents: 1,128          interior: {X3: [129            {130              Parachain: STATEMINE_CHAIN,131            },132            {133              PalletInstance: STATEMINE_PALLET_INSTANCE,134            },135            {136              GeneralIndex: USDT_ASSET_ID,137            },138          ]},139        },140      };141142      const metadata =143      {144        name: USDT_ASSET_ID,145        symbol: USDT_ASSET_METADATA_NAME,146        decimals: USDT_ASSET_METADATA_DECIMALS,147        minimalBalance: USDT_ASSET_METADATA_MINIMAL_BALANCE,148      };149      await helper.getSudo().foreignAssets.register(alice, alice.address, location, metadata);150      balanceQuartzBefore = await helper.balance.getSubstrate(alice.address);151    });152153154    // Providing the relay currency to the quartz sender account155    // (fee for USDT XCM are paid in relay tokens)156    await usingRelayPlaygrounds(relayUrl, async (helper) => {157      const destination = {158        V2: {159          parents: 0,160          interior: {X1: {161            Parachain: QUARTZ_CHAIN,162          },163          },164        }};165166      const beneficiary = {167        V2: {168          parents: 0,169          interior: {X1: {170            AccountId32: {171              network: 'Any',172              id: alice.addressRaw,173            },174          }},175        },176      };177178      const assets = {179        V2: [180          {181            id: {182              Concrete: {183                parents: 0,184                interior: 'Here',185              },186            },187            fun: {188              Fungible: TRANSFER_AMOUNT_RELAY,189            },190          },191        ],192      };193194      const feeAssetItem = 0;195196      await helper.xcm.limitedReserveTransferAssets(alice, destination, beneficiary, assets, feeAssetItem, 'Unlimited');197    });198199  });200201  itSub('Should connect and send USDT from Statemine to Quartz', async ({helper}) => {202    await usingStateminePlaygrounds(statemineUrl, async (helper) => {203      const dest = {204        V2: {205          parents: 1,206          interior: {X1: {207            Parachain: QUARTZ_CHAIN,208          },209          },210        }};211212      const beneficiary = {213        V2: {214          parents: 0,215          interior: {X1: {216            AccountId32: {217              network: 'Any',218              id: alice.addressRaw,219            },220          }},221        },222      };223224      const assets = {225        V2: [226          {227            id: {228              Concrete: {229                parents: 0,230                interior: {231                  X2: [232                    {233                      PalletInstance: STATEMINE_PALLET_INSTANCE,234                    },235                    {236                      GeneralIndex: USDT_ASSET_ID,237                    },238                  ]},239              },240            },241            fun: {242              Fungible: TRANSFER_AMOUNT,243            },244          },245        ],246      };247248      const feeAssetItem = 0;249250      balanceStmnBefore = await helper.balance.getSubstrate(alice.address);251      await helper.xcm.limitedReserveTransferAssets(alice, dest, beneficiary, assets, feeAssetItem, 'Unlimited');252253      balanceStmnAfter = await helper.balance.getSubstrate(alice.address);254255      // common good parachain take commission in it native token256      console.log(257        '[Statemine -> Quartz] transaction fees on Statemine: %s WND',258        helper.util.bigIntToDecimals(balanceStmnBefore - balanceStmnAfter, STATEMINE_DECIMALS),259      );260      expect(balanceStmnBefore > balanceStmnAfter).to.be.true;261262    });263264265    // ensure that asset has been delivered266    await helper.wait.newBlocks(3);267268    // expext collection id will be with id 1269    const free = await helper.ft.getBalance(1, {Substrate: alice.address});270271    balanceQuartzAfter = await helper.balance.getSubstrate(alice.address);272273    console.log(274      '[Statemine -> Quartz] transaction fees on Quartz: %s USDT',275      helper.util.bigIntToDecimals(TRANSFER_AMOUNT - free, USDT_ASSET_METADATA_DECIMALS),276    );277    console.log(278      '[Statemine -> Quartz] transaction fees on Quartz: %s QTZ',279      helper.util.bigIntToDecimals(balanceQuartzAfter - balanceQuartzBefore),280    );281    // commission has not paid in USDT token282    expect(free).to.be.equal(TRANSFER_AMOUNT);283    // ... and parachain native token284    expect(balanceQuartzAfter == balanceQuartzBefore).to.be.true;285  });286287  itSub('Should connect and send USDT from Quartz to Statemine back', async ({helper}) => {288    const destination = {289      V2: {290        parents: 1,291        interior: {X2: [292          {293            Parachain: STATEMINE_CHAIN,294          },295          {296            AccountId32: {297              network: 'Any',298              id: alice.addressRaw,299            },300          },301        ]},302      },303    };304305    const relayFee = 400_000_000_000_000n;306    const currencies: [any, bigint][] = [307      [308        {309          ForeignAssetId: 0,310        },311        TRANSFER_AMOUNT,312      ],313      [314        {315          NativeAssetId: 'Parent',316        },317        relayFee,318      ],319    ];320321    const feeItem = 1;322323    await helper.xTokens.transferMulticurrencies(alice, currencies, feeItem, destination, 'Unlimited');324325    // the commission has been paid in parachain native token326    balanceQuartzFinal = await helper.balance.getSubstrate(alice.address);327    console.log('[Quartz -> Statemine] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(balanceQuartzAfter - balanceQuartzFinal));328    expect(balanceQuartzAfter > balanceQuartzFinal).to.be.true;329330    await usingStateminePlaygrounds(statemineUrl, async (helper) => {331      await helper.wait.newBlocks(3);332333      // The USDT token never paid fees. Its amount not changed from begin value.334      // Also check that xcm transfer has been succeeded335      expect((await helper.assets.account(USDT_ASSET_ID, alice.address))! == USDT_ASSET_AMOUNT).to.be.true;336    });337  });338339  itSub('Should connect and send Relay token to Quartz', async ({helper}) => {340    balanceBobBefore = await helper.balance.getSubstrate(bob.address);341    balanceBobRelayTokenBefore = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});342343    await usingRelayPlaygrounds(relayUrl, async (helper) => {344      const destination = {345        V2: {346          parents: 0,347          interior: {X1: {348            Parachain: QUARTZ_CHAIN,349          },350          },351        }};352353      const beneficiary = {354        V2: {355          parents: 0,356          interior: {X1: {357            AccountId32: {358              network: 'Any',359              id: bob.addressRaw,360            },361          }},362        },363      };364365      const assets = {366        V2: [367          {368            id: {369              Concrete: {370                parents: 0,371                interior: 'Here',372              },373            },374            fun: {375              Fungible: TRANSFER_AMOUNT_RELAY,376            },377          },378        ],379      };380381      const feeAssetItem = 0;382383      await helper.xcm.limitedReserveTransferAssets(bob, destination, beneficiary, assets, feeAssetItem, 'Unlimited');384    });385386    await helper.wait.newBlocks(3);387388    balanceBobAfter = await helper.balance.getSubstrate(bob.address);389    balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});390391    const wndFeeOnQuartz = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;392    const wndDiffOnQuartz = balanceBobRelayTokenAfter - balanceBobRelayTokenBefore;393    console.log(394      '[Relay (Westend) -> Quartz] transaction fees: %s QTZ',395      helper.util.bigIntToDecimals(balanceBobAfter - balanceBobBefore),396    );397    console.log(398      '[Relay (Westend) -> Quartz] transaction fees: %s WND',399      helper.util.bigIntToDecimals(wndFeeOnQuartz, STATEMINE_DECIMALS),400    );401    console.log('[Relay (Westend) -> Quartz] actually delivered: %s WND', wndDiffOnQuartz);402    expect(wndFeeOnQuartz == 0n, 'No incoming WND fees should be taken').to.be.true;403    expect(balanceBobBefore == balanceBobAfter, 'No incoming QTZ fees should be taken').to.be.true;404  });405406  itSub('Should connect and send Relay token back', async ({helper}) => {407    let relayTokenBalanceBefore: bigint;408    let relayTokenBalanceAfter: bigint;409    await usingRelayPlaygrounds(relayUrl, async (helper) => {410      relayTokenBalanceBefore = await helper.balance.getSubstrate(bob.address);411    });412413    const destination = {414      V2: {415        parents: 1,416        interior: {417          X1:{418            AccountId32: {419              network: 'Any',420              id: bob.addressRaw,421            },422          },423        },424      },425    };426427    const currencies: any = [428      [429        {430          NativeAssetId: 'Parent',431        },432        TRANSFER_AMOUNT_RELAY,433      ],434    ];435436    const feeItem = 0;437438    await helper.xTokens.transferMulticurrencies(bob, currencies, feeItem, destination, 'Unlimited');439440    balanceBobFinal = await helper.balance.getSubstrate(bob.address);441    console.log('[Quartz -> Relay (Westend)] transaction fees: %s QTZ',  helper.util.bigIntToDecimals(balanceBobAfter - balanceBobFinal));442443    await usingRelayPlaygrounds(relayUrl, async (helper) => {444      await helper.wait.newBlocks(10);445      relayTokenBalanceAfter = await helper.balance.getSubstrate(bob.address);446447      const diff = relayTokenBalanceAfter - relayTokenBalanceBefore;448      console.log('[Quartz -> Relay (Westend)] actually delivered: %s WND', helper.util.bigIntToDecimals(diff, RELAY_DECIMALS));449      expect(diff > 0, 'Relay tokens was not delivered back').to.be.true;450    });451  });452});453454describeXCM('[XCM] Integration test: Exchanging tokens with Karura', () => {455  let alice: IKeyringPair;456  let randomAccount: IKeyringPair;457458  let balanceQuartzTokenInit: bigint;459  let balanceQuartzTokenMiddle: bigint;460  let balanceQuartzTokenFinal: bigint;461  let balanceKaruraTokenInit: bigint;462  let balanceKaruraTokenMiddle: bigint;463  let balanceKaruraTokenFinal: bigint;464  let balanceQuartzForeignTokenInit: bigint;465  let balanceQuartzForeignTokenMiddle: bigint;466  let balanceQuartzForeignTokenFinal: bigint;467468  // computed by a test transfer from prod Quartz to prod Karura.469  // 2 QTZ sent https://quartz.subscan.io/xcm_message/kusama-f60d821b049f8835a3005ce7102285006f5b61e9470  // 1.919176000000000000 QTZ received (you can check Karura's chain state in the corresponding block)471  const expectedKaruraIncomeFee = 2000000000000000000n - 1919176000000000000n;472473  const KARURA_BACKWARD_TRANSFER_AMOUNT = TRANSFER_AMOUNT - expectedKaruraIncomeFee;474475  before(async () => {476    await usingPlaygrounds(async (helper, privateKey) => {477      alice = await privateKey('//Alice');478      [randomAccount] = await helper.arrange.createAccounts([0n], alice);479480      // Set the default version to wrap the first message to other chains.481      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);482    });483484    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {485      const destination = {486        V1: {487          parents: 1,488          interior: {489            X1: {490              Parachain: QUARTZ_CHAIN,491            },492          },493        },494      };495496      const metadata = {497        name: 'Quartz',498        symbol: 'QTZ',499        decimals: 18,500        minimalBalance: 1000000000000000000n,501      };502503      await helper.getSudo().assetRegistry.registerForeignAsset(alice, destination, metadata);504      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);505      balanceKaruraTokenInit = await helper.balance.getSubstrate(randomAccount.address);506      balanceQuartzForeignTokenInit = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});507    });508509    await usingPlaygrounds(async (helper) => {510      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10n * TRANSFER_AMOUNT);511      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccount.address);512    });513  });514515  itSub('Should connect and send QTZ to Karura', async ({helper}) => {516    const destination = {517      V2: {518        parents: 1,519        interior: {520          X1: {521            Parachain: KARURA_CHAIN,522          },523        },524      },525    };526527    const beneficiary = {528      V2: {529        parents: 0,530        interior: {531          X1: {532            AccountId32: {533              network: 'Any',534              id: randomAccount.addressRaw,535            },536          },537        },538      },539    };540541    const assets = {542      V2: [543        {544          id: {545            Concrete: {546              parents: 0,547              interior: 'Here',548            },549          },550          fun: {551            Fungible: TRANSFER_AMOUNT,552          },553        },554      ],555    };556557    const feeAssetItem = 0;558559    await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');560    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);561562    const qtzFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;563    expect(qtzFees > 0n, 'Negative fees QTZ, looks like nothing was transferred').to.be.true;564    console.log('[Quartz -> Karura] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));565566    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {567      await helper.wait.newBlocks(3);568569      balanceQuartzForeignTokenMiddle = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});570      balanceKaruraTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);571572      const karFees = balanceKaruraTokenInit - balanceKaruraTokenMiddle;573      const qtzIncomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenInit;574      const karUnqFees = TRANSFER_AMOUNT - qtzIncomeTransfer;575576      console.log(577        '[Quartz -> Karura] transaction fees on Karura: %s KAR',578        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),579      );580      console.log(581        '[Quartz -> Karura] transaction fees on Karura: %s QTZ',582        helper.util.bigIntToDecimals(karUnqFees),583      );584      console.log('[Quartz -> Karura] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));585      expect(karFees == 0n).to.be.true;586      expect(587        karUnqFees == expectedKaruraIncomeFee,588        'Karura took different income fee, check the Karura foreign asset config',589      ).to.be.true;590    });591  });592593  itSub('Should connect to Karura and send QTZ back', async ({helper}) => {594    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {595      const destination = {596        V1: {597          parents: 1,598          interior: {599            X2: [600              {Parachain: QUARTZ_CHAIN},601              {602                AccountId32: {603                  network: 'Any',604                  id: randomAccount.addressRaw,605                },606              },607            ],608          },609        },610      };611612      const id = {613        ForeignAsset: 0,614      };615616      await helper.xTokens.transfer(randomAccount, id, KARURA_BACKWARD_TRANSFER_AMOUNT, destination, 'Unlimited');617      balanceKaruraTokenFinal = await helper.balance.getSubstrate(randomAccount.address);618      balanceQuartzForeignTokenFinal = await helper.tokens.accounts(randomAccount.address, id);619620      const karFees = balanceKaruraTokenMiddle - balanceKaruraTokenFinal;621      const qtzOutcomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenFinal;622623      console.log(624        '[Karura -> Quartz] transaction fees on Karura: %s KAR',625        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),626      );627      console.log('[Karura -> Quartz] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));628629      expect(karFees > 0, 'Negative fees KAR, looks like nothing was transferred').to.be.true;630      expect(qtzOutcomeTransfer == KARURA_BACKWARD_TRANSFER_AMOUNT).to.be.true;631    });632633    await helper.wait.newBlocks(3);634635    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccount.address);636    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;637    expect(actuallyDelivered > 0).to.be.true;638639    console.log('[Karura -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));640641    const qtzFees = KARURA_BACKWARD_TRANSFER_AMOUNT - actuallyDelivered;642    console.log('[Karura -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));643    expect(qtzFees == 0n).to.be.true;644  });645646  itSub('Karura can send only up to its balance', async ({helper}) => {647    // set Karura's sovereign account's balance648    const karuraBalance = 10000n * (10n ** QTZ_DECIMALS);649    const karuraSovereignAccount = helper.address.paraSiblingSovereignAccount(KARURA_CHAIN);650    await helper.getSudo().balance.setBalanceSubstrate(alice, karuraSovereignAccount, karuraBalance);651652    const moreThanKaruraHas = karuraBalance * 2n;653654    let targetAccountBalance = 0n;655    const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);656657    const quartzMultilocation = {658      V1: {659        parents: 1,660        interior: {661          X1: {Parachain: QUARTZ_CHAIN},662        },663      },664    };665666    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, moreThanKaruraHas);667668    // Try to trick Quartz669    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {670      await helper.getSudo().executeExtrinsic(671        alice,672        'api.tx.polkadotXcm.send',673        [674          quartzMultilocation,675          maliciousXcmProgram,676        ],677        true,678      );679    });680681    const maxWaitBlocks = 3;682683    const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(684      maxWaitBlocks,685      'xcmpQueue',686      'Fail',687    );688689    expect(690      xcmpQueueFailEvent != null,691      `'xcmpQueue.FailEvent' event is expected`,692    ).to.be.true;693694    expect(695      xcmpQueueFailEvent!.isFailedToTransactAsset,696      `The XCM error should be 'FailedToTransactAsset'`,697    ).to.be.true;698699    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);700    expect(targetAccountBalance).to.be.equal(0n);701702    // But Karura still can send the correct amount703    const validTransferAmount = karuraBalance / 2n;704    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, validTransferAmount);705706    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {707      await helper.getSudo().executeExtrinsic(708        alice,709        'api.tx.polkadotXcm.send',710        [711          quartzMultilocation,712          validXcmProgram,713        ],714        true,715      );716    });717718    await helper.wait.newBlocks(maxWaitBlocks);719720    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);721    expect(targetAccountBalance).to.be.equal(validTransferAmount);722  });723});724725// These tests are relevant only when726// the the corresponding foreign assets are not registered727describeXCM('[XCM] Integration test: Quartz rejects non-native tokens', () => {728  let alice: IKeyringPair;729  let alith: IKeyringPair;730731  const testAmount = 100_000_000_000n;732  let quartzParachainJunction;733  let quartzAccountJunction;734735  let quartzParachainMultilocation: any;736  let quartzAccountMultilocation: any;737  let quartzCombinedMultilocation: any;738739  before(async () => {740    await usingPlaygrounds(async (helper, privateKey) => {741      alice = await privateKey('//Alice');742743      quartzParachainJunction = {Parachain: QUARTZ_CHAIN};744      quartzAccountJunction = {745        AccountId32: {746          network: 'Any',747          id: alice.addressRaw,748        },749      };750751      quartzParachainMultilocation = {752        V1: {753          parents: 1,754          interior: {755            X1: quartzParachainJunction,756          },757        },758      };759760      quartzAccountMultilocation = {761        V1: {762          parents: 0,763          interior: {764            X1: quartzAccountJunction,765          },766        },767      };768769      quartzCombinedMultilocation = {770        V1: {771          parents: 1,772          interior: {773            X2: [quartzParachainJunction, quartzAccountJunction],774          },775        },776      };777778      // Set the default version to wrap the first message to other chains.779      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);780    });781782    // eslint-disable-next-line require-await783    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {784      alith = helper.account.alithAccount();785    });786  });787788  const expectFailedToTransact = async (network: string, helper: DevUniqueHelper) => {789    const maxWaitBlocks = 3;790791    const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(792      maxWaitBlocks,793      'xcmpQueue',794      'Fail',795    );796797    expect(798      xcmpQueueFailEvent != null,799      `[reject ${network} tokens] 'xcmpQueue.FailEvent' event is expected`,800    ).to.be.true;801802    expect(803      xcmpQueueFailEvent!.isFailedToTransactAsset,804      `[reject ${network} tokens] The XCM error should be 'FailedToTransactAsset'`,805    ).to.be.true;806  };807808  itSub('Quartz rejects KAR tokens from Karura', async ({helper}) => {809    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {810      const id = {811        Token: 'KAR',812      };813      const destination = quartzCombinedMultilocation;814      await helper.xTokens.transfer(alice, id, testAmount, destination, 'Unlimited');815    });816817    await expectFailedToTransact('KAR', helper);818  });819820  itSub('Quartz rejects MOVR tokens from Moonriver', async ({helper}) => {821    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {822      const id = 'SelfReserve';823      const destination = quartzCombinedMultilocation;824      await helper.xTokens.transfer(alith, id, testAmount, destination, 'Unlimited');825    });826827    await expectFailedToTransact('MOVR', helper);828  });829830  itSub('Quartz rejects SDN tokens from Shiden', async ({helper}) => {831    await usingShidenPlaygrounds(shidenUrl, async (helper) => {832      const destinationParachain = quartzParachainMultilocation;833      const beneficiary = quartzAccountMultilocation;834      const assets = {835        V1: [{836          id: {837            Concrete: {838              parents: 0,839              interior: 'Here',840            },841          },842          fun: {843            Fungible: testAmount,844          },845        }],846      };847      const feeAssetItem = 0;848849      await helper.executeExtrinsic(alice, 'api.tx.polkadotXcm.reserveWithdrawAssets', [850        destinationParachain,851        beneficiary,852        assets,853        feeAssetItem,854      ]);855    });856857    await expectFailedToTransact('SDN', helper);858  });859});860861describeXCM('[XCM] Integration test: Exchanging QTZ with Moonriver', () => {862  // Quartz constants863  let quartzDonor: IKeyringPair;864  let quartzAssetLocation;865866  let randomAccountQuartz: IKeyringPair;867  let randomAccountMoonriver: IKeyringPair;868869  // Moonriver constants870  let assetId: string;871872  const councilVotingThreshold = 2;873  const technicalCommitteeThreshold = 2;874  const votingPeriod = 3;875  const delayPeriod = 0;876877  const quartzAssetMetadata = {878    name: 'xcQuartz',879    symbol: 'xcQTZ',880    decimals: 18,881    isFrozen: false,882    minimalBalance: 1n,883  };884885  let balanceQuartzTokenInit: bigint;886  let balanceQuartzTokenMiddle: bigint;887  let balanceQuartzTokenFinal: bigint;888  let balanceForeignQtzTokenInit: bigint;889  let balanceForeignQtzTokenMiddle: bigint;890  let balanceForeignQtzTokenFinal: bigint;891  let balanceMovrTokenInit: bigint;892  let balanceMovrTokenMiddle: bigint;893  let balanceMovrTokenFinal: bigint;894895  before(async () => {896    await usingPlaygrounds(async (helper, privateKey) => {897      quartzDonor = await privateKey('//Alice');898      [randomAccountQuartz] = await helper.arrange.createAccounts([0n], quartzDonor);899900      balanceForeignQtzTokenInit = 0n;901902      // Set the default version to wrap the first message to other chains.903      const alice = quartzDonor;904      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);905    });906907    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {908      const alithAccount = helper.account.alithAccount();909      const baltatharAccount = helper.account.baltatharAccount();910      const dorothyAccount = helper.account.dorothyAccount();911912      randomAccountMoonriver = helper.account.create();913914      // >>> Sponsoring Dorothy >>>915      console.log('Sponsoring Dorothy.......');916      await helper.balance.transferToEthereum(alithAccount, dorothyAccount.address, 11_000_000_000_000_000_000n);917      console.log('Sponsoring Dorothy.......DONE');918      // <<< Sponsoring Dorothy <<<919920      quartzAssetLocation = {921        XCM: {922          parents: 1,923          interior: {X1: {Parachain: QUARTZ_CHAIN}},924        },925      };926      const existentialDeposit = 1n;927      const isSufficient = true;928      const unitsPerSecond = 1n;929      const numAssetsWeightHint = 0;930931      const encodedProposal = helper.assetManager.makeRegisterForeignAssetProposal({932        location: quartzAssetLocation,933        metadata: quartzAssetMetadata,934        existentialDeposit,935        isSufficient,936        unitsPerSecond,937        numAssetsWeightHint,938      });939      const proposalHash = blake2AsHex(encodedProposal);940941      console.log('Encoded proposal for registerForeignAsset & setAssetUnitsPerSecond is %s', encodedProposal);942      console.log('Encoded length %d', encodedProposal.length);943      console.log('Encoded proposal hash for batch utility after schedule is %s', proposalHash);944945      // >>> Note motion preimage >>>946      console.log('Note motion preimage.......');947      await helper.democracy.notePreimage(baltatharAccount, encodedProposal);948      console.log('Note motion preimage.......DONE');949      // <<< Note motion preimage <<<950951      // >>> Propose external motion through council >>>952      console.log('Propose external motion through council.......');953      const externalMotion = helper.democracy.externalProposeMajority({Legacy: proposalHash});954      const encodedMotion = externalMotion?.method.toHex() || '';955      const motionHash = blake2AsHex(encodedMotion);956      console.log('Motion hash is %s', motionHash);957958      await helper.collective.council.propose(baltatharAccount, councilVotingThreshold, externalMotion, externalMotion.encodedLength);959960      const councilProposalIdx = await helper.collective.council.proposalCount() - 1;961      await helper.collective.council.vote(dorothyAccount, motionHash, councilProposalIdx, true);962      await helper.collective.council.vote(baltatharAccount, motionHash, councilProposalIdx, true);963964      await helper.collective.council.close(965        dorothyAccount,966        motionHash,967        councilProposalIdx,968        {969          refTime: 1_000_000_000,970          proofSize: 1_000_000,971        },972        externalMotion.encodedLength,973      );974      console.log('Propose external motion through council.......DONE');975      // <<< Propose external motion through council <<<976977      // >>> Fast track proposal through technical committee >>>978      console.log('Fast track proposal through technical committee.......');979      const fastTrack = helper.democracy.fastTrack(proposalHash, votingPeriod, delayPeriod);980      const encodedFastTrack = fastTrack?.method.toHex() || '';981      const fastTrackHash = blake2AsHex(encodedFastTrack);982      console.log('FastTrack hash is %s', fastTrackHash);983984      await helper.collective.techCommittee.propose(alithAccount, technicalCommitteeThreshold, fastTrack, fastTrack.encodedLength);985986      const techProposalIdx = await helper.collective.techCommittee.proposalCount() - 1;987      await helper.collective.techCommittee.vote(baltatharAccount, fastTrackHash, techProposalIdx, true);988      await helper.collective.techCommittee.vote(alithAccount, fastTrackHash, techProposalIdx, true);989990      await helper.collective.techCommittee.close(991        baltatharAccount,992        fastTrackHash,993        techProposalIdx,994        {995          refTime: 1_000_000_000,996          proofSize: 1_000_000,997        },998        fastTrack.encodedLength,999      );1000      console.log('Fast track proposal through technical committee.......DONE');1001      // <<< Fast track proposal through technical committee <<<10021003      // >>> Referendum voting >>>1004      console.log('Referendum voting.......');1005      await helper.democracy.referendumVote(dorothyAccount, 0, {1006        balance: 10_000_000_000_000_000_000n,1007        vote: {aye: true, conviction: 1},1008      });1009      console.log('Referendum voting.......DONE');1010      // <<< Referendum voting <<<10111012      // >>> Acquire Quartz AssetId Info on Moonriver >>>1013      console.log('Acquire Quartz AssetId Info on Moonriver.......');10141015      // Wait for the democracy execute1016      await helper.wait.newBlocks(5);10171018      assetId = (await helper.assetManager.assetTypeId(quartzAssetLocation)).toString();10191020      console.log('QTZ asset ID is %s', assetId);1021      console.log('Acquire Quartz AssetId Info on Moonriver.......DONE');1022      // >>> Acquire Quartz AssetId Info on Moonriver >>>10231024      // >>> Sponsoring random Account >>>1025      console.log('Sponsoring random Account.......');1026      await helper.balance.transferToEthereum(baltatharAccount, randomAccountMoonriver.address, 11_000_000_000_000_000_000n);1027      console.log('Sponsoring random Account.......DONE');1028      // <<< Sponsoring random Account <<<10291030      balanceMovrTokenInit = await helper.balance.getEthereum(randomAccountMoonriver.address);1031    });10321033    await usingPlaygrounds(async (helper) => {1034      await helper.balance.transferToSubstrate(quartzDonor, randomAccountQuartz.address, 10n * TRANSFER_AMOUNT);1035      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccountQuartz.address);1036    });1037  });10381039  itSub('Should connect and send QTZ to Moonriver', async ({helper}) => {1040    const currencyId = {1041      NativeAssetId: 'Here',1042    };1043    const dest = {1044      V2: {1045        parents: 1,1046        interior: {1047          X2: [1048            {Parachain: MOONRIVER_CHAIN},1049            {AccountKey20: {network: 'Any', key: randomAccountMoonriver.address}},1050          ],1051        },1052      },1053    };1054    const amount = TRANSFER_AMOUNT;10551056    await helper.xTokens.transfer(randomAccountQuartz, currencyId, amount, dest, 'Unlimited');10571058    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccountQuartz.address);1059    expect(balanceQuartzTokenMiddle < balanceQuartzTokenInit).to.be.true;10601061    const transactionFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;1062    console.log('[Quartz -> Moonriver] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(transactionFees));1063    expect(transactionFees > 0, 'Negative fees QTZ, looks like nothing was transferred').to.be.true;10641065    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1066      await helper.wait.newBlocks(3);10671068      balanceMovrTokenMiddle = await helper.balance.getEthereum(randomAccountMoonriver.address);10691070      const movrFees = balanceMovrTokenInit - balanceMovrTokenMiddle;1071      console.log('[Quartz -> Moonriver] transaction fees on Moonriver: %s MOVR',helper.util.bigIntToDecimals(movrFees));1072      expect(movrFees == 0n).to.be.true;10731074      balanceForeignQtzTokenMiddle = (await helper.assets.account(assetId, randomAccountMoonriver.address))!; // BigInt(qtzRandomAccountAsset['balance']);1075      const qtzIncomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenInit;1076      console.log('[Quartz -> Moonriver] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));1077      expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;1078    });1079  });10801081  itSub('Should connect to Moonriver and send QTZ back', async ({helper}) => {1082    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1083      const asset = {1084        V1: {1085          id: {1086            Concrete: {1087              parents: 1,1088              interior: {1089                X1: {Parachain: QUARTZ_CHAIN},1090              },1091            },1092          },1093          fun: {1094            Fungible: TRANSFER_AMOUNT,1095          },1096        },1097      };1098      const destination = {1099        V1: {1100          parents: 1,1101          interior: {1102            X2: [1103              {Parachain: QUARTZ_CHAIN},1104              {AccountId32: {network: 'Any', id: randomAccountQuartz.addressRaw}},1105            ],1106          },1107        },1108      };11091110      await helper.xTokens.transferMultiasset(randomAccountMoonriver, asset, destination, 'Unlimited');11111112      balanceMovrTokenFinal = await helper.balance.getEthereum(randomAccountMoonriver.address);11131114      const movrFees = balanceMovrTokenMiddle - balanceMovrTokenFinal;1115      console.log('[Moonriver -> Quartz] transaction fees on Moonriver: %s MOVR', helper.util.bigIntToDecimals(movrFees));1116      expect(movrFees > 0, 'Negative fees MOVR, looks like nothing was transferred').to.be.true;11171118      const qtzRandomAccountAsset = await helper.assets.account(assetId, randomAccountMoonriver.address);11191120      expect(qtzRandomAccountAsset).to.be.null;11211122      balanceForeignQtzTokenFinal = 0n;11231124      const qtzOutcomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenFinal;1125      console.log('[Quartz -> Moonriver] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));1126      expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;1127    });11281129    await helper.wait.newBlocks(3);11301131    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccountQuartz.address);1132    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;1133    expect(actuallyDelivered > 0).to.be.true;11341135    console.log('[Moonriver -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));11361137    const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;1138    console.log('[Moonriver -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));1139    expect(qtzFees == 0n).to.be.true;1140  });11411142  itSub.skip('Moonriver can send only up to its balance', async ({helper}) => {1143    throw Error("Not yet implemented");1144  });1145});11461147describeXCM('[XCM] Integration test: Exchanging tokens with Shiden', () => {1148  let alice: IKeyringPair;1149  let sender: IKeyringPair;11501151  const QTZ_ASSET_ID_ON_SHIDEN = 1;1152  const QTZ_MINIMAL_BALANCE_ON_SHIDEN = 1n;11531154  // Quartz -> Shiden1155  const shidenInitialBalance = 1n * (10n ** SHIDEN_DECIMALS); // 1 SHD, existential deposit required to actually create the account on Shiden1156  const unitsPerSecond = 228_000_000_000n; // This is Phala's value. What will be ours?1157  const qtzToShidenTransferred = 10n * (10n ** QTZ_DECIMALS); // 10 QTZ1158  const qtzToShidenArrived = 9_999_999_999_088_000_000n; // 9.999 ... QTZ, Shiden takes a commision in foreign tokens11591160  // Shiden -> Quartz1161  const qtzFromShidenTransfered = 5n * (10n ** QTZ_DECIMALS); // 5 QTZ1162  const qtzOnShidenLeft = qtzToShidenArrived - qtzFromShidenTransfered; // 4.999_999_999_088_000_000n QTZ11631164  let balanceAfterQuartzToShidenXCM: bigint;11651166  before(async () => {1167    await usingPlaygrounds(async (helper, privateKey) => {1168      alice = await privateKey('//Alice');1169      [sender] = await helper.arrange.createAccounts([100n], alice);1170      console.log('sender', sender.address);11711172      // Set the default version to wrap the first message to other chains.1173      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);1174    });11751176    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1177      console.log('1. Create foreign asset and metadata');1178      // TODO update metadata with values from production1179      await helper.assets.create(1180        alice,1181        QTZ_ASSET_ID_ON_SHIDEN,1182        alice.address,1183        QTZ_MINIMAL_BALANCE_ON_SHIDEN,1184      );11851186      await helper.assets.setMetadata(1187        alice,1188        QTZ_ASSET_ID_ON_SHIDEN,1189        'Cross chain QTZ',1190        'xcQTZ',1191        Number(QTZ_DECIMALS),1192      );11931194      console.log('2. Register asset location on Shiden');1195      const assetLocation = {1196        V1: {1197          parents: 1,1198          interior: {1199            X1: {1200              Parachain: QUARTZ_CHAIN,1201            },1202          },1203        },1204      };12051206      await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.registerAssetLocation', [assetLocation, QTZ_ASSET_ID_ON_SHIDEN]);12071208      console.log('3. Set QTZ payment for XCM execution on Shiden');1209      await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.setAssetUnitsPerSecond', [assetLocation, unitsPerSecond]);12101211      console.log('4. Transfer 1 SDN to recipient to create the account (needed due to existential balance)');1212      await helper.balance.transferToSubstrate(alice, sender.address, shidenInitialBalance);1213    });1214  });12151216  itSub('Should connect and send QTZ to Shiden', async ({helper}) => {1217    const destination = {1218      V2: {1219        parents: 1,1220        interior: {1221          X1: {1222            Parachain: SHIDEN_CHAIN,1223          },1224        },1225      },1226    };12271228    const beneficiary = {1229      V2: {1230        parents: 0,1231        interior: {1232          X1: {1233            AccountId32: {1234              network: 'Any',1235              id: sender.addressRaw,1236            },1237          },1238        },1239      },1240    };12411242    const assets = {1243      V2: [1244        {1245          id: {1246            Concrete: {1247              parents: 0,1248              interior: 'Here',1249            },1250          },1251          fun: {1252            Fungible: qtzToShidenTransferred,1253          },1254        },1255      ],1256    };12571258    // Initial balance is 100 QTZ1259    const balanceBefore = await helper.balance.getSubstrate(sender.address);1260    console.log(`Initial balance is: ${balanceBefore}`);12611262    const feeAssetItem = 0;1263    await helper.xcm.limitedReserveTransferAssets(sender, destination, beneficiary, assets, feeAssetItem, 'Unlimited');12641265    // Balance after reserve transfer is less than 901266    balanceAfterQuartzToShidenXCM = await helper.balance.getSubstrate(sender.address);1267    console.log(`QTZ Balance on Quartz after XCM is: ${balanceAfterQuartzToShidenXCM}`);1268    console.log(`Quartz's QTZ commission is: ${balanceBefore - balanceAfterQuartzToShidenXCM}`);1269    expect(balanceBefore - balanceAfterQuartzToShidenXCM > 0).to.be.true;12701271    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1272      await helper.wait.newBlocks(3);1273      const xcQTZbalance = await helper.assets.account(QTZ_ASSET_ID_ON_SHIDEN, sender.address);1274      const shidenBalance = await helper.balance.getSubstrate(sender.address);12751276      console.log(`xcQTZ balance on Shiden after XCM is: ${xcQTZbalance}`);1277      console.log(`Shiden's QTZ commission is: ${qtzToShidenTransferred - xcQTZbalance!}`);12781279      expect(xcQTZbalance).to.eq(qtzToShidenArrived);1280      // SHD balance does not changed:1281      expect(shidenBalance).to.eq(shidenInitialBalance);1282    });1283  });12841285  itSub('Should connect to Shiden and send QTZ back', async ({helper}) => {1286    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1287      const destination = {1288        V1: {1289          parents: 1,1290          interior: {1291            X1: {1292              Parachain: QUARTZ_CHAIN,1293            },1294          },1295        },1296      };12971298      const beneficiary = {1299        V1: {1300          parents: 0,1301          interior: {1302            X1: {1303              AccountId32: {1304                network: 'Any',1305                id: sender.addressRaw,1306              },1307            },1308          },1309        },1310      };13111312      const assets = {1313        V1: [1314          {1315            id: {1316              Concrete: {1317                parents: 1,1318                interior: {1319                  X1: {1320                    Parachain: QUARTZ_CHAIN,1321                  },1322                },1323              },1324            },1325            fun: {1326              Fungible: qtzFromShidenTransfered,1327            },1328          },1329        ],1330      };13311332      // Initial balance is 1 SDN1333      const balanceSDNbefore = await helper.balance.getSubstrate(sender.address);1334      console.log(`SDN balance is: ${balanceSDNbefore}, it does not changed`);1335      expect(balanceSDNbefore).to.eq(shidenInitialBalance);13361337      const feeAssetItem = 0;1338      // this is non-standard polkadotXcm extension for Astar only. It calls InitiateReserveWithdraw1339      await helper.executeExtrinsic(sender, 'api.tx.polkadotXcm.reserveWithdrawAssets', [destination, beneficiary, assets, feeAssetItem]);13401341      // Balance after reserve transfer is less than 1 SDN1342      const xcQTZbalance = await helper.assets.account(QTZ_ASSET_ID_ON_SHIDEN, sender.address);1343      const balanceSDN = await helper.balance.getSubstrate(sender.address);1344      console.log(`xcQTZ balance on Shiden after XCM is: ${xcQTZbalance}`);13451346      // Assert: xcQTZ balance correctly decreased1347      expect(xcQTZbalance).to.eq(qtzOnShidenLeft);1348      // Assert: SDN balance is 0.996...1349      expect(balanceSDN / (10n ** (SHIDEN_DECIMALS - 3n))).to.eq(996n);1350    });13511352    await helper.wait.newBlocks(3);1353    const balanceQTZ = await helper.balance.getSubstrate(sender.address);1354    console.log(`QTZ Balance on Quartz after XCM is: ${balanceQTZ}`);1355    expect(balanceQTZ).to.eq(balanceAfterQuartzToShidenXCM + qtzFromShidenTransfered);1356  });13571358  itSub('Shiden can send only up to its balance', async ({helper}) => {1359    // set Shiden's sovereign account's balance1360    const shidenBalance = 10000n * (10n ** QTZ_DECIMALS);1361    const shidenSovereignAccount = helper.address.paraSiblingSovereignAccount(SHIDEN_CHAIN);1362    await helper.getSudo().balance.setBalanceSubstrate(alice, shidenSovereignAccount, shidenBalance);13631364    const moreThanShidenHas = shidenBalance * 2n;13651366    let targetAccountBalance = 0n;1367    const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);13681369    const quartzMultilocation = {1370      V1: {1371        parents: 1,1372        interior: {1373          X1: {Parachain: QUARTZ_CHAIN},1374        },1375      },1376    };13771378    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, moreThanShidenHas);13791380    // Try to trick Quartz1381    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1382      await helper.getSudo().executeExtrinsic(1383        alice,1384        'api.tx.polkadotXcm.send',1385        [1386          quartzMultilocation,1387          maliciousXcmProgram,1388        ],1389        true,1390      );1391    });13921393    const maxWaitBlocks = 3;13941395    const xcmpQueueFailEvent = await helper.wait.eventOutcome<XcmV2TraitsError>(1396      maxWaitBlocks,1397      'xcmpQueue',1398      'Fail',1399    );14001401    expect(1402      xcmpQueueFailEvent != null,1403      `'xcmpQueue.FailEvent' event is expected`,1404    ).to.be.true;14051406    expect(1407      xcmpQueueFailEvent!.isFailedToTransactAsset,1408      `The XCM error should be 'FailedToTransactAsset'`,1409    ).to.be.true;14101411    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);1412    expect(targetAccountBalance).to.be.equal(0n);14131414    // But Shiden still can send the correct amount1415    const validTransferAmount = shidenBalance / 2n;1416    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, validTransferAmount);14171418    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1419      await helper.getSudo().executeExtrinsic(1420        alice,1421        'api.tx.polkadotXcm.send',1422        [1423          quartzMultilocation,1424          validXcmProgram,1425        ],1426        true,1427      );1428    });14291430    await helper.wait.newBlocks(maxWaitBlocks);14311432    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);1433    expect(targetAccountBalance).to.be.equal(validTransferAmount);1434  });1435});
modifiedtests/src/xcm/xcmUnique.test.tsdiffbeforeafterboth
--- a/tests/src/xcm/xcmUnique.test.ts
+++ b/tests/src/xcm/xcmUnique.test.ts
@@ -644,6 +644,84 @@
     console.log('[Acala -> Unique] transaction fees on Unique: %s UNQ', helper.util.bigIntToDecimals(unqFees));
     expect(unqFees == 0n).to.be.true;
   });
+
+  itSub('Acala can send only up to its balance', async ({helper}) => {
+    // set Acala's sovereign account's balance
+    const acalaBalance = 10000n * (10n ** UNQ_DECIMALS);
+    const acalaSovereignAccount = helper.address.paraSiblingSovereignAccount(ACALA_CHAIN);
+    await helper.getSudo().balance.setBalanceSubstrate(alice, acalaSovereignAccount, acalaBalance);
+
+    const moreThanAcalaHas = acalaBalance * 2n;
+
+    let targetAccountBalance = 0n;
+    const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);
+
+    const uniqueMultilocation = {
+      V1: {
+        parents: 1,
+        interior: {
+          X1: {Parachain: UNIQUE_CHAIN},
+        },
+      },
+    };
+
+    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, moreThanAcalaHas);
+
+    // Try to trick Unique
+    await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
+      await helper.getSudo().executeExtrinsic(
+        alice,
+        'api.tx.polkadotXcm.send',
+        [
+          uniqueMultilocation,
+          maliciousXcmProgram,
+        ],
+        true,
+      );
+    });
+
+    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!.isFailedToTransactAsset,
+      `The XCM error should be 'FailedToTransactAsset'`,
+    ).to.be.true;
+
+    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+    expect(targetAccountBalance).to.be.equal(0n);
+
+    // But Acala still can send the correct amount
+    const validTransferAmount = acalaBalance / 2n;
+    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, validTransferAmount);
+
+    await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
+      await helper.getSudo().executeExtrinsic(
+        alice,
+        'api.tx.polkadotXcm.send',
+        [
+          uniqueMultilocation,
+          validXcmProgram,
+        ],
+        true,
+      );
+    });
+
+    await helper.wait.newBlocks(maxWaitBlocks);
+
+    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+    expect(targetAccountBalance).to.be.equal(validTransferAmount);
+  });
 });
 
 // These tests are relevant only when
@@ -1063,6 +1141,10 @@
     console.log('[Moonbeam -> Unique] transaction fees on Unique: %s UNQ', helper.util.bigIntToDecimals(unqFees));
     expect(unqFees == 0n).to.be.true;
   });
+
+  itSub.skip('Moonbeam can send only up to its balance', async ({helper}) => {
+    throw Error("Not yet implemented");
+  });
 });
 
 describeXCM('[XCM] Integration test: Exchanging tokens with Astar', () => {
@@ -1330,4 +1412,82 @@
       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);
+    const astarSovereignAccount = helper.address.paraSiblingSovereignAccount(ASTAR_CHAIN);
+    await helper.getSudo().balance.setBalanceSubstrate(alice, astarSovereignAccount, astarBalance);
+
+    const moreThanShidenHas = astarBalance * 2n;
+
+    let targetAccountBalance = 0n;
+    const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);
+
+    const uniqueMultilocation = {
+      V1: {
+        parents: 1,
+        interior: {
+          X1: {Parachain: UNIQUE_CHAIN},
+        },
+      },
+    };
+
+    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, moreThanShidenHas);
+
+    // Try to trick Unique
+    await usingAstarPlaygrounds(astarUrl, async (helper) => {
+      await helper.getSudo().executeExtrinsic(
+        alice,
+        'api.tx.polkadotXcm.send',
+        [
+          uniqueMultilocation,
+          maliciousXcmProgram,
+        ],
+        true,
+      );
+    });
+
+    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!.isFailedToTransactAsset,
+      `The XCM error should be 'FailedToTransactAsset'`,
+    ).to.be.true;
+
+    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+    expect(targetAccountBalance).to.be.equal(0n);
+
+    // But Astar still can send the correct amount
+    const validTransferAmount = astarBalance / 2n;
+    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(targetAccount.addressRaw, validTransferAmount);
+
+    await usingAstarPlaygrounds(astarUrl, async (helper) => {
+      await helper.getSudo().executeExtrinsic(
+        alice,
+        'api.tx.polkadotXcm.send',
+        [
+          uniqueMultilocation,
+          validXcmProgram,
+        ],
+        true,
+      );
+    });
+
+    await helper.wait.newBlocks(maxWaitBlocks);
+
+    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+    expect(targetAccountBalance).to.be.equal(validTransferAmount);
+  });
 });