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

difftreelog

source

tests/src/xcm/xcmQuartz.test.ts54.1 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 config from '../config';19import {itSub, expect, describeXCM, usingPlaygrounds, usingKaruraPlaygrounds, usingRelayPlaygrounds, usingMoonriverPlaygrounds, usingStateminePlaygrounds, usingShidenPlaygrounds} from '../util';20import {DevUniqueHelper, Event} from '../util/playgrounds/unique.dev';2122const QUARTZ_CHAIN = 2095;23const STATEMINE_CHAIN = 1000;24const KARURA_CHAIN = 2000;25const MOONRIVER_CHAIN = 2023;26const SHIDEN_CHAIN = 2007;2728const STATEMINE_PALLET_INSTANCE = 50;2930const relayUrl = config.relayUrl;31const statemineUrl = config.statemineUrl;32const karuraUrl = config.karuraUrl;33const moonriverUrl = config.moonriverUrl;34const shidenUrl = config.shidenUrl;3536const RELAY_DECIMALS = 12;37const STATEMINE_DECIMALS = 12;38const KARURA_DECIMALS = 12;39const SHIDEN_DECIMALS = 18n;40const QTZ_DECIMALS = 18n;4142const TRANSFER_AMOUNT = 2000000000000000000000000n;4344const FUNDING_AMOUNT = 3_500_000_0000_000_000n;4546const TRANSFER_AMOUNT_RELAY = 50_000_000_000_000_000n;4748const USDT_ASSET_ID = 100;49const USDT_ASSET_METADATA_DECIMALS = 18;50const USDT_ASSET_METADATA_NAME = 'USDT';51const USDT_ASSET_METADATA_DESCRIPTION = 'USDT';52const USDT_ASSET_METADATA_MINIMAL_BALANCE = 1n;53const USDT_ASSET_AMOUNT = 10_000_000_000_000_000_000_000_000n;5455const SAFE_XCM_VERSION = 2;5657describeXCM('[XCM] Integration test: Exchanging USDT with Statemine', () => {58  let alice: IKeyringPair;59  let bob: IKeyringPair;6061  let balanceStmnBefore: bigint;62  let balanceStmnAfter: bigint;6364  let balanceQuartzBefore: bigint;65  let balanceQuartzAfter: bigint;66  let balanceQuartzFinal: bigint;6768  let balanceBobBefore: bigint;69  let balanceBobAfter: bigint;70  let balanceBobFinal: bigint;7172  let balanceBobRelayTokenBefore: bigint;73  let balanceBobRelayTokenAfter: bigint;747576  before(async () => {77    await usingPlaygrounds(async (helper, privateKey) => {78      alice = await privateKey('//Alice');79      bob = await privateKey('//Bob'); // sovereign account on Statemine(t) funds donor8081      // Set the default version to wrap the first message to other chains.82      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);83    });8485    await usingRelayPlaygrounds(relayUrl, async (helper) => {86      // Fund accounts on Statemine(t)87      await helper.xcm.teleportNativeAsset(alice, STATEMINE_CHAIN, alice.addressRaw, FUNDING_AMOUNT);88      await helper.xcm.teleportNativeAsset(alice, STATEMINE_CHAIN, bob.addressRaw, FUNDING_AMOUNT);89    });9091    await usingStateminePlaygrounds(statemineUrl, async (helper) => {92      const sovereignFundingAmount = 3_500_000_000n;9394      await helper.assets.create(95        alice,96        USDT_ASSET_ID,97        alice.address,98        USDT_ASSET_METADATA_MINIMAL_BALANCE,99      );100      await helper.assets.setMetadata(101        alice,102        USDT_ASSET_ID,103        USDT_ASSET_METADATA_NAME,104        USDT_ASSET_METADATA_DESCRIPTION,105        USDT_ASSET_METADATA_DECIMALS,106      );107      await helper.assets.mint(108        alice,109        USDT_ASSET_ID,110        alice.address,111        USDT_ASSET_AMOUNT,112      );113114      // funding parachain sovereing account on Statemine(t).115      // The sovereign account should be created before any action116      // (the assets pallet on Statemine(t) check if the sovereign account exists)117      const parachainSovereingAccount = helper.address.paraSiblingSovereignAccount(QUARTZ_CHAIN);118      await helper.balance.transferToSubstrate(bob, parachainSovereingAccount, sovereignFundingAmount);119    });120121122    await usingPlaygrounds(async (helper) => {123      const location = {124        V2: {125          parents: 1,126          interior: {X3: [127            {128              Parachain: STATEMINE_CHAIN,129            },130            {131              PalletInstance: STATEMINE_PALLET_INSTANCE,132            },133            {134              GeneralIndex: USDT_ASSET_ID,135            },136          ]},137        },138      };139140      const metadata =141      {142        name: USDT_ASSET_ID,143        symbol: USDT_ASSET_METADATA_NAME,144        decimals: USDT_ASSET_METADATA_DECIMALS,145        minimalBalance: USDT_ASSET_METADATA_MINIMAL_BALANCE,146      };147      await helper.getSudo().foreignAssets.register(alice, alice.address, location, metadata);148      balanceQuartzBefore = await helper.balance.getSubstrate(alice.address);149    });150151152    // Providing the relay currency to the quartz sender account153    // (fee for USDT XCM are paid in relay tokens)154    await usingRelayPlaygrounds(relayUrl, async (helper) => {155      const destination = {156        V2: {157          parents: 0,158          interior: {X1: {159            Parachain: QUARTZ_CHAIN,160          },161          },162        }};163164      const beneficiary = {165        V2: {166          parents: 0,167          interior: {X1: {168            AccountId32: {169              network: 'Any',170              id: alice.addressRaw,171            },172          }},173        },174      };175176      const assets = {177        V2: [178          {179            id: {180              Concrete: {181                parents: 0,182                interior: 'Here',183              },184            },185            fun: {186              Fungible: TRANSFER_AMOUNT_RELAY,187            },188          },189        ],190      };191192      const feeAssetItem = 0;193194      await helper.xcm.limitedReserveTransferAssets(alice, destination, beneficiary, assets, feeAssetItem, 'Unlimited');195    });196197  });198199  itSub('Should connect and send USDT from Statemine to Quartz', async ({helper}) => {200    await usingStateminePlaygrounds(statemineUrl, async (helper) => {201      const dest = {202        V2: {203          parents: 1,204          interior: {X1: {205            Parachain: QUARTZ_CHAIN,206          },207          },208        }};209210      const beneficiary = {211        V2: {212          parents: 0,213          interior: {X1: {214            AccountId32: {215              network: 'Any',216              id: alice.addressRaw,217            },218          }},219        },220      };221222      const assets = {223        V2: [224          {225            id: {226              Concrete: {227                parents: 0,228                interior: {229                  X2: [230                    {231                      PalletInstance: STATEMINE_PALLET_INSTANCE,232                    },233                    {234                      GeneralIndex: USDT_ASSET_ID,235                    },236                  ]},237              },238            },239            fun: {240              Fungible: TRANSFER_AMOUNT,241            },242          },243        ],244      };245246      const feeAssetItem = 0;247248      balanceStmnBefore = await helper.balance.getSubstrate(alice.address);249      await helper.xcm.limitedReserveTransferAssets(alice, dest, beneficiary, assets, feeAssetItem, 'Unlimited');250251      balanceStmnAfter = await helper.balance.getSubstrate(alice.address);252253      // common good parachain take commission in it native token254      console.log(255        '[Statemine -> Quartz] transaction fees on Statemine: %s WND',256        helper.util.bigIntToDecimals(balanceStmnBefore - balanceStmnAfter, STATEMINE_DECIMALS),257      );258      expect(balanceStmnBefore > balanceStmnAfter).to.be.true;259260    });261262263    // ensure that asset has been delivered264    await helper.wait.newBlocks(3);265266    // expext collection id will be with id 1267    const free = await helper.ft.getBalance(1, {Substrate: alice.address});268269    balanceQuartzAfter = await helper.balance.getSubstrate(alice.address);270271    console.log(272      '[Statemine -> Quartz] transaction fees on Quartz: %s USDT',273      helper.util.bigIntToDecimals(TRANSFER_AMOUNT - free, USDT_ASSET_METADATA_DECIMALS),274    );275    console.log(276      '[Statemine -> Quartz] transaction fees on Quartz: %s QTZ',277      helper.util.bigIntToDecimals(balanceQuartzAfter - balanceQuartzBefore),278    );279    // commission has not paid in USDT token280    expect(free).to.be.equal(TRANSFER_AMOUNT);281    // ... and parachain native token282    expect(balanceQuartzAfter == balanceQuartzBefore).to.be.true;283  });284285  itSub('Should connect and send USDT from Quartz to Statemine back', async ({helper}) => {286    const destination = {287      V2: {288        parents: 1,289        interior: {X2: [290          {291            Parachain: STATEMINE_CHAIN,292          },293          {294            AccountId32: {295              network: 'Any',296              id: alice.addressRaw,297            },298          },299        ]},300      },301    };302303    const relayFee = 400_000_000_000_000n;304    const currencies: [any, bigint][] = [305      [306        {307          ForeignAssetId: 0,308        },309        TRANSFER_AMOUNT,310      ],311      [312        {313          NativeAssetId: 'Parent',314        },315        relayFee,316      ],317    ];318319    const feeItem = 1;320321    await helper.xTokens.transferMulticurrencies(alice, currencies, feeItem, destination, 'Unlimited');322323    // the commission has been paid in parachain native token324    balanceQuartzFinal = await helper.balance.getSubstrate(alice.address);325    console.log('[Quartz -> Statemine] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(balanceQuartzAfter - balanceQuartzFinal));326    expect(balanceQuartzAfter > balanceQuartzFinal).to.be.true;327328    await usingStateminePlaygrounds(statemineUrl, async (helper) => {329      await helper.wait.newBlocks(3);330331      // The USDT token never paid fees. Its amount not changed from begin value.332      // Also check that xcm transfer has been succeeded333      expect((await helper.assets.account(USDT_ASSET_ID, alice.address))! == USDT_ASSET_AMOUNT).to.be.true;334    });335  });336337  itSub('Should connect and send Relay token to Quartz', async ({helper}) => {338    balanceBobBefore = await helper.balance.getSubstrate(bob.address);339    balanceBobRelayTokenBefore = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});340341    await usingRelayPlaygrounds(relayUrl, async (helper) => {342      const destination = {343        V2: {344          parents: 0,345          interior: {X1: {346            Parachain: QUARTZ_CHAIN,347          },348          },349        }};350351      const beneficiary = {352        V2: {353          parents: 0,354          interior: {X1: {355            AccountId32: {356              network: 'Any',357              id: bob.addressRaw,358            },359          }},360        },361      };362363      const assets = {364        V2: [365          {366            id: {367              Concrete: {368                parents: 0,369                interior: 'Here',370              },371            },372            fun: {373              Fungible: TRANSFER_AMOUNT_RELAY,374            },375          },376        ],377      };378379      const feeAssetItem = 0;380381      await helper.xcm.limitedReserveTransferAssets(bob, destination, beneficiary, assets, feeAssetItem, 'Unlimited');382    });383384    await helper.wait.newBlocks(3);385386    balanceBobAfter = await helper.balance.getSubstrate(bob.address);387    balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});388389    const wndFeeOnQuartz = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;390    const wndDiffOnQuartz = balanceBobRelayTokenAfter - balanceBobRelayTokenBefore;391    console.log(392      '[Relay (Westend) -> Quartz] transaction fees: %s QTZ',393      helper.util.bigIntToDecimals(balanceBobAfter - balanceBobBefore),394    );395    console.log(396      '[Relay (Westend) -> Quartz] transaction fees: %s WND',397      helper.util.bigIntToDecimals(wndFeeOnQuartz, STATEMINE_DECIMALS),398    );399    console.log('[Relay (Westend) -> Quartz] actually delivered: %s WND', wndDiffOnQuartz);400    expect(wndFeeOnQuartz == 0n, 'No incoming WND fees should be taken').to.be.true;401    expect(balanceBobBefore == balanceBobAfter, 'No incoming QTZ fees should be taken').to.be.true;402  });403404  itSub('Should connect and send Relay token back', async ({helper}) => {405    let relayTokenBalanceBefore: bigint;406    let relayTokenBalanceAfter: bigint;407    await usingRelayPlaygrounds(relayUrl, async (helper) => {408      relayTokenBalanceBefore = await helper.balance.getSubstrate(bob.address);409    });410411    const destination = {412      V2: {413        parents: 1,414        interior: {415          X1:{416            AccountId32: {417              network: 'Any',418              id: bob.addressRaw,419            },420          },421        },422      },423    };424425    const currencies: any = [426      [427        {428          NativeAssetId: 'Parent',429        },430        TRANSFER_AMOUNT_RELAY,431      ],432    ];433434    const feeItem = 0;435436    await helper.xTokens.transferMulticurrencies(bob, currencies, feeItem, destination, 'Unlimited');437438    balanceBobFinal = await helper.balance.getSubstrate(bob.address);439    console.log('[Quartz -> Relay (Westend)] transaction fees: %s QTZ',  helper.util.bigIntToDecimals(balanceBobAfter - balanceBobFinal));440441    await usingRelayPlaygrounds(relayUrl, async (helper) => {442      await helper.wait.newBlocks(10);443      relayTokenBalanceAfter = await helper.balance.getSubstrate(bob.address);444445      const diff = relayTokenBalanceAfter - relayTokenBalanceBefore;446      console.log('[Quartz -> Relay (Westend)] actually delivered: %s WND', helper.util.bigIntToDecimals(diff, RELAY_DECIMALS));447      expect(diff > 0, 'Relay tokens was not delivered back').to.be.true;448    });449  });450});451452describeXCM('[XCM] Integration test: Exchanging tokens with Karura', () => {453  let alice: IKeyringPair;454  let randomAccount: IKeyringPair;455456  let balanceQuartzTokenInit: bigint;457  let balanceQuartzTokenMiddle: bigint;458  let balanceQuartzTokenFinal: bigint;459  let balanceKaruraTokenInit: bigint;460  let balanceKaruraTokenMiddle: bigint;461  let balanceKaruraTokenFinal: bigint;462  let balanceQuartzForeignTokenInit: bigint;463  let balanceQuartzForeignTokenMiddle: bigint;464  let balanceQuartzForeignTokenFinal: bigint;465466  // computed by a test transfer from prod Quartz to prod Karura.467  // 2 QTZ sent https://quartz.subscan.io/xcm_message/kusama-f60d821b049f8835a3005ce7102285006f5b61e9468  // 1.919176000000000000 QTZ received (you can check Karura's chain state in the corresponding block)469  const expectedKaruraIncomeFee = 2000000000000000000n - 1919176000000000000n;470471  const KARURA_BACKWARD_TRANSFER_AMOUNT = TRANSFER_AMOUNT - expectedKaruraIncomeFee;472473  before(async () => {474    await usingPlaygrounds(async (helper, privateKey) => {475      alice = await privateKey('//Alice');476      [randomAccount] = await helper.arrange.createAccounts([0n], alice);477478      // Set the default version to wrap the first message to other chains.479      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);480    });481482    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {483      const destination = {484        V1: {485          parents: 1,486          interior: {487            X1: {488              Parachain: QUARTZ_CHAIN,489            },490          },491        },492      };493494      const metadata = {495        name: 'Quartz',496        symbol: 'QTZ',497        decimals: 18,498        minimalBalance: 1000000000000000000n,499      };500501      await helper.getSudo().assetRegistry.registerForeignAsset(alice, destination, metadata);502      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);503      balanceKaruraTokenInit = await helper.balance.getSubstrate(randomAccount.address);504      balanceQuartzForeignTokenInit = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});505    });506507    await usingPlaygrounds(async (helper) => {508      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10n * TRANSFER_AMOUNT);509      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccount.address);510    });511  });512513  itSub('Should connect and send QTZ to Karura', async ({helper}) => {514    const destination = {515      V2: {516        parents: 1,517        interior: {518          X1: {519            Parachain: KARURA_CHAIN,520          },521        },522      },523    };524525    const beneficiary = {526      V2: {527        parents: 0,528        interior: {529          X1: {530            AccountId32: {531              network: 'Any',532              id: randomAccount.addressRaw,533            },534          },535        },536      },537    };538539    const assets = {540      V2: [541        {542          id: {543            Concrete: {544              parents: 0,545              interior: 'Here',546            },547          },548          fun: {549            Fungible: TRANSFER_AMOUNT,550          },551        },552      ],553    };554555    const feeAssetItem = 0;556557    await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');558    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);559560    const qtzFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;561    expect(qtzFees > 0n, 'Negative fees QTZ, looks like nothing was transferred').to.be.true;562    console.log('[Quartz -> Karura] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));563564    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {565      await helper.wait.newBlocks(3);566567      balanceQuartzForeignTokenMiddle = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});568      balanceKaruraTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);569570      const karFees = balanceKaruraTokenInit - balanceKaruraTokenMiddle;571      const qtzIncomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenInit;572      const karUnqFees = TRANSFER_AMOUNT - qtzIncomeTransfer;573574      console.log(575        '[Quartz -> Karura] transaction fees on Karura: %s KAR',576        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),577      );578      console.log(579        '[Quartz -> Karura] transaction fees on Karura: %s QTZ',580        helper.util.bigIntToDecimals(karUnqFees),581      );582      console.log('[Quartz -> Karura] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));583      expect(karFees == 0n).to.be.true;584      expect(585        karUnqFees == expectedKaruraIncomeFee,586        'Karura took different income fee, check the Karura foreign asset config',587      ).to.be.true;588    });589  });590591  itSub('Should connect to Karura and send QTZ back', async ({helper}) => {592    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {593      const destination = {594        V1: {595          parents: 1,596          interior: {597            X2: [598              {Parachain: QUARTZ_CHAIN},599              {600                AccountId32: {601                  network: 'Any',602                  id: randomAccount.addressRaw,603                },604              },605            ],606          },607        },608      };609610      const id = {611        ForeignAsset: 0,612      };613614      await helper.xTokens.transfer(randomAccount, id, KARURA_BACKWARD_TRANSFER_AMOUNT, destination, 'Unlimited');615      balanceKaruraTokenFinal = await helper.balance.getSubstrate(randomAccount.address);616      balanceQuartzForeignTokenFinal = await helper.tokens.accounts(randomAccount.address, id);617618      const karFees = balanceKaruraTokenMiddle - balanceKaruraTokenFinal;619      const qtzOutcomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenFinal;620621      console.log(622        '[Karura -> Quartz] transaction fees on Karura: %s KAR',623        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),624      );625      console.log('[Karura -> Quartz] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));626627      expect(karFees > 0, 'Negative fees KAR, looks like nothing was transferred').to.be.true;628      expect(qtzOutcomeTransfer == KARURA_BACKWARD_TRANSFER_AMOUNT).to.be.true;629    });630631    await helper.wait.newBlocks(3);632633    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccount.address);634    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;635    expect(actuallyDelivered > 0).to.be.true;636637    console.log('[Karura -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));638639    const qtzFees = KARURA_BACKWARD_TRANSFER_AMOUNT - actuallyDelivered;640    console.log('[Karura -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));641    expect(qtzFees == 0n).to.be.true;642  });643644  itSub('Karura can send only up to its balance', async ({helper}) => {645    // set Karura's sovereign account's balance646    const karuraBalance = 10000n * (10n ** QTZ_DECIMALS);647    const karuraSovereignAccount = helper.address.paraSiblingSovereignAccount(KARURA_CHAIN);648    await helper.getSudo().balance.setBalanceSubstrate(alice, karuraSovereignAccount, karuraBalance);649650    const moreThanKaruraHas = karuraBalance * 2n;651652    let targetAccountBalance = 0n;653    const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);654655    const quartzMultilocation = {656      V1: {657        parents: 1,658        interior: {659          X1: {Parachain: QUARTZ_CHAIN},660        },661      },662    };663664    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(665      targetAccount.addressRaw,666      {667        Concrete: {668          parents: 0,669          interior: 'Here',670        },671      },672      moreThanKaruraHas,673    );674675    let maliciousXcmProgramSent: any;676    const maxWaitBlocks = 3;677678    // Try to trick Quartz679    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {680      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);681682      maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);683    });684685    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {686      return event.messageHash() == maliciousXcmProgramSent.messageHash()687        && event.outcome().isFailedToTransactAsset;688    });689690    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);691    expect(targetAccountBalance).to.be.equal(0n);692693    // But Karura still can send the correct amount694    const validTransferAmount = karuraBalance / 2n;695    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(696      targetAccount.addressRaw,697      {698        Concrete: {699          parents: 0,700          interior: 'Here',701        },702      },703      validTransferAmount,704    );705706    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {707      await helper.getSudo().xcm.send(alice, quartzMultilocation, validXcmProgram);708    });709710    await helper.wait.newBlocks(maxWaitBlocks);711712    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);713    expect(targetAccountBalance).to.be.equal(validTransferAmount);714  });715716  itSub('Should not accept reserve transfer of QTZ from Karura', async ({helper}) => {717    const testAmount = 10_000n * (10n ** QTZ_DECIMALS);718    const [targetAccount] = await helper.arrange.createAccounts([0n], alice);719720    const quartzMultilocation = {721      V1: {722        parents: 1,723        interior: {724          X1: {725            Parachain: QUARTZ_CHAIN,726          },727        },728      },729    };730731    const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(732      targetAccount.addressRaw,733      {734        Concrete: {735          parents: 1,736          interior: {737            X1: {738              Parachain: QUARTZ_CHAIN,739            },740          },741        },742      },743      testAmount,744    );745746    const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(747      targetAccount.addressRaw,748      {749        Concrete: {750          parents: 0,751          interior: 'Here',752        },753      },754      testAmount,755    );756757    let maliciousXcmProgramFullIdSent: any;758    let maliciousXcmProgramHereIdSent: any;759    const maxWaitBlocks = 3;760761    // Try to trick Quartz using full QTZ identification762    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {763      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgramFullId);764765      maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);766    });767768    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {769      return event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()770        && event.outcome().isUntrustedReserveLocation;771    });772773    let accountBalance = await helper.balance.getSubstrate(targetAccount.address);774    expect(accountBalance).to.be.equal(0n);775776    // Try to trick Quartz using shortened QTZ identification777    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {778      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgramHereId);779780      maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);781    });782783    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {784      return event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()785        && event.outcome().isUntrustedReserveLocation;786    });787788    accountBalance = await helper.balance.getSubstrate(targetAccount.address);789    expect(accountBalance).to.be.equal(0n);790  });791});792793// These tests are relevant only when794// the the corresponding foreign assets are not registered795describeXCM('[XCM] Integration test: Quartz rejects non-native tokens', () => {796  let alice: IKeyringPair;797  let alith: IKeyringPair;798799  const testAmount = 100_000_000_000n;800  let quartzParachainJunction;801  let quartzAccountJunction;802803  let quartzParachainMultilocation: any;804  let quartzAccountMultilocation: any;805  let quartzCombinedMultilocation: any;806807  let messageSent: any;808809  const maxWaitBlocks = 3;810811  before(async () => {812    await usingPlaygrounds(async (helper, privateKey) => {813      alice = await privateKey('//Alice');814815      quartzParachainJunction = {Parachain: QUARTZ_CHAIN};816      quartzAccountJunction = {817        AccountId32: {818          network: 'Any',819          id: alice.addressRaw,820        },821      };822823      quartzParachainMultilocation = {824        V1: {825          parents: 1,826          interior: {827            X1: quartzParachainJunction,828          },829        },830      };831832      quartzAccountMultilocation = {833        V1: {834          parents: 0,835          interior: {836            X1: quartzAccountJunction,837          },838        },839      };840841      quartzCombinedMultilocation = {842        V1: {843          parents: 1,844          interior: {845            X2: [quartzParachainJunction, quartzAccountJunction],846          },847        },848      };849850      // Set the default version to wrap the first message to other chains.851      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);852    });853854    // eslint-disable-next-line require-await855    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {856      alith = helper.account.alithAccount();857    });858  });859860  const expectFailedToTransact = async (helper: DevUniqueHelper, messageSent: any) => {861    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {862      return event.messageHash() == messageSent.messageHash()863        && event.outcome().isFailedToTransactAsset;864    });865  };866867  itSub('Quartz rejects KAR tokens from Karura', async ({helper}) => {868    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {869      const id = {870        Token: 'KAR',871      };872      const destination = quartzCombinedMultilocation;873      await helper.xTokens.transfer(alice, id, testAmount, destination, 'Unlimited');874875      messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);876    });877878    await expectFailedToTransact(helper, messageSent);879  });880881  itSub('Quartz rejects MOVR tokens from Moonriver', async ({helper}) => {882    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {883      const id = 'SelfReserve';884      const destination = quartzCombinedMultilocation;885      await helper.xTokens.transfer(alith, id, testAmount, destination, 'Unlimited');886887      messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);888    });889890    await expectFailedToTransact(helper, messageSent);891  });892893  itSub('Quartz rejects SDN tokens from Shiden', async ({helper}) => {894    await usingShidenPlaygrounds(shidenUrl, async (helper) => {895      const destinationParachain = quartzParachainMultilocation;896      const beneficiary = quartzAccountMultilocation;897      const assets = {898        V1: [{899          id: {900            Concrete: {901              parents: 0,902              interior: 'Here',903            },904          },905          fun: {906            Fungible: testAmount,907          },908        }],909      };910      const feeAssetItem = 0;911912      await helper.executeExtrinsic(alice, 'api.tx.polkadotXcm.reserveWithdrawAssets', [913        destinationParachain,914        beneficiary,915        assets,916        feeAssetItem,917      ]);918919      messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);920    });921922    await expectFailedToTransact(helper, messageSent);923  });924});925926describeXCM('[XCM] Integration test: Exchanging QTZ with Moonriver', () => {927  // Quartz constants928  let alice: IKeyringPair;929  let quartzAssetLocation;930931  let randomAccountQuartz: IKeyringPair;932  let randomAccountMoonriver: IKeyringPair;933934  // Moonriver constants935  let assetId: string;936937  const quartzAssetMetadata = {938    name: 'xcQuartz',939    symbol: 'xcQTZ',940    decimals: 18,941    isFrozen: false,942    minimalBalance: 1n,943  };944945  let balanceQuartzTokenInit: bigint;946  let balanceQuartzTokenMiddle: bigint;947  let balanceQuartzTokenFinal: bigint;948  let balanceForeignQtzTokenInit: bigint;949  let balanceForeignQtzTokenMiddle: bigint;950  let balanceForeignQtzTokenFinal: bigint;951  let balanceMovrTokenInit: bigint;952  let balanceMovrTokenMiddle: bigint;953  let balanceMovrTokenFinal: bigint;954955  before(async () => {956    await usingPlaygrounds(async (helper, privateKey) => {957      alice = await privateKey('//Alice');958      [randomAccountQuartz] = await helper.arrange.createAccounts([0n], alice);959960      balanceForeignQtzTokenInit = 0n;961962      // Set the default version to wrap the first message to other chains.963      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);964    });965966    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {967      const alithAccount = helper.account.alithAccount();968      const baltatharAccount = helper.account.baltatharAccount();969      const dorothyAccount = helper.account.dorothyAccount();970971      randomAccountMoonriver = helper.account.create();972973      // >>> Sponsoring Dorothy >>>974      console.log('Sponsoring Dorothy.......');975      await helper.balance.transferToEthereum(alithAccount, dorothyAccount.address, 11_000_000_000_000_000_000n);976      console.log('Sponsoring Dorothy.......DONE');977      // <<< Sponsoring Dorothy <<<978979      quartzAssetLocation = {980        XCM: {981          parents: 1,982          interior: {X1: {Parachain: QUARTZ_CHAIN}},983        },984      };985      const existentialDeposit = 1n;986      const isSufficient = true;987      const unitsPerSecond = 1n;988      const numAssetsWeightHint = 0;989990      const encodedProposal = helper.assetManager.makeRegisterForeignAssetProposal({991        location: quartzAssetLocation,992        metadata: quartzAssetMetadata,993        existentialDeposit,994        isSufficient,995        unitsPerSecond,996        numAssetsWeightHint,997      });998999      console.log('Encoded proposal for registerForeignAsset & setAssetUnitsPerSecond is %s', encodedProposal);10001001      await helper.fastDemocracy.executeProposal('register QTZ foreign asset', encodedProposal);10021003      // >>> Acquire Quartz AssetId Info on Moonriver >>>1004      console.log('Acquire Quartz AssetId Info on Moonriver.......');10051006      assetId = (await helper.assetManager.assetTypeId(quartzAssetLocation)).toString();10071008      console.log('QTZ asset ID is %s', assetId);1009      console.log('Acquire Quartz AssetId Info on Moonriver.......DONE');1010      // >>> Acquire Quartz AssetId Info on Moonriver >>>10111012      // >>> Sponsoring random Account >>>1013      console.log('Sponsoring random Account.......');1014      await helper.balance.transferToEthereum(baltatharAccount, randomAccountMoonriver.address, 11_000_000_000_000_000_000n);1015      console.log('Sponsoring random Account.......DONE');1016      // <<< Sponsoring random Account <<<10171018      balanceMovrTokenInit = await helper.balance.getEthereum(randomAccountMoonriver.address);1019    });10201021    await usingPlaygrounds(async (helper) => {1022      await helper.balance.transferToSubstrate(alice, randomAccountQuartz.address, 10n * TRANSFER_AMOUNT);1023      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccountQuartz.address);1024    });1025  });10261027  itSub('Should connect and send QTZ to Moonriver', async ({helper}) => {1028    const currencyId = {1029      NativeAssetId: 'Here',1030    };1031    const dest = {1032      V2: {1033        parents: 1,1034        interior: {1035          X2: [1036            {Parachain: MOONRIVER_CHAIN},1037            {AccountKey20: {network: 'Any', key: randomAccountMoonriver.address}},1038          ],1039        },1040      },1041    };1042    const amount = TRANSFER_AMOUNT;10431044    await helper.xTokens.transfer(randomAccountQuartz, currencyId, amount, dest, 'Unlimited');10451046    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccountQuartz.address);1047    expect(balanceQuartzTokenMiddle < balanceQuartzTokenInit).to.be.true;10481049    const transactionFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;1050    console.log('[Quartz -> Moonriver] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(transactionFees));1051    expect(transactionFees > 0, 'Negative fees QTZ, looks like nothing was transferred').to.be.true;10521053    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1054      await helper.wait.newBlocks(3);10551056      balanceMovrTokenMiddle = await helper.balance.getEthereum(randomAccountMoonriver.address);10571058      const movrFees = balanceMovrTokenInit - balanceMovrTokenMiddle;1059      console.log('[Quartz -> Moonriver] transaction fees on Moonriver: %s MOVR',helper.util.bigIntToDecimals(movrFees));1060      expect(movrFees == 0n).to.be.true;10611062      balanceForeignQtzTokenMiddle = (await helper.assets.account(assetId, randomAccountMoonriver.address))!; // BigInt(qtzRandomAccountAsset['balance']);1063      const qtzIncomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenInit;1064      console.log('[Quartz -> Moonriver] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));1065      expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;1066    });1067  });10681069  itSub('Should connect to Moonriver and send QTZ back', async ({helper}) => {1070    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1071      const asset = {1072        V1: {1073          id: {1074            Concrete: {1075              parents: 1,1076              interior: {1077                X1: {Parachain: QUARTZ_CHAIN},1078              },1079            },1080          },1081          fun: {1082            Fungible: TRANSFER_AMOUNT,1083          },1084        },1085      };1086      const destination = {1087        V1: {1088          parents: 1,1089          interior: {1090            X2: [1091              {Parachain: QUARTZ_CHAIN},1092              {AccountId32: {network: 'Any', id: randomAccountQuartz.addressRaw}},1093            ],1094          },1095        },1096      };10971098      await helper.xTokens.transferMultiasset(randomAccountMoonriver, asset, destination, 'Unlimited');10991100      balanceMovrTokenFinal = await helper.balance.getEthereum(randomAccountMoonriver.address);11011102      const movrFees = balanceMovrTokenMiddle - balanceMovrTokenFinal;1103      console.log('[Moonriver -> Quartz] transaction fees on Moonriver: %s MOVR', helper.util.bigIntToDecimals(movrFees));1104      expect(movrFees > 0, 'Negative fees MOVR, looks like nothing was transferred').to.be.true;11051106      const qtzRandomAccountAsset = await helper.assets.account(assetId, randomAccountMoonriver.address);11071108      expect(qtzRandomAccountAsset).to.be.null;11091110      balanceForeignQtzTokenFinal = 0n;11111112      const qtzOutcomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenFinal;1113      console.log('[Quartz -> Moonriver] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));1114      expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;1115    });11161117    await helper.wait.newBlocks(3);11181119    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccountQuartz.address);1120    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;1121    expect(actuallyDelivered > 0).to.be.true;11221123    console.log('[Moonriver -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));11241125    const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;1126    console.log('[Moonriver -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));1127    expect(qtzFees == 0n).to.be.true;1128  });11291130  itSub('Moonriver can send only up to its balance', async ({helper}) => {1131    // set Moonriver's sovereign account's balance1132    const moonriverBalance = 10000n * (10n ** QTZ_DECIMALS);1133    const moonriverSovereignAccount = helper.address.paraSiblingSovereignAccount(MOONRIVER_CHAIN);1134    await helper.getSudo().balance.setBalanceSubstrate(alice, moonriverSovereignAccount, moonriverBalance);11351136    const moreThanMoonriverHas = moonriverBalance * 2n;11371138    let targetAccountBalance = 0n;1139    const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);11401141    const quartzMultilocation = {1142      V1: {1143        parents: 1,1144        interior: {1145          X1: {Parachain: QUARTZ_CHAIN},1146        },1147      },1148    };11491150    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(1151      targetAccount.addressRaw,1152      {1153        Concrete: {1154          parents: 0,1155          interior: 'Here',1156        },1157      },1158      moreThanMoonriverHas,1159    );11601161    let maliciousXcmProgramSent: any;1162    const maxWaitBlocks = 3;11631164    // Try to trick Quartz1165    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1166      const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [quartzMultilocation, maliciousXcmProgram]);11671168      // Needed to bypass the call filter.1169      const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);1170      await helper.fastDemocracy.executeProposal('try to spend more QTZ than Moonriver has', batchCall);11711172      maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1173    });11741175    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {1176      return event.messageHash() == maliciousXcmProgramSent.messageHash()1177        && event.outcome().isFailedToTransactAsset;1178    });11791180    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);1181    expect(targetAccountBalance).to.be.equal(0n);11821183    // But Moonriver still can send the correct amount1184    const validTransferAmount = moonriverBalance / 2n;1185    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(1186      targetAccount.addressRaw,1187      {1188        Concrete: {1189          parents: 0,1190          interior: 'Here',1191        },1192      },1193      validTransferAmount,1194    );11951196    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1197      const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [quartzMultilocation, validXcmProgram]);11981199      // Needed to bypass the call filter.1200      const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);1201      await helper.fastDemocracy.executeProposal('Spend the correct amount of QTZ', batchCall);1202    });12031204    await helper.wait.newBlocks(maxWaitBlocks);12051206    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);1207    expect(targetAccountBalance).to.be.equal(validTransferAmount);1208  });12091210  itSub('Should not accept reserve transfer of QTZ from Moonriver', async ({helper}) => {1211    const testAmount = 10_000n * (10n ** QTZ_DECIMALS);1212    const [targetAccount] = await helper.arrange.createAccounts([0n], alice);12131214    const quartzMultilocation = {1215      V1: {1216        parents: 1,1217        interior: {1218          X1: {1219            Parachain: QUARTZ_CHAIN,1220          },1221        },1222      },1223    };12241225    const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(1226      targetAccount.addressRaw,1227      {1228        Concrete: {1229          parents: 0,1230          interior: {1231            X1: {1232              Parachain: QUARTZ_CHAIN,1233            },1234          },1235        },1236      },1237      testAmount,1238    );12391240    const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(1241      targetAccount.addressRaw,1242      {1243        Concrete: {1244          parents: 0,1245          interior: 'Here',1246        },1247      },1248      testAmount,1249    );12501251    let maliciousXcmProgramFullIdSent: any;1252    let maliciousXcmProgramHereIdSent: any;1253    const maxWaitBlocks = 3;12541255    // Try to trick Quartz using full QTZ identification1256    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1257      const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [quartzMultilocation, maliciousXcmProgramFullId]);12581259      // Needed to bypass the call filter.1260      const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);1261      await helper.fastDemocracy.executeProposal('try to act like a reserve location for QTZ using path asset identification', batchCall);12621263      maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1264    });12651266    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {1267      return event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()1268        && event.outcome().isUntrustedReserveLocation;1269    });12701271    let accountBalance = await helper.balance.getSubstrate(targetAccount.address);1272    expect(accountBalance).to.be.equal(0n);12731274    // Try to trick Quartz using shortened QTZ identification1275    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {1276      const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [quartzMultilocation, maliciousXcmProgramHereId]);12771278      // Needed to bypass the call filter.1279      const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);1280      await helper.fastDemocracy.executeProposal('try to act like a reserve location for QTZ using "here" asset identification', batchCall);12811282      maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1283    });12841285    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {1286      return event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()1287        && event.outcome().isUntrustedReserveLocation;1288    });12891290    accountBalance = await helper.balance.getSubstrate(targetAccount.address);1291    expect(accountBalance).to.be.equal(0n);1292  });1293});12941295describeXCM('[XCM] Integration test: Exchanging tokens with Shiden', () => {1296  let alice: IKeyringPair;1297  let sender: IKeyringPair;12981299  const QTZ_ASSET_ID_ON_SHIDEN = 1;1300  const QTZ_MINIMAL_BALANCE_ON_SHIDEN = 1n;13011302  // Quartz -> Shiden1303  const shidenInitialBalance = 1n * (10n ** SHIDEN_DECIMALS); // 1 SHD, existential deposit required to actually create the account on Shiden1304  const unitsPerSecond = 228_000_000_000n; // This is Phala's value. What will be ours?1305  const qtzToShidenTransferred = 10n * (10n ** QTZ_DECIMALS); // 10 QTZ1306  const qtzToShidenArrived = 9_999_999_999_088_000_000n; // 9.999 ... QTZ, Shiden takes a commision in foreign tokens13071308  // Shiden -> Quartz1309  const qtzFromShidenTransfered = 5n * (10n ** QTZ_DECIMALS); // 5 QTZ1310  const qtzOnShidenLeft = qtzToShidenArrived - qtzFromShidenTransfered; // 4.999_999_999_088_000_000n QTZ13111312  let balanceAfterQuartzToShidenXCM: bigint;13131314  before(async () => {1315    await usingPlaygrounds(async (helper, privateKey) => {1316      alice = await privateKey('//Alice');1317      [sender] = await helper.arrange.createAccounts([100n], alice);1318      console.log('sender', sender.address);13191320      // Set the default version to wrap the first message to other chains.1321      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);1322    });13231324    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1325      console.log('1. Create foreign asset and metadata');1326      // TODO update metadata with values from production1327      await helper.assets.create(1328        alice,1329        QTZ_ASSET_ID_ON_SHIDEN,1330        alice.address,1331        QTZ_MINIMAL_BALANCE_ON_SHIDEN,1332      );13331334      await helper.assets.setMetadata(1335        alice,1336        QTZ_ASSET_ID_ON_SHIDEN,1337        'Cross chain QTZ',1338        'xcQTZ',1339        Number(QTZ_DECIMALS),1340      );13411342      console.log('2. Register asset location on Shiden');1343      const assetLocation = {1344        V1: {1345          parents: 1,1346          interior: {1347            X1: {1348              Parachain: QUARTZ_CHAIN,1349            },1350          },1351        },1352      };13531354      await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.registerAssetLocation', [assetLocation, QTZ_ASSET_ID_ON_SHIDEN]);13551356      console.log('3. Set QTZ payment for XCM execution on Shiden');1357      await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.setAssetUnitsPerSecond', [assetLocation, unitsPerSecond]);13581359      console.log('4. Transfer 1 SDN to recipient to create the account (needed due to existential balance)');1360      await helper.balance.transferToSubstrate(alice, sender.address, shidenInitialBalance);1361    });1362  });13631364  itSub('Should connect and send QTZ to Shiden', async ({helper}) => {1365    const destination = {1366      V2: {1367        parents: 1,1368        interior: {1369          X1: {1370            Parachain: SHIDEN_CHAIN,1371          },1372        },1373      },1374    };13751376    const beneficiary = {1377      V2: {1378        parents: 0,1379        interior: {1380          X1: {1381            AccountId32: {1382              network: 'Any',1383              id: sender.addressRaw,1384            },1385          },1386        },1387      },1388    };13891390    const assets = {1391      V2: [1392        {1393          id: {1394            Concrete: {1395              parents: 0,1396              interior: 'Here',1397            },1398          },1399          fun: {1400            Fungible: qtzToShidenTransferred,1401          },1402        },1403      ],1404    };14051406    // Initial balance is 100 QTZ1407    const balanceBefore = await helper.balance.getSubstrate(sender.address);1408    console.log(`Initial balance is: ${balanceBefore}`);14091410    const feeAssetItem = 0;1411    await helper.xcm.limitedReserveTransferAssets(sender, destination, beneficiary, assets, feeAssetItem, 'Unlimited');14121413    // Balance after reserve transfer is less than 901414    balanceAfterQuartzToShidenXCM = await helper.balance.getSubstrate(sender.address);1415    console.log(`QTZ Balance on Quartz after XCM is: ${balanceAfterQuartzToShidenXCM}`);1416    console.log(`Quartz's QTZ commission is: ${balanceBefore - balanceAfterQuartzToShidenXCM}`);1417    expect(balanceBefore - balanceAfterQuartzToShidenXCM > 0).to.be.true;14181419    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1420      await helper.wait.newBlocks(3);1421      const xcQTZbalance = await helper.assets.account(QTZ_ASSET_ID_ON_SHIDEN, sender.address);1422      const shidenBalance = await helper.balance.getSubstrate(sender.address);14231424      console.log(`xcQTZ balance on Shiden after XCM is: ${xcQTZbalance}`);1425      console.log(`Shiden's QTZ commission is: ${qtzToShidenTransferred - xcQTZbalance!}`);14261427      expect(xcQTZbalance).to.eq(qtzToShidenArrived);1428      // SHD balance does not changed:1429      expect(shidenBalance).to.eq(shidenInitialBalance);1430    });1431  });14321433  itSub('Should connect to Shiden and send QTZ back', async ({helper}) => {1434    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1435      const destination = {1436        V1: {1437          parents: 1,1438          interior: {1439            X1: {1440              Parachain: QUARTZ_CHAIN,1441            },1442          },1443        },1444      };14451446      const beneficiary = {1447        V1: {1448          parents: 0,1449          interior: {1450            X1: {1451              AccountId32: {1452                network: 'Any',1453                id: sender.addressRaw,1454              },1455            },1456          },1457        },1458      };14591460      const assets = {1461        V1: [1462          {1463            id: {1464              Concrete: {1465                parents: 1,1466                interior: {1467                  X1: {1468                    Parachain: QUARTZ_CHAIN,1469                  },1470                },1471              },1472            },1473            fun: {1474              Fungible: qtzFromShidenTransfered,1475            },1476          },1477        ],1478      };14791480      // Initial balance is 1 SDN1481      const balanceSDNbefore = await helper.balance.getSubstrate(sender.address);1482      console.log(`SDN balance is: ${balanceSDNbefore}, it does not changed`);1483      expect(balanceSDNbefore).to.eq(shidenInitialBalance);14841485      const feeAssetItem = 0;1486      // this is non-standard polkadotXcm extension for Astar only. It calls InitiateReserveWithdraw1487      await helper.executeExtrinsic(sender, 'api.tx.polkadotXcm.reserveWithdrawAssets', [destination, beneficiary, assets, feeAssetItem]);14881489      // Balance after reserve transfer is less than 1 SDN1490      const xcQTZbalance = await helper.assets.account(QTZ_ASSET_ID_ON_SHIDEN, sender.address);1491      const balanceSDN = await helper.balance.getSubstrate(sender.address);1492      console.log(`xcQTZ balance on Shiden after XCM is: ${xcQTZbalance}`);14931494      // Assert: xcQTZ balance correctly decreased1495      expect(xcQTZbalance).to.eq(qtzOnShidenLeft);1496      // Assert: SDN balance is 0.996...1497      expect(balanceSDN / (10n ** (SHIDEN_DECIMALS - 3n))).to.eq(996n);1498    });14991500    await helper.wait.newBlocks(3);1501    const balanceQTZ = await helper.balance.getSubstrate(sender.address);1502    console.log(`QTZ Balance on Quartz after XCM is: ${balanceQTZ}`);1503    expect(balanceQTZ).to.eq(balanceAfterQuartzToShidenXCM + qtzFromShidenTransfered);1504  });15051506  itSub('Shiden can send only up to its balance', async ({helper}) => {1507    // set Shiden's sovereign account's balance1508    const shidenBalance = 10000n * (10n ** QTZ_DECIMALS);1509    const shidenSovereignAccount = helper.address.paraSiblingSovereignAccount(SHIDEN_CHAIN);1510    await helper.getSudo().balance.setBalanceSubstrate(alice, shidenSovereignAccount, shidenBalance);15111512    const moreThanShidenHas = shidenBalance * 2n;15131514    let targetAccountBalance = 0n;1515    const [targetAccount] = await helper.arrange.createAccounts([targetAccountBalance], alice);15161517    const quartzMultilocation = {1518      V1: {1519        parents: 1,1520        interior: {1521          X1: {Parachain: QUARTZ_CHAIN},1522        },1523      },1524    };15251526    const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(1527      targetAccount.addressRaw,1528      {1529        Concrete: {1530          parents: 0,1531          interior: 'Here',1532        },1533      },1534      moreThanShidenHas,1535    );15361537    let maliciousXcmProgramSent: any;1538    const maxWaitBlocks = 3;15391540    // Try to trick Quartz1541    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1542      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgram);15431544      maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1545    });15461547    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {1548      return event.messageHash() == maliciousXcmProgramSent.messageHash()1549        && event.outcome().isFailedToTransactAsset;1550    });15511552    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);1553    expect(targetAccountBalance).to.be.equal(0n);15541555    // But Shiden still can send the correct amount1556    const validTransferAmount = shidenBalance / 2n;1557    const validXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(1558      targetAccount.addressRaw,1559      {1560        Concrete: {1561          parents: 0,1562          interior: 'Here',1563        },1564      },1565      validTransferAmount,1566    );15671568    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1569      await helper.getSudo().xcm.send(alice, quartzMultilocation, validXcmProgram);1570    });15711572    await helper.wait.newBlocks(maxWaitBlocks);15731574    targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);1575    expect(targetAccountBalance).to.be.equal(validTransferAmount);1576  });15771578  itSub('Should not accept reserve transfer of QTZ from Shiden', async ({helper}) => {1579    const testAmount = 10_000n * (10n ** QTZ_DECIMALS);1580    const [targetAccount] = await helper.arrange.createAccounts([0n], alice);15811582    const quartzMultilocation = {1583      V1: {1584        parents: 1,1585        interior: {1586          X1: {1587            Parachain: QUARTZ_CHAIN,1588          },1589        },1590      },1591    };15921593    const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(1594      targetAccount.addressRaw,1595      {1596        Concrete: {1597          parents: 1,1598          interior: {1599            X1: {1600              Parachain: QUARTZ_CHAIN,1601            },1602          },1603        },1604      },1605      testAmount,1606    );16071608    const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(1609      targetAccount.addressRaw,1610      {1611        Concrete: {1612          parents: 0,1613          interior: 'Here',1614        },1615      },1616      testAmount,1617    );16181619    let maliciousXcmProgramFullIdSent: any;1620    let maliciousXcmProgramHereIdSent: any;1621    const maxWaitBlocks = 3;16221623    // Try to trick Quartz using full QTZ identification1624    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1625      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgramFullId);16261627      maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1628    });16291630    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {1631      return event.messageHash() == maliciousXcmProgramFullIdSent.messageHash()1632        && event.outcome().isUntrustedReserveLocation;1633    });16341635    let accountBalance = await helper.balance.getSubstrate(targetAccount.address);1636    expect(accountBalance).to.be.equal(0n);16371638    // Try to trick Quartz using shortened QTZ identification1639    await usingShidenPlaygrounds(shidenUrl, async (helper) => {1640      await helper.getSudo().xcm.send(alice, quartzMultilocation, maliciousXcmProgramHereId);16411642      maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);1643    });16441645    await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => {1646      return event.messageHash() == maliciousXcmProgramHereIdSent.messageHash()1647        && event.outcome().isUntrustedReserveLocation;1648    });16491650    accountBalance = await helper.balance.getSubstrate(targetAccount.address);1651    expect(accountBalance).to.be.equal(0n);1652  });1653});