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

difftreelog

source

tests/src/xcm/xcmQuartz.test.ts53.7 KiBsourcehistory
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 {itSub, expect, describeXCM, usingPlaygrounds, usingKaruraPlaygrounds, usingRelayPlaygrounds, usingMoonriverPlaygrounds, usingStateminePlaygrounds, usingShidenPlaygrounds} from '../util';19import {DevUniqueHelper, Event} from '../util/playgrounds/unique.dev';20import {STATEMINE_CHAIN, QUARTZ_CHAIN, KARURA_CHAIN, MOONRIVER_CHAIN, SHIDEN_CHAIN, STATEMINE_DECIMALS, KARURA_DECIMALS, QTZ_DECIMALS, RELAY_DECIMALS, SHIDEN_DECIMALS, karuraUrl, moonriverUrl, relayUrl, shidenUrl, statemineUrl} from './xcm.types';21222324const STATEMINE_PALLET_INSTANCE = 50;2526const TRANSFER_AMOUNT = 2000000000000000000000000n;2728const FUNDING_AMOUNT = 3_500_000_0000_000_000n;2930const TRANSFER_AMOUNT_RELAY = 50_000_000_000_000_000n;3132const USDT_ASSET_ID = 100;33const USDT_ASSET_METADATA_DECIMALS = 18;34const USDT_ASSET_METADATA_NAME = 'USDT';35const USDT_ASSET_METADATA_DESCRIPTION = 'USDT';36const USDT_ASSET_METADATA_MINIMAL_BALANCE = 1n;37const USDT_ASSET_AMOUNT = 10_000_000_000_000_000_000_000_000n;3839const SAFE_XCM_VERSION = 2;4041describeXCM('[XCM] Integration test: Exchanging USDT with Statemine', () => {42  let alice: IKeyringPair;43  let bob: IKeyringPair;4445  let balanceStmnBefore: bigint;46  let balanceStmnAfter: bigint;4748  let balanceQuartzBefore: bigint;49  let balanceQuartzAfter: bigint;50  let balanceQuartzFinal: bigint;5152  let balanceBobBefore: bigint;53  let balanceBobAfter: bigint;54  let balanceBobFinal: bigint;5556  let balanceBobRelayTokenBefore: bigint;57  let balanceBobRelayTokenAfter: bigint;585960  before(async () => {61    await usingPlaygrounds(async (helper, privateKey) => {62      alice = await privateKey('//Alice');63      bob = await privateKey('//Bob'); // sovereign account on Statemine(t) funds donor6465      // Set the default version to wrap the first message to other chains.66      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);67    });6869    await usingRelayPlaygrounds(relayUrl, async (helper) => {70      // Fund accounts on Statemine(t)71      await helper.xcm.teleportNativeAsset(alice, STATEMINE_CHAIN, alice.addressRaw, FUNDING_AMOUNT);72      await helper.xcm.teleportNativeAsset(alice, STATEMINE_CHAIN, bob.addressRaw, FUNDING_AMOUNT);73    });7475    await usingStateminePlaygrounds(statemineUrl, async (helper) => {76      const sovereignFundingAmount = 3_500_000_000n;7778      await helper.assets.create(79        alice,80        USDT_ASSET_ID,81        alice.address,82        USDT_ASSET_METADATA_MINIMAL_BALANCE,83      );84      await helper.assets.setMetadata(85        alice,86        USDT_ASSET_ID,87        USDT_ASSET_METADATA_NAME,88        USDT_ASSET_METADATA_DESCRIPTION,89        USDT_ASSET_METADATA_DECIMALS,90      );91      await helper.assets.mint(92        alice,93        USDT_ASSET_ID,94        alice.address,95        USDT_ASSET_AMOUNT,96      );9798      // funding parachain sovereing account on Statemine(t).99      // The sovereign account should be created before any action100      // (the assets pallet on Statemine(t) check if the sovereign account exists)101      const parachainSovereingAccount = helper.address.paraSiblingSovereignAccount(QUARTZ_CHAIN);102      await helper.balance.transferToSubstrate(bob, parachainSovereingAccount, sovereignFundingAmount);103    });104105106    await usingPlaygrounds(async (helper) => {107      const location = {108        V2: {109          parents: 1,110          interior: {X3: [111            {112              Parachain: STATEMINE_CHAIN,113            },114            {115              PalletInstance: STATEMINE_PALLET_INSTANCE,116            },117            {118              GeneralIndex: USDT_ASSET_ID,119            },120          ]},121        },122      };123124      const metadata =125      {126        name: USDT_ASSET_ID,127        symbol: USDT_ASSET_METADATA_NAME,128        decimals: USDT_ASSET_METADATA_DECIMALS,129        minimalBalance: USDT_ASSET_METADATA_MINIMAL_BALANCE,130      };131      await helper.getSudo().foreignAssets.register(alice, alice.address, location, metadata);132      balanceQuartzBefore = await helper.balance.getSubstrate(alice.address);133    });134135136    // Providing the relay currency to the quartz sender account137    // (fee for USDT XCM are paid in relay tokens)138    await usingRelayPlaygrounds(relayUrl, async (helper) => {139      const destination = {140        V2: {141          parents: 0,142          interior: {X1: {143            Parachain: QUARTZ_CHAIN,144          },145          },146        }};147148      const beneficiary = {149        V2: {150          parents: 0,151          interior: {X1: {152            AccountId32: {153              network: 'Any',154              id: alice.addressRaw,155            },156          }},157        },158      };159160      const assets = {161        V2: [162          {163            id: {164              Concrete: {165                parents: 0,166                interior: 'Here',167              },168            },169            fun: {170              Fungible: TRANSFER_AMOUNT_RELAY,171            },172          },173        ],174      };175176      const feeAssetItem = 0;177178      await helper.xcm.limitedReserveTransferAssets(alice, destination, beneficiary, assets, feeAssetItem, 'Unlimited');179    });180181  });182183  itSub('Should connect and send USDT from Statemine to Quartz', async ({helper}) => {184    await usingStateminePlaygrounds(statemineUrl, async (helper) => {185      const dest = {186        V2: {187          parents: 1,188          interior: {X1: {189            Parachain: QUARTZ_CHAIN,190          },191          },192        }};193194      const beneficiary = {195        V2: {196          parents: 0,197          interior: {X1: {198            AccountId32: {199              network: 'Any',200              id: alice.addressRaw,201            },202          }},203        },204      };205206      const assets = {207        V2: [208          {209            id: {210              Concrete: {211                parents: 0,212                interior: {213                  X2: [214                    {215                      PalletInstance: STATEMINE_PALLET_INSTANCE,216                    },217                    {218                      GeneralIndex: USDT_ASSET_ID,219                    },220                  ]},221              },222            },223            fun: {224              Fungible: TRANSFER_AMOUNT,225            },226          },227        ],228      };229230      const feeAssetItem = 0;231232      balanceStmnBefore = await helper.balance.getSubstrate(alice.address);233      await helper.xcm.limitedReserveTransferAssets(alice, dest, beneficiary, assets, feeAssetItem, 'Unlimited');234235      balanceStmnAfter = await helper.balance.getSubstrate(alice.address);236237      // common good parachain take commission in it native token238      console.log(239        '[Statemine -> Quartz] transaction fees on Statemine: %s WND',240        helper.util.bigIntToDecimals(balanceStmnBefore - balanceStmnAfter, STATEMINE_DECIMALS),241      );242      expect(balanceStmnBefore > balanceStmnAfter).to.be.true;243244    });245246247    // ensure that asset has been delivered248    await helper.wait.newBlocks(3);249250    // expext collection id will be with id 1251    const free = await helper.ft.getBalance(1, {Substrate: alice.address});252253    balanceQuartzAfter = await helper.balance.getSubstrate(alice.address);254255    console.log(256      '[Statemine -> Quartz] transaction fees on Quartz: %s USDT',257      helper.util.bigIntToDecimals(TRANSFER_AMOUNT - free, USDT_ASSET_METADATA_DECIMALS),258    );259    console.log(260      '[Statemine -> Quartz] transaction fees on Quartz: %s QTZ',261      helper.util.bigIntToDecimals(balanceQuartzAfter - balanceQuartzBefore),262    );263    // commission has not paid in USDT token264    expect(free).to.be.equal(TRANSFER_AMOUNT);265    // ... and parachain native token266    expect(balanceQuartzAfter == balanceQuartzBefore).to.be.true;267  });268269  itSub('Should connect and send USDT from Quartz to Statemine back', async ({helper}) => {270    const destination = {271      V2: {272        parents: 1,273        interior: {X2: [274          {275            Parachain: STATEMINE_CHAIN,276          },277          {278            AccountId32: {279              network: 'Any',280              id: alice.addressRaw,281            },282          },283        ]},284      },285    };286287    const relayFee = 400_000_000_000_000n;288    const currencies: [any, bigint][] = [289      [290        {291          ForeignAssetId: 0,292        },293        TRANSFER_AMOUNT,294      ],295      [296        {297          NativeAssetId: 'Parent',298        },299        relayFee,300      ],301    ];302303    const feeItem = 1;304305    await helper.xTokens.transferMulticurrencies(alice, currencies, feeItem, destination, 'Unlimited');306307    // the commission has been paid in parachain native token308    balanceQuartzFinal = await helper.balance.getSubstrate(alice.address);309    console.log('[Quartz -> Statemine] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(balanceQuartzAfter - balanceQuartzFinal));310    expect(balanceQuartzAfter > balanceQuartzFinal).to.be.true;311312    await usingStateminePlaygrounds(statemineUrl, async (helper) => {313      await helper.wait.newBlocks(3);314315      // The USDT token never paid fees. Its amount not changed from begin value.316      // Also check that xcm transfer has been succeeded317      expect((await helper.assets.account(USDT_ASSET_ID, alice.address))! == USDT_ASSET_AMOUNT).to.be.true;318    });319  });320321  itSub('Should connect and send Relay token to Quartz', async ({helper}) => {322    balanceBobBefore = await helper.balance.getSubstrate(bob.address);323    balanceBobRelayTokenBefore = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});324325    await usingRelayPlaygrounds(relayUrl, async (helper) => {326      const destination = {327        V2: {328          parents: 0,329          interior: {X1: {330            Parachain: QUARTZ_CHAIN,331          },332          },333        }};334335      const beneficiary = {336        V2: {337          parents: 0,338          interior: {X1: {339            AccountId32: {340              network: 'Any',341              id: bob.addressRaw,342            },343          }},344        },345      };346347      const assets = {348        V2: [349          {350            id: {351              Concrete: {352                parents: 0,353                interior: 'Here',354              },355            },356            fun: {357              Fungible: TRANSFER_AMOUNT_RELAY,358            },359          },360        ],361      };362363      const feeAssetItem = 0;364365      await helper.xcm.limitedReserveTransferAssets(bob, destination, beneficiary, assets, feeAssetItem, 'Unlimited');366    });367368    await helper.wait.newBlocks(3);369370    balanceBobAfter = await helper.balance.getSubstrate(bob.address);371    balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});372373    const wndFeeOnQuartz = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;374    const wndDiffOnQuartz = balanceBobRelayTokenAfter - balanceBobRelayTokenBefore;375    console.log(376      '[Relay (Westend) -> Quartz] transaction fees: %s QTZ',377      helper.util.bigIntToDecimals(balanceBobAfter - balanceBobBefore),378    );379    console.log(380      '[Relay (Westend) -> Quartz] transaction fees: %s WND',381      helper.util.bigIntToDecimals(wndFeeOnQuartz, STATEMINE_DECIMALS),382    );383    console.log('[Relay (Westend) -> Quartz] actually delivered: %s WND', wndDiffOnQuartz);384    expect(wndFeeOnQuartz == 0n, 'No incoming WND fees should be taken').to.be.true;385    expect(balanceBobBefore == balanceBobAfter, 'No incoming QTZ fees should be taken').to.be.true;386  });387388  itSub('Should connect and send Relay token back', async ({helper}) => {389    let relayTokenBalanceBefore: bigint;390    let relayTokenBalanceAfter: bigint;391    await usingRelayPlaygrounds(relayUrl, async (helper) => {392      relayTokenBalanceBefore = await helper.balance.getSubstrate(bob.address);393    });394395    const destination = {396      V2: {397        parents: 1,398        interior: {399          X1:{400            AccountId32: {401              network: 'Any',402              id: bob.addressRaw,403            },404          },405        },406      },407    };408409    const currencies: any = [410      [411        {412          NativeAssetId: 'Parent',413        },414        TRANSFER_AMOUNT_RELAY,415      ],416    ];417418    const feeItem = 0;419420    await helper.xTokens.transferMulticurrencies(bob, currencies, feeItem, destination, 'Unlimited');421422    balanceBobFinal = await helper.balance.getSubstrate(bob.address);423    console.log('[Quartz -> Relay (Westend)] transaction fees: %s QTZ',  helper.util.bigIntToDecimals(balanceBobAfter - balanceBobFinal));424425    await usingRelayPlaygrounds(relayUrl, async (helper) => {426      await helper.wait.newBlocks(10);427      relayTokenBalanceAfter = await helper.balance.getSubstrate(bob.address);428429      const diff = relayTokenBalanceAfter - relayTokenBalanceBefore;430      console.log('[Quartz -> Relay (Westend)] actually delivered: %s WND', helper.util.bigIntToDecimals(diff, RELAY_DECIMALS));431      expect(diff > 0, 'Relay tokens was not delivered back').to.be.true;432    });433  });434});435436describeXCM('[XCM] Integration test: Exchanging tokens with Karura', () => {437  let alice: IKeyringPair;438  let randomAccount: IKeyringPair;439440  let balanceQuartzTokenInit: bigint;441  let balanceQuartzTokenMiddle: bigint;442  let balanceQuartzTokenFinal: bigint;443  let balanceKaruraTokenInit: bigint;444  let balanceKaruraTokenMiddle: bigint;445  let balanceKaruraTokenFinal: bigint;446  let balanceQuartzForeignTokenInit: bigint;447  let balanceQuartzForeignTokenMiddle: bigint;448  let balanceQuartzForeignTokenFinal: bigint;449450  // computed by a test transfer from prod Quartz to prod Karura.451  // 2 QTZ sent https://quartz.subscan.io/xcm_message/kusama-f60d821b049f8835a3005ce7102285006f5b61e9452  // 1.919176000000000000 QTZ received (you can check Karura's chain state in the corresponding block)453  const expectedKaruraIncomeFee = 2000000000000000000n - 1919176000000000000n;454  const karuraEps = 8n * 10n ** 16n;455456  let karuraBackwardTransferAmount: bigint;457458  before(async () => {459    await usingPlaygrounds(async (helper, privateKey) => {460      alice = await privateKey('//Alice');461      [randomAccount] = await helper.arrange.createAccounts([0n], alice);462463      // Set the default version to wrap the first message to other chains.464      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);465    });466467    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {468      const destination = {469        V2: {470          parents: 1,471          interior: {472            X1: {473              Parachain: QUARTZ_CHAIN,474            },475          },476        },477      };478479      const metadata = {480        name: 'Quartz',481        symbol: 'QTZ',482        decimals: 18,483        minimalBalance: 1000000000000000000n,484      };485486      await helper.getSudo().assetRegistry.registerForeignAsset(alice, destination, metadata);487      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);488      balanceKaruraTokenInit = await helper.balance.getSubstrate(randomAccount.address);489      balanceQuartzForeignTokenInit = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});490    });491492    await usingPlaygrounds(async (helper) => {493      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10n * TRANSFER_AMOUNT);494      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccount.address);495    });496  });497498  itSub('Should connect and send QTZ to Karura', async ({helper}) => {499    const destination = {500      V2: {501        parents: 1,502        interior: {503          X1: {504            Parachain: KARURA_CHAIN,505          },506        },507      },508    };509510    const beneficiary = {511      V2: {512        parents: 0,513        interior: {514          X1: {515            AccountId32: {516              network: 'Any',517              id: randomAccount.addressRaw,518            },519          },520        },521      },522    };523524    const assets = {525      V2: [526        {527          id: {528            Concrete: {529              parents: 0,530              interior: 'Here',531            },532          },533          fun: {534            Fungible: TRANSFER_AMOUNT,535          },536        },537      ],538    };539540    const feeAssetItem = 0;541542    await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');543    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);544545    const qtzFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;546    expect(qtzFees > 0n, 'Negative fees QTZ, looks like nothing was transferred').to.be.true;547    console.log('[Quartz -> Karura] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));548549    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {550      await helper.wait.newBlocks(3);551552      balanceQuartzForeignTokenMiddle = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});553      balanceKaruraTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);554555      const karFees = balanceKaruraTokenInit - balanceKaruraTokenMiddle;556      const qtzIncomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenInit;557      karuraBackwardTransferAmount = qtzIncomeTransfer;558559      const karUnqFees = TRANSFER_AMOUNT - qtzIncomeTransfer;560561      console.log(562        '[Quartz -> Karura] transaction fees on Karura: %s KAR',563        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),564      );565      console.log(566        '[Quartz -> Karura] transaction fees on Karura: %s QTZ',567        helper.util.bigIntToDecimals(karUnqFees),568      );569      console.log('[Quartz -> Karura] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));570      expect(karFees == 0n).to.be.true;571572      const bigintAbs = (n: bigint) => (n < 0n) ? -n : n;573574      expect(575        bigintAbs(karUnqFees - expectedKaruraIncomeFee) < karuraEps,576        'Karura took different income fee, check the Karura foreign asset config',577      ).to.be.true;578    });579  });580581  itSub('Should connect to Karura and send QTZ back', async ({helper}) => {582    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {583      const destination = {584        V2: {585          parents: 1,586          interior: {587            X2: [588              {Parachain: QUARTZ_CHAIN},589              {590                AccountId32: {591                  network: 'Any',592                  id: randomAccount.addressRaw,593                },594              },595            ],596          },597        },598      };599600      const id = {601        ForeignAsset: 0,602      };603604      await helper.xTokens.transfer(randomAccount, id, karuraBackwardTransferAmount, destination, 'Unlimited');605      balanceKaruraTokenFinal = await helper.balance.getSubstrate(randomAccount.address);606      balanceQuartzForeignTokenFinal = await helper.tokens.accounts(randomAccount.address, id);607608      const karFees = balanceKaruraTokenMiddle - balanceKaruraTokenFinal;609      const qtzOutcomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenFinal;610611      console.log(612        '[Karura -> Quartz] transaction fees on Karura: %s KAR',613        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),614      );615      console.log('[Karura -> Quartz] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));616617      expect(karFees > 0, 'Negative fees KAR, looks like nothing was transferred').to.be.true;618      expect(qtzOutcomeTransfer == karuraBackwardTransferAmount).to.be.true;619    });620621    await helper.wait.newBlocks(3);622623    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccount.address);624    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;625    expect(actuallyDelivered > 0).to.be.true;626627    console.log('[Karura -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));628629    const qtzFees = karuraBackwardTransferAmount - actuallyDelivered;630    console.log('[Karura -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));631    expect(qtzFees == 0n).to.be.true;632  });633634  itSub('Karura can send only up to its balance', async ({helper}) => {635    // set Karura's sovereign account's balance636    const karuraBalance = 10000n * (10n ** QTZ_DECIMALS);637    const karuraSovereignAccount = helper.address.paraSiblingSovereignAccount(KARURA_CHAIN);638    await helper.getSudo().balance.setBalanceSubstrate(alice, karuraSovereignAccount, karuraBalance);639640    const moreThanKaruraHas = karuraBalance * 2n;641642    let targetAccountBalance = 0n;643    const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);644645    const quartzMultilocation = {646      V2: {647        parents: 1,648        interior: {649          X1: {Parachain: QUARTZ_CHAIN},650        },651      },652    };653654    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(655      targetAccount.addressRaw,656      {657        Concrete: {658          parents: 0,659          interior: 'Here',660        },661      },662      moreThanKaruraHas,663    );664665    let maliciousXcmProgramSent: any;666    const maxWaitBlocks = 5;667668    // Try to trick Quartz669    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {670      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);671672      maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);673    });674675    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == maliciousXcmProgramSent.messageHash676        && event.outcome.isFailedToTransactAsset);677678    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);679    expect(targetAccountBalance).to.be.equal(0n);680681    // But Karura still can send the correct amount682    const validTransferAmount = karuraBalance / 2n;683    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(684      targetAccount.addressRaw,685      {686        Concrete: {687          parents: 0,688          interior: 'Here',689        },690      },691      validTransferAmount,692    );693694    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {695      await helper.getSudo().xcm.send(alice, quartzMultilocation, validXcmProgram);696    });697698    await helper.wait.newBlocks(maxWaitBlocks);699700    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);701    expect(targetAccountBalance).to.be.equal(validTransferAmount);702  });703704  itSub('Should not accept reserve transfer of QTZ from Karura', async ({helper}) => {705    const testAmount = 10_000n * (10n ** QTZ_DECIMALS);706    const [targetAccount] = await helper.arrange.createAccounts([0n], alice);707708    const quartzMultilocation = {709      V2: {710        parents: 1,711        interior: {712          X1: {713            Parachain: QUARTZ_CHAIN,714          },715        },716      },717    };718719    const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(720      targetAccount.addressRaw,721      {722        Concrete: {723          parents: 1,724          interior: {725            X1: {726              Parachain: QUARTZ_CHAIN,727            },728          },729        },730      },731      testAmount,732    );733734    const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(735      targetAccount.addressRaw,736      {737        Concrete: {738          parents: 0,739          interior: 'Here',740        },741      },742      testAmount,743    );744745    let maliciousXcmProgramFullIdSent: any;746    let maliciousXcmProgramHereIdSent: any;747    const maxWaitBlocks = 3;748749    // Try to trick Quartz using full QTZ identification750    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {751      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgramFullId);752753      maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);754    });755756    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == maliciousXcmProgramFullIdSent.messageHash757        && event.outcome.isUntrustedReserveLocation);758759    let accountBalance = await helper.balance.getSubstrate(targetAccount.address);760    expect(accountBalance).to.be.equal(0n);761762    // Try to trick Quartz using shortened QTZ identification763    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {764      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgramHereId);765766      maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);767    });768769    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == maliciousXcmProgramHereIdSent.messageHash770        && event.outcome.isUntrustedReserveLocation);771772    accountBalance = await helper.balance.getSubstrate(targetAccount.address);773    expect(accountBalance).to.be.equal(0n);774  });775});776777// These tests are relevant only when778// the the corresponding foreign assets are not registered779describeXCM('[XCM] Integration test: Quartz rejects non-native tokens', () => {780  let alice: IKeyringPair;781  let alith: IKeyringPair;782783  const testAmount = 100_000_000_000n;784  let quartzParachainJunction;785  let quartzAccountJunction;786787  let quartzParachainMultilocation: any;788  let quartzAccountMultilocation: any;789  let quartzCombinedMultilocation: any;790791  let messageSent: any;792793  const maxWaitBlocks = 3;794795  before(async () => {796    await usingPlaygrounds(async (helper, privateKey) => {797      alice = await privateKey('//Alice');798799      quartzParachainJunction = {Parachain: QUARTZ_CHAIN};800      quartzAccountJunction = {801        AccountId32: {802          network: 'Any',803          id: alice.addressRaw,804        },805      };806807      quartzParachainMultilocation = {808        V2: {809          parents: 1,810          interior: {811            X1: quartzParachainJunction,812          },813        },814      };815816      quartzAccountMultilocation = {817        V2: {818          parents: 0,819          interior: {820            X1: quartzAccountJunction,821          },822        },823      };824825      quartzCombinedMultilocation = {826        V2: {827          parents: 1,828          interior: {829            X2: [quartzParachainJunction, quartzAccountJunction],830          },831        },832      };833834      // Set the default version to wrap the first message to other chains.835      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);836    });837838    // eslint-disable-next-line require-await839    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {840      alith = helper.account.alithAccount();841    });842  });843844  const expectFailedToTransact = async (helper: DevUniqueHelper, messageSent: any) => {845    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash846        && event.outcome.isFailedToTransactAsset);847  };848849  itSub('Quartz rejects KAR tokens from Karura', async ({helper}) => {850    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {851      const id = {852        Token: 'KAR',853      };854      const destination = quartzCombinedMultilocation;855      await helper.xTokens.transfer(alice, id, testAmount, destination, 'Unlimited');856857      messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);858    });859860    await expectFailedToTransact(helper, messageSent);861  });862863  itSub('Quartz rejects MOVR tokens from Moonriver', async ({helper}) => {864    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {865      const id = 'SelfReserve';866      const destination = quartzCombinedMultilocation;867      await helper.xTokens.transfer(alith, id, testAmount, destination, 'Unlimited');868869      messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);870    });871872    await expectFailedToTransact(helper, messageSent);873  });874875  itSub('Quartz rejects SDN tokens from Shiden', async ({helper}) => {876    await usingShidenPlaygrounds(shidenUrl, async (helper) => {877      const destinationParachain = quartzParachainMultilocation;878      const beneficiary = quartzAccountMultilocation;879      const assets = {880        V2: [{881          id: {882            Concrete: {883              parents: 0,884              interior: 'Here',885            },886          },887          fun: {888            Fungible: testAmount,889          },890        }],891      };892      const feeAssetItem = 0;893894      await helper.executeExtrinsic(alice, 'api.tx.polkadotXcm.reserveWithdrawAssets', [895        destinationParachain,896        beneficiary,897        assets,898        feeAssetItem,899      ]);900901      messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);902    });903904    await expectFailedToTransact(helper, messageSent);905  });906});907908describeXCM('[XCM] Integration test: Exchanging QTZ with Moonriver', () => {909  // Quartz constants910  let alice: IKeyringPair;911  let quartzAssetLocation;912913  let randomAccountQuartz: IKeyringPair;914  let randomAccountMoonriver: IKeyringPair;915916  // Moonriver constants917  let assetId: string;918919  const quartzAssetMetadata = {920    name: 'xcQuartz',921    symbol: 'xcQTZ',922    decimals: 18,923    isFrozen: false,924    minimalBalance: 1n,925  };926927  let balanceQuartzTokenInit: bigint;928  let balanceQuartzTokenMiddle: bigint;929  let balanceQuartzTokenFinal: bigint;930  let balanceForeignQtzTokenInit: bigint;931  let balanceForeignQtzTokenMiddle: bigint;932  let balanceForeignQtzTokenFinal: bigint;933  let balanceMovrTokenInit: bigint;934  let balanceMovrTokenMiddle: bigint;935  let balanceMovrTokenFinal: bigint;936937  before(async () => {938    await usingPlaygrounds(async (helper, privateKey) => {939      alice = await privateKey('//Alice');940      [randomAccountQuartz] = await helper.arrange.createAccounts([0n], alice);941942      balanceForeignQtzTokenInit = 0n;943944      // Set the default version to wrap the first message to other chains.945      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);946    });947948    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {949      const alithAccount = helper.account.alithAccount();950      const baltatharAccount = helper.account.baltatharAccount();951      const dorothyAccount = helper.account.dorothyAccount();952953      randomAccountMoonriver = helper.account.create();954955      // >>> Sponsoring Dorothy >>>956      console.log('Sponsoring Dorothy.......');957      await helper.balance.transferToEthereum(alithAccount, dorothyAccount.address, 11_000_000_000_000_000_000n);958      console.log('Sponsoring Dorothy.......DONE');959      // <<< Sponsoring Dorothy <<<960961      quartzAssetLocation = {962        XCM: {963          parents: 1,964          interior: {X1: {Parachain: QUARTZ_CHAIN}},965        },966      };967      const existentialDeposit = 1n;968      const isSufficient = true;969      const unitsPerSecond = 1n;970      const numAssetsWeightHint = 0;971972      const encodedProposal = helper.assetManager.makeRegisterForeignAssetProposal({973        location: quartzAssetLocation,974        metadata: quartzAssetMetadata,975        existentialDeposit,976        isSufficient,977        unitsPerSecond,978        numAssetsWeightHint,979      });980981      console.log('Encoded proposal for registerForeignAsset & setAssetUnitsPerSecond is %s', encodedProposal);982983      await helper.fastDemocracy.executeProposal('register QTZ foreign asset', encodedProposal);984985      // >>> Acquire Quartz AssetId Info on Moonriver >>>986      console.log('Acquire Quartz AssetId Info on Moonriver.......');987988      assetId = (await helper.assetManager.assetTypeId(quartzAssetLocation)).toString();989990      console.log('QTZ asset ID is %s', assetId);991      console.log('Acquire Quartz AssetId Info on Moonriver.......DONE');992      // >>> Acquire Quartz AssetId Info on Moonriver >>>993994      // >>> Sponsoring random Account >>>995      console.log('Sponsoring random Account.......');996      await helper.balance.transferToEthereum(baltatharAccount, randomAccountMoonriver.address, 11_000_000_000_000_000_000n);997      console.log('Sponsoring random Account.......DONE');998      // <<< Sponsoring random Account <<<9991000      balanceMovrTokenInit = await helper.balance.getEthereum(randomAccountMoonriver.address);1001    });10021003    await usingPlaygrounds(async (helper) => {1004      await helper.balance.transferToSubstrate(alice, randomAccountQuartz.address, 10n * TRANSFER_AMOUNT);1005      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccountQuartz.address);1006    });1007  });10081009  itSub('Should connect and send QTZ to Moonriver', async ({helper}) => {1010    const currencyId = {1011      NativeAssetId: 'Here',1012    };1013    const dest = {1014      V2: {1015        parents: 1,1016        interior: {1017          X2: [1018            {Parachain: MOONRIVER_CHAIN},1019            {AccountKey20: {network: 'Any', key: randomAccountMoonriver.address}},1020          ],1021        },1022      },1023    };1024    const amount = TRANSFER_AMOUNT;10251026    await helper.xTokens.transfer(randomAccountQuartz, currencyId, amount, dest, 'Unlimited');10271028    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccountQuartz.address);1029    expect(balanceQuartzTokenMiddle < balanceQuartzTokenInit).to.be.true;10301031    const transactionFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;1032    console.log('[Quartz -> Moonriver] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(transactionFees));1033    expect(transactionFees > 0, 'Negative fees QTZ, looks like nothing was transferred').to.be.true;10341035    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1036      await helper.wait.newBlocks(3);10371038      balanceMovrTokenMiddle = await helper.balance.getEthereum(randomAccountMoonriver.address);10391040      const movrFees = balanceMovrTokenInit - balanceMovrTokenMiddle;1041      console.log('[Quartz -> Moonriver] transaction fees on Moonriver: %s MOVR',helper.util.bigIntToDecimals(movrFees));1042      expect(movrFees == 0n).to.be.true;10431044      balanceForeignQtzTokenMiddle = (await helper.assets.account(assetId, randomAccountMoonriver.address))!; // BigInt(qtzRandomAccountAsset['balance']);1045      const qtzIncomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenInit;1046      console.log('[Quartz -> Moonriver] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));1047      expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;1048    });1049  });10501051  itSub('Should connect to Moonriver and send QTZ back', async ({helper}) => {1052    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1053      const asset = {1054        V2: {1055          id: {1056            Concrete: {1057              parents: 1,1058              interior: {1059                X1: {Parachain: QUARTZ_CHAIN},1060              },1061            },1062          },1063          fun: {1064            Fungible: TRANSFER_AMOUNT,1065          },1066        },1067      };1068      const destination = {1069        V2: {1070          parents: 1,1071          interior: {1072            X2: [1073              {Parachain: QUARTZ_CHAIN},1074              {AccountId32: {network: 'Any', id: randomAccountQuartz.addressRaw}},1075            ],1076          },1077        },1078      };10791080      await helper.xTokens.transferMultiasset(randomAccountMoonriver, asset, destination, 'Unlimited');10811082      balanceMovrTokenFinal = await helper.balance.getEthereum(randomAccountMoonriver.address);10831084      const movrFees = balanceMovrTokenMiddle - balanceMovrTokenFinal;1085      console.log('[Moonriver -> Quartz] transaction fees on Moonriver: %s MOVR', helper.util.bigIntToDecimals(movrFees));1086      expect(movrFees > 0, 'Negative fees MOVR, looks like nothing was transferred').to.be.true;10871088      const qtzRandomAccountAsset = await helper.assets.account(assetId, randomAccountMoonriver.address);10891090      expect(qtzRandomAccountAsset).to.be.null;10911092      balanceForeignQtzTokenFinal = 0n;10931094      const qtzOutcomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenFinal;1095      console.log('[Quartz -> Moonriver] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));1096      expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;1097    });10981099    await helper.wait.newBlocks(3);11001101    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccountQuartz.address);1102    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;1103    expect(actuallyDelivered > 0).to.be.true;11041105    console.log('[Moonriver -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));11061107    const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;1108    console.log('[Moonriver -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));1109    expect(qtzFees == 0n).to.be.true;1110  });11111112  itSub('Moonriver can send only up to its balance', async ({helper}) => {1113    // set Moonriver's sovereign account's balance1114    const moonriverBalance = 10000n * (10n ** QTZ_DECIMALS);1115    const moonriverSovereignAccount = helper.address.paraSiblingSovereignAccount(MOONRIVER_CHAIN);1116    await helper.getSudo().balance.setBalanceSubstrate(alice, moonriverSovereignAccount, moonriverBalance);11171118    const moreThanMoonriverHas = moonriverBalance * 2n;11191120    let targetAccountBalance = 0n;1121    const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);11221123    const quartzMultilocation = {1124      V2: {1125        parents: 1,1126        interior: {1127          X1: {Parachain: QUARTZ_CHAIN},1128        },1129      },1130    };11311132    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(1133      targetAccount.addressRaw,1134      {1135        Concrete: {1136          parents: 0,1137          interior: 'Here',1138        },1139      },1140      moreThanMoonriverHas,1141    );11421143    let maliciousXcmProgramSent: any;1144    const maxWaitBlocks = 3;11451146    // Try to trick Quartz1147    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1148      const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [quartzMultilocation, maliciousXcmProgram]);11491150      // Needed to bypass the call filter.1151      const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);1152      await helper.fastDemocracy.executeProposal('try to spend more QTZ than Moonriver has', batchCall);11531154      maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1155    });11561157    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == maliciousXcmProgramSent.messageHash1158        && event.outcome.isFailedToTransactAsset);11591160    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);1161    expect(targetAccountBalance).to.be.equal(0n);11621163    // But Moonriver still can send the correct amount1164    const validTransferAmount = moonriverBalance / 2n;1165    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(1166      targetAccount.addressRaw,1167      {1168        Concrete: {1169          parents: 0,1170          interior: 'Here',1171        },1172      },1173      validTransferAmount,1174    );11751176    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1177      const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [quartzMultilocation, validXcmProgram]);11781179      // Needed to bypass the call filter.1180      const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);1181      await helper.fastDemocracy.executeProposal('Spend the correct amount of QTZ', batchCall);1182    });11831184    await helper.wait.newBlocks(maxWaitBlocks);11851186    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);1187    expect(targetAccountBalance).to.be.equal(validTransferAmount);1188  });11891190  itSub('Should not accept reserve transfer of QTZ from Moonriver', async ({helper}) => {1191    const testAmount = 10_000n * (10n ** QTZ_DECIMALS);1192    const [targetAccount] = await helper.arrange.createAccounts([0n], alice);11931194    const quartzMultilocation = {1195      V2: {1196        parents: 1,1197        interior: {1198          X1: {1199            Parachain: QUARTZ_CHAIN,1200          },1201        },1202      },1203    };12041205    const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(1206      targetAccount.addressRaw,1207      {1208        Concrete: {1209          parents: 0,1210          interior: {1211            X1: {1212              Parachain: QUARTZ_CHAIN,1213            },1214          },1215        },1216      },1217      testAmount,1218    );12191220    const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(1221      targetAccount.addressRaw,1222      {1223        Concrete: {1224          parents: 0,1225          interior: 'Here',1226        },1227      },1228      testAmount,1229    );12301231    let maliciousXcmProgramFullIdSent: any;1232    let maliciousXcmProgramHereIdSent: any;1233    const maxWaitBlocks = 3;12341235    // Try to trick Quartz using full QTZ identification1236    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1237      const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [quartzMultilocation, maliciousXcmProgramFullId]);12381239      // Needed to bypass the call filter.1240      const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);1241      await helper.fastDemocracy.executeProposal('try to act like a reserve location for QTZ using path asset identification', batchCall);12421243      maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1244    });12451246    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == maliciousXcmProgramFullIdSent.messageHash1247        && event.outcome.isUntrustedReserveLocation);12481249    let accountBalance = await helper.balance.getSubstrate(targetAccount.address);1250    expect(accountBalance).to.be.equal(0n);12511252    // Try to trick Quartz using shortened QTZ identification1253    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1254      const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [quartzMultilocation, maliciousXcmProgramHereId]);12551256      // Needed to bypass the call filter.1257      const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);1258      await helper.fastDemocracy.executeProposal('try to act like a reserve location for QTZ using "here" asset identification', batchCall);12591260      maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1261    });12621263    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == maliciousXcmProgramHereIdSent.messageHash1264        && event.outcome.isUntrustedReserveLocation);12651266    accountBalance = await helper.balance.getSubstrate(targetAccount.address);1267    expect(accountBalance).to.be.equal(0n);1268  });1269});12701271describeXCM('[XCM] Integration test: Exchanging tokens with Shiden', () => {1272  let alice: IKeyringPair;1273  let sender: IKeyringPair;12741275  const QTZ_ASSET_ID_ON_SHIDEN = 1;1276  const QTZ_MINIMAL_BALANCE_ON_SHIDEN = 1n;12771278  // Quartz -> Shiden1279  const shidenInitialBalance = 1n * (10n ** SHIDEN_DECIMALS); // 1 SHD, existential deposit required to actually create the account on Shiden1280  const unitsPerSecond = 228_000_000_000n; // This is Phala's value. What will be ours?1281  const qtzToShidenTransferred = 10n * (10n ** QTZ_DECIMALS); // 10 QTZ1282  const qtzToShidenArrived = 9_999_999_999_088_000_000n; // 9.999 ... QTZ, Shiden takes a commision in foreign tokens12831284  // Shiden -> Quartz1285  const qtzFromShidenTransfered = 5n * (10n ** QTZ_DECIMALS); // 5 QTZ1286  const qtzOnShidenLeft = qtzToShidenArrived - qtzFromShidenTransfered; // 4.999_999_999_088_000_000n QTZ12871288  let balanceAfterQuartzToShidenXCM: bigint;12891290  before(async () => {1291    await usingPlaygrounds(async (helper, privateKey) => {1292      alice = await privateKey('//Alice');1293      [sender] = await helper.arrange.createAccounts([100n], alice);1294      console.log('sender', sender.address);12951296      // Set the default version to wrap the first message to other chains.1297      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);1298    });12991300    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1301      console.log('1. Create foreign asset and metadata');1302      // TODO update metadata with values from production1303      await helper.assets.create(1304        alice,1305        QTZ_ASSET_ID_ON_SHIDEN,1306        alice.address,1307        QTZ_MINIMAL_BALANCE_ON_SHIDEN,1308      );13091310      await helper.assets.setMetadata(1311        alice,1312        QTZ_ASSET_ID_ON_SHIDEN,1313        'Cross chain QTZ',1314        'xcQTZ',1315        Number(QTZ_DECIMALS),1316      );13171318      console.log('2. Register asset location on Shiden');1319      const assetLocation = {1320        V2: {1321          parents: 1,1322          interior: {1323            X1: {1324              Parachain: QUARTZ_CHAIN,1325            },1326          },1327        },1328      };13291330      await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.registerAssetLocation', [assetLocation, QTZ_ASSET_ID_ON_SHIDEN]);13311332      console.log('3. Set QTZ payment for XCM execution on Shiden');1333      await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.setAssetUnitsPerSecond', [assetLocation, unitsPerSecond]);13341335      console.log('4. Transfer 1 SDN to recipient to create the account (needed due to existential balance)');1336      await helper.balance.transferToSubstrate(alice, sender.address, shidenInitialBalance);1337    });1338  });13391340  itSub('Should connect and send QTZ to Shiden', async ({helper}) => {1341    const destination = {1342      V2: {1343        parents: 1,1344        interior: {1345          X1: {1346            Parachain: SHIDEN_CHAIN,1347          },1348        },1349      },1350    };13511352    const beneficiary = {1353      V2: {1354        parents: 0,1355        interior: {1356          X1: {1357            AccountId32: {1358              network: 'Any',1359              id: sender.addressRaw,1360            },1361          },1362        },1363      },1364    };13651366    const assets = {1367      V2: [1368        {1369          id: {1370            Concrete: {1371              parents: 0,1372              interior: 'Here',1373            },1374          },1375          fun: {1376            Fungible: qtzToShidenTransferred,1377          },1378        },1379      ],1380    };13811382    // Initial balance is 100 QTZ1383    const balanceBefore = await helper.balance.getSubstrate(sender.address);1384    console.log(`Initial balance is: ${balanceBefore}`);13851386    const feeAssetItem = 0;1387    await helper.xcm.limitedReserveTransferAssets(sender, destination, beneficiary, assets, feeAssetItem, 'Unlimited');13881389    // Balance after reserve transfer is less than 901390    balanceAfterQuartzToShidenXCM = await helper.balance.getSubstrate(sender.address);1391    console.log(`QTZ Balance on Quartz after XCM is: ${balanceAfterQuartzToShidenXCM}`);1392    console.log(`Quartz's QTZ commission is: ${balanceBefore - balanceAfterQuartzToShidenXCM}`);1393    expect(balanceBefore - balanceAfterQuartzToShidenXCM > 0).to.be.true;13941395    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1396      await helper.wait.newBlocks(3);1397      const xcQTZbalance = await helper.assets.account(QTZ_ASSET_ID_ON_SHIDEN, sender.address);1398      const shidenBalance = await helper.balance.getSubstrate(sender.address);13991400      console.log(`xcQTZ balance on Shiden after XCM is: ${xcQTZbalance}`);1401      console.log(`Shiden's QTZ commission is: ${qtzToShidenTransferred - xcQTZbalance!}`);14021403      expect(xcQTZbalance).to.eq(qtzToShidenArrived);1404      // SHD balance does not changed:1405      expect(shidenBalance).to.eq(shidenInitialBalance);1406    });1407  });14081409  itSub('Should connect to Shiden and send QTZ back', async ({helper}) => {1410    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1411      const destination = {1412        V2: {1413          parents: 1,1414          interior: {1415            X1: {1416              Parachain: QUARTZ_CHAIN,1417            },1418          },1419        },1420      };14211422      const beneficiary = {1423        V2: {1424          parents: 0,1425          interior: {1426            X1: {1427              AccountId32: {1428                network: 'Any',1429                id: sender.addressRaw,1430              },1431            },1432          },1433        },1434      };14351436      const assets = {1437        V2: [1438          {1439            id: {1440              Concrete: {1441                parents: 1,1442                interior: {1443                  X1: {1444                    Parachain: QUARTZ_CHAIN,1445                  },1446                },1447              },1448            },1449            fun: {1450              Fungible: qtzFromShidenTransfered,1451            },1452          },1453        ],1454      };14551456      // Initial balance is 1 SDN1457      const balanceSDNbefore = await helper.balance.getSubstrate(sender.address);1458      console.log(`SDN balance is: ${balanceSDNbefore}, it does not changed`);1459      expect(balanceSDNbefore).to.eq(shidenInitialBalance);14601461      const feeAssetItem = 0;1462      // this is non-standard polkadotXcm extension for Astar only. It calls InitiateReserveWithdraw1463      await helper.executeExtrinsic(sender, 'api.tx.polkadotXcm.reserveWithdrawAssets', [destination, beneficiary, assets, feeAssetItem]);14641465      // Balance after reserve transfer is less than 1 SDN1466      const xcQTZbalance = await helper.assets.account(QTZ_ASSET_ID_ON_SHIDEN, sender.address);1467      const balanceSDN = await helper.balance.getSubstrate(sender.address);1468      console.log(`xcQTZ balance on Shiden after XCM is: ${xcQTZbalance}`);14691470      // Assert: xcQTZ balance correctly decreased1471      expect(xcQTZbalance).to.eq(qtzOnShidenLeft);1472      // Assert: SDN balance is 0.996...1473      expect(balanceSDN / (10n ** (SHIDEN_DECIMALS - 3n))).to.eq(996n);1474    });14751476    await helper.wait.newBlocks(3);1477    const balanceQTZ = await helper.balance.getSubstrate(sender.address);1478    console.log(`QTZ Balance on Quartz after XCM is: ${balanceQTZ}`);1479    expect(balanceQTZ).to.eq(balanceAfterQuartzToShidenXCM + qtzFromShidenTransfered);1480  });14811482  itSub('Shiden can send only up to its balance', async ({helper}) => {1483    // set Shiden's sovereign account's balance1484    const shidenBalance = 10000n * (10n ** QTZ_DECIMALS);1485    const shidenSovereignAccount = helper.address.paraSiblingSovereignAccount(SHIDEN_CHAIN);1486    await helper.getSudo().balance.setBalanceSubstrate(alice, shidenSovereignAccount, shidenBalance);14871488    const moreThanShidenHas = shidenBalance * 2n;14891490    let targetAccountBalance = 0n;1491    const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);14921493    const quartzMultilocation = {1494      V2: {1495        parents: 1,1496        interior: {1497          X1: {Parachain: QUARTZ_CHAIN},1498        },1499      },1500    };15011502    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(1503      targetAccount.addressRaw,1504      {1505        Concrete: {1506          parents: 0,1507          interior: 'Here',1508        },1509      },1510      moreThanShidenHas,1511    );15121513    let maliciousXcmProgramSent: any;1514    const maxWaitBlocks = 3;15151516    // Try to trick Quartz1517    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1518      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);15191520      maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1521    });15221523    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == maliciousXcmProgramSent.messageHash1524        && event.outcome.isFailedToTransactAsset);15251526    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);1527    expect(targetAccountBalance).to.be.equal(0n);15281529    // But Shiden still can send the correct amount1530    const validTransferAmount = shidenBalance / 2n;1531    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(1532      targetAccount.addressRaw,1533      {1534        Concrete: {1535          parents: 0,1536          interior: 'Here',1537        },1538      },1539      validTransferAmount,1540    );15411542    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1543      await helper.getSudo().xcm.send(alice, quartzMultilocation, validXcmProgram);1544    });15451546    await helper.wait.newBlocks(maxWaitBlocks);15471548    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);1549    expect(targetAccountBalance).to.be.equal(validTransferAmount);1550  });15511552  itSub('Should not accept reserve transfer of QTZ from Shiden', async ({helper}) => {1553    const testAmount = 10_000n * (10n ** QTZ_DECIMALS);1554    const [targetAccount] = await helper.arrange.createAccounts([0n], alice);15551556    const quartzMultilocation = {1557      V2: {1558        parents: 1,1559        interior: {1560          X1: {1561            Parachain: QUARTZ_CHAIN,1562          },1563        },1564      },1565    };15661567    const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(1568      targetAccount.addressRaw,1569      {1570        Concrete: {1571          parents: 1,1572          interior: {1573            X1: {1574              Parachain: QUARTZ_CHAIN,1575            },1576          },1577        },1578      },1579      testAmount,1580    );15811582    const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(1583      targetAccount.addressRaw,1584      {1585        Concrete: {1586          parents: 0,1587          interior: 'Here',1588        },1589      },1590      testAmount,1591    );15921593    let maliciousXcmProgramFullIdSent: any;1594    let maliciousXcmProgramHereIdSent: any;1595    const maxWaitBlocks = 3;15961597    // Try to trick Quartz using full QTZ identification1598    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1599      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgramFullId);16001601      maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1602    });16031604    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == maliciousXcmProgramFullIdSent.messageHash1605        && event.outcome.isUntrustedReserveLocation);16061607    let accountBalance = await helper.balance.getSubstrate(targetAccount.address);1608    expect(accountBalance).to.be.equal(0n);16091610    // Try to trick Quartz using shortened QTZ identification1611    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1612      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgramHereId);16131614      maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1615    });16161617    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == maliciousXcmProgramHereIdSent.messageHash1618        && event.outcome.isUntrustedReserveLocation);16191620    accountBalance = await helper.balance.getSubstrate(targetAccount.address);1621    expect(accountBalance).to.be.equal(0n);1622  });1623});