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

difftreelog

source

tests/src/xcm/xcmQuartz.test.ts32.8 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 {blake2AsHex} from '@polkadot/util-crypto';19import config from '../config';20import {XcmV2TraitsError} from '../interfaces';21import {itSub, expect, describeXCM, usingPlaygrounds, usingKaruraPlaygrounds, usingRelayPlaygrounds, usingMoonriverPlaygrounds, usingStateminePlaygrounds} from '../util';2223const QUARTZ_CHAIN = 2095;24const STATEMINE_CHAIN = 1000;25const KARURA_CHAIN = 2000;26const MOONRIVER_CHAIN = 2023;2728const STATEMINE_PALLET_INSTANCE = 50;2930const relayUrl = config.relayUrl;31const statemineUrl = config.statemineUrl;32const karuraUrl = config.karuraUrl;33const moonriverUrl = config.moonriverUrl;3435const RELAY_DECIMALS = 12;36const STATEMINE_DECIMALS = 12;37const KARURA_DECIMALS = 12;3839const TRANSFER_AMOUNT = 2000000000000000000000000n;4041const FUNDING_AMOUNT = 3_500_000_0000_000_000n;4243const TRANSFER_AMOUNT_RELAY = 50_000_000_000_000_000n;4445const USDT_ASSET_ID = 100;46const USDT_ASSET_METADATA_DECIMALS = 18;47const USDT_ASSET_METADATA_NAME = 'USDT';48const USDT_ASSET_METADATA_DESCRIPTION = 'USDT';49const USDT_ASSET_METADATA_MINIMAL_BALANCE = 1n;50const USDT_ASSET_AMOUNT = 10_000_000_000_000_000_000_000_000n;5152const SAFE_XCM_VERSION = 2;5354describeXCM('[XCM] Integration test: Exchanging USDT with Statemine', () => {55  let alice: IKeyringPair;56  let bob: IKeyringPair;5758  let balanceStmnBefore: bigint;59  let balanceStmnAfter: bigint;6061  let balanceQuartzBefore: bigint;62  let balanceQuartzAfter: bigint;63  let balanceQuartzFinal: bigint;6465  let balanceBobBefore: bigint;66  let balanceBobAfter: bigint;67  let balanceBobFinal: bigint;6869  let balanceBobRelayTokenBefore: bigint;70  let balanceBobRelayTokenAfter: bigint;717273  before(async () => {74    await usingPlaygrounds(async (helper, privateKey) => {75      alice = await privateKey('//Alice');76      bob = await privateKey('//Bob'); // sovereign account on Statemine(t) funds donor7778      // Set the default version to wrap the first message to other chains.79      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);80    });8182    await usingRelayPlaygrounds(relayUrl, async (helper) => {83      // Fund accounts on Statemine(t)84      await helper.xcm.teleportNativeAsset(alice, STATEMINE_CHAIN, alice.addressRaw, FUNDING_AMOUNT);85      await helper.xcm.teleportNativeAsset(alice, STATEMINE_CHAIN, bob.addressRaw, FUNDING_AMOUNT);86    });8788    await usingStateminePlaygrounds(statemineUrl, async (helper) => {89      const sovereignFundingAmount = 3_500_000_000n;9091      await helper.assets.create(92        alice,93        USDT_ASSET_ID,94        alice.address,95        USDT_ASSET_METADATA_MINIMAL_BALANCE,96      );97      await helper.assets.setMetadata(98        alice,99        USDT_ASSET_ID,100        USDT_ASSET_METADATA_NAME,101        USDT_ASSET_METADATA_DESCRIPTION,102        USDT_ASSET_METADATA_DECIMALS,103      );104      await helper.assets.mint(105        alice,106        USDT_ASSET_ID,107        alice.address,108        USDT_ASSET_AMOUNT,109      );110111      // funding parachain sovereing account on Statemine(t).112      // The sovereign account should be created before any action113      // (the assets pallet on Statemine(t) check if the sovereign account exists)114      const parachainSovereingAccount = helper.address.paraSiblingSovereignAccount(QUARTZ_CHAIN);115      await helper.balance.transferToSubstrate(bob, parachainSovereingAccount, sovereignFundingAmount);116    });117118119    await usingPlaygrounds(async (helper) => {120      const location = {121        V2: {122          parents: 1,123          interior: {X3: [124            {125              Parachain: STATEMINE_CHAIN,126            },127            {128              PalletInstance: STATEMINE_PALLET_INSTANCE,129            },130            {131              GeneralIndex: USDT_ASSET_ID,132            },133          ]},134        },135      };136137      const metadata =138      {139        name: USDT_ASSET_ID,140        symbol: USDT_ASSET_METADATA_NAME,141        decimals: USDT_ASSET_METADATA_DECIMALS,142        minimalBalance: USDT_ASSET_METADATA_MINIMAL_BALANCE,143      };144      await helper.getSudo().foreignAssets.register(alice, alice.address, location, metadata);145      balanceQuartzBefore = await helper.balance.getSubstrate(alice.address);146    });147148149    // Providing the relay currency to the quartz sender account150    // (fee for USDT XCM are paid in relay tokens)151    await usingRelayPlaygrounds(relayUrl, async (helper) => {152      const destination = {153        V1: {154          parents: 0,155          interior: {X1: {156            Parachain: QUARTZ_CHAIN,157          },158          },159        }};160161      const beneficiary = {162        V1: {163          parents: 0,164          interior: {X1: {165            AccountId32: {166              network: 'Any',167              id: alice.addressRaw,168            },169          }},170        },171      };172173      const assets = {174        V1: [175          {176            id: {177              Concrete: {178                parents: 0,179                interior: 'Here',180              },181            },182            fun: {183              Fungible: TRANSFER_AMOUNT_RELAY,184            },185          },186        ],187      };188189      const feeAssetItem = 0;190191      await helper.xcm.limitedReserveTransferAssets(alice, destination, beneficiary, assets, feeAssetItem, 'Unlimited');192    });193194  });195196  itSub('Should connect and send USDT from Statemine to Quartz', async ({helper}) => {197    await usingStateminePlaygrounds(statemineUrl, async (helper) => {198      const dest = {199        V1: {200          parents: 1,201          interior: {X1: {202            Parachain: QUARTZ_CHAIN,203          },204          },205        }};206207      const beneficiary = {208        V1: {209          parents: 0,210          interior: {X1: {211            AccountId32: {212              network: 'Any',213              id: alice.addressRaw,214            },215          }},216        },217      };218219      const assets = {220        V1: [221          {222            id: {223              Concrete: {224                parents: 0,225                interior: {226                  X2: [227                    {228                      PalletInstance: STATEMINE_PALLET_INSTANCE,229                    },230                    {231                      GeneralIndex: USDT_ASSET_ID,232                    },233                  ]},234              },235            },236            fun: {237              Fungible: TRANSFER_AMOUNT,238            },239          },240        ],241      };242243      const feeAssetItem = 0;244245      balanceStmnBefore = await helper.balance.getSubstrate(alice.address);246      await helper.xcm.limitedReserveTransferAssets(alice, dest, beneficiary, assets, feeAssetItem, 'Unlimited');247248      balanceStmnAfter = await helper.balance.getSubstrate(alice.address);249250      // common good parachain take commission in it native token251      console.log(252        '[Statemine -> Quartz] transaction fees on Statemine: %s WND',253        helper.util.bigIntToDecimals(balanceStmnBefore - balanceStmnAfter, STATEMINE_DECIMALS),254      );255      expect(balanceStmnBefore > balanceStmnAfter).to.be.true;256257    });258259260    // ensure that asset has been delivered261    await helper.wait.newBlocks(3);262263    // expext collection id will be with id 1264    const free = await helper.ft.getBalance(1, {Substrate: alice.address});265266    balanceQuartzAfter = await helper.balance.getSubstrate(alice.address);267268    console.log(269      '[Statemine -> Quartz] transaction fees on Quartz: %s USDT',270      helper.util.bigIntToDecimals(TRANSFER_AMOUNT - free, USDT_ASSET_METADATA_DECIMALS),271    );272    console.log(273      '[Statemine -> Quartz] transaction fees on Quartz: %s QTZ',274      helper.util.bigIntToDecimals(balanceQuartzAfter - balanceQuartzBefore),275    );276    // commission has not paid in USDT token277    expect(free).to.be.equal(TRANSFER_AMOUNT);278    // ... and parachain native token279    expect(balanceQuartzAfter == balanceQuartzBefore).to.be.true;280  });281282  itSub('Should connect and send USDT from Quartz to Statemine back', async ({helper}) => {283    const destination = {284      V2: {285        parents: 1,286        interior: {X2: [287          {288            Parachain: STATEMINE_CHAIN,289          },290          {291            AccountId32: {292              network: 'Any',293              id: alice.addressRaw,294            },295          },296        ]},297      },298    };299300    const relayFee = 400_000_000_000_000n;301    const currencies: [any, bigint][] = [302      [303        {304          ForeignAssetId: 0,305        },306        TRANSFER_AMOUNT,307      ],308      [309        {310          NativeAssetId: 'Parent',311        },312        relayFee,313      ],314    ];315316    const feeItem = 1;317318    await helper.xTokens.transferMulticurrencies(alice, currencies, feeItem, destination, 'Unlimited');319320    // the commission has been paid in parachain native token321    balanceQuartzFinal = await helper.balance.getSubstrate(alice.address);322    console.log('[Quartz -> Statemine] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(balanceQuartzAfter - balanceQuartzFinal));323    expect(balanceQuartzAfter > balanceQuartzFinal).to.be.true;324325    await usingStateminePlaygrounds(statemineUrl, async (helper) => {326      await helper.wait.newBlocks(3);327328      // The USDT token never paid fees. Its amount not changed from begin value.329      // Also check that xcm transfer has been succeeded330      expect((await helper.assets.account(USDT_ASSET_ID, alice.address))! == USDT_ASSET_AMOUNT).to.be.true;331    });332  });333334  itSub('Should connect and send Relay token to Quartz', async ({helper}) => {335    balanceBobBefore = await helper.balance.getSubstrate(bob.address);336    balanceBobRelayTokenBefore = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});337338    await usingRelayPlaygrounds(relayUrl, async (helper) => {339      const destination = {340        V1: {341          parents: 0,342          interior: {X1: {343            Parachain: QUARTZ_CHAIN,344          },345          },346        }};347348      const beneficiary = {349        V1: {350          parents: 0,351          interior: {X1: {352            AccountId32: {353              network: 'Any',354              id: bob.addressRaw,355            },356          }},357        },358      };359360      const assets = {361        V1: [362          {363            id: {364              Concrete: {365                parents: 0,366                interior: 'Here',367              },368            },369            fun: {370              Fungible: TRANSFER_AMOUNT_RELAY,371            },372          },373        ],374      };375376      const feeAssetItem = 0;377378      await helper.xcm.limitedReserveTransferAssets(bob, destination, beneficiary, assets, feeAssetItem, 'Unlimited');379    });380381    await helper.wait.newBlocks(3);382383    balanceBobAfter = await helper.balance.getSubstrate(bob.address);384    balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});385386    const wndFeeOnQuartz = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;387    const wndDiffOnQuartz = balanceBobRelayTokenAfter - balanceBobRelayTokenBefore;388    console.log(389      '[Relay (Westend) -> Quartz] transaction fees: %s QTZ',390      helper.util.bigIntToDecimals(balanceBobAfter - balanceBobBefore),391    );392    console.log(393      '[Relay (Westend) -> Quartz] transaction fees: %s WND',394      helper.util.bigIntToDecimals(wndFeeOnQuartz, STATEMINE_DECIMALS),395    );396    console.log('[Relay (Westend) -> Quartz] actually delivered: %s WND', wndDiffOnQuartz);397    expect(wndFeeOnQuartz == 0n, 'No incoming WND fees should be taken').to.be.true;398    expect(balanceBobBefore == balanceBobAfter, 'No incoming QTZ fees should be taken').to.be.true;399  });400401  itSub('Should connect and send Relay token back', async ({helper}) => {402    let relayTokenBalanceBefore: bigint;403    let relayTokenBalanceAfter: bigint;404    await usingRelayPlaygrounds(relayUrl, async (helper) => {405      relayTokenBalanceBefore = await helper.balance.getSubstrate(bob.address);406    });407408    const destination = {409      V2: {410        parents: 1,411        interior: {412          X1:{413            AccountId32: {414              network: 'Any',415              id: bob.addressRaw,416            },417          },418        },419      },420    };421422    const currencies: any = [423      [424        {425          NativeAssetId: 'Parent',426        },427        TRANSFER_AMOUNT_RELAY,428      ],429    ];430431    const feeItem = 0;432433    await helper.xTokens.transferMulticurrencies(bob, currencies, feeItem, destination, 'Unlimited');434435    balanceBobFinal = await helper.balance.getSubstrate(bob.address);436    console.log('[Quartz -> Relay (Westend)] transaction fees: %s QTZ',  helper.util.bigIntToDecimals(balanceBobAfter - balanceBobFinal));437438    await usingRelayPlaygrounds(relayUrl, async (helper) => {439      await helper.wait.newBlocks(10);440      relayTokenBalanceAfter = await helper.balance.getSubstrate(bob.address);441442      const diff = relayTokenBalanceAfter - relayTokenBalanceBefore;443      console.log('[Quartz -> Relay (Westend)] actually delivered: %s WND', helper.util.bigIntToDecimals(diff, RELAY_DECIMALS));444      expect(diff > 0, 'Relay tokens was not delivered back').to.be.true;445    });446  });447});448449describeXCM('[XCM] Integration test: Exchanging tokens with Karura', () => {450  let alice: IKeyringPair;451  let randomAccount: IKeyringPair;452453  let balanceQuartzTokenInit: bigint;454  let balanceQuartzTokenMiddle: bigint;455  let balanceQuartzTokenFinal: bigint;456  let balanceKaruraTokenInit: bigint;457  let balanceKaruraTokenMiddle: bigint;458  let balanceKaruraTokenFinal: bigint;459  let balanceQuartzForeignTokenInit: bigint;460  let balanceQuartzForeignTokenMiddle: bigint;461  let balanceQuartzForeignTokenFinal: bigint;462463  // computed by a test transfer from prod Quartz to prod Karura.464  // 2 QTZ sent https://quartz.subscan.io/xcm_message/kusama-f60d821b049f8835a3005ce7102285006f5b61e9465  // 1.919176000000000000 QTZ received (you can check Karura's chain state in the corresponding block)466  const expectedKaruraIncomeFee = 2000000000000000000n - 1919176000000000000n;467468  const KARURA_BACKWARD_TRANSFER_AMOUNT = TRANSFER_AMOUNT - expectedKaruraIncomeFee;469470  before(async () => {471    await usingPlaygrounds(async (helper, privateKey) => {472      alice = await privateKey('//Alice');473      [randomAccount] = await helper.arrange.createAccounts([0n], alice);474475      // Set the default version to wrap the first message to other chains.476      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);477    });478479    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {480      const destination = {481        V1: {482          parents: 1,483          interior: {484            X1: {485              Parachain: QUARTZ_CHAIN,486            },487          },488        },489      };490491      const metadata = {492        name: 'Quartz',493        symbol: 'QTZ',494        decimals: 18,495        minimalBalance: 1000000000000000000n,496      };497498      await helper.getSudo().assetRegistry.registerForeignAsset(alice, destination, metadata);499      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);500      balanceKaruraTokenInit = await helper.balance.getSubstrate(randomAccount.address);501      balanceQuartzForeignTokenInit = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});502    });503504    await usingPlaygrounds(async (helper) => {505      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10n * TRANSFER_AMOUNT);506      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccount.address);507    });508  });509510  itSub('Should connect and send QTZ to Karura', async ({helper}) => {511    const destination = {512      V2: {513        parents: 1,514        interior: {515          X1: {516            Parachain: KARURA_CHAIN,517          },518        },519      },520    };521522    const beneficiary = {523      V2: {524        parents: 0,525        interior: {526          X1: {527            AccountId32: {528              network: 'Any',529              id: randomAccount.addressRaw,530            },531          },532        },533      },534    };535536    const assets = {537      V2: [538        {539          id: {540            Concrete: {541              parents: 0,542              interior: 'Here',543            },544          },545          fun: {546            Fungible: TRANSFER_AMOUNT,547          },548        },549      ],550    };551552    const feeAssetItem = 0;553554    await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');555    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);556557    const qtzFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;558    expect(qtzFees > 0n, 'Negative fees QTZ, looks like nothing was transferred').to.be.true;559    console.log('[Quartz -> Karura] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));560561    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {562      await helper.wait.newBlocks(3);563564      balanceQuartzForeignTokenMiddle = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});565      balanceKaruraTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);566567      const karFees = balanceKaruraTokenInit - balanceKaruraTokenMiddle;568      const qtzIncomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenInit;569      const karUnqFees = TRANSFER_AMOUNT - qtzIncomeTransfer;570571      console.log(572        '[Quartz -> Karura] transaction fees on Karura: %s KAR',573        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),574      );575      console.log(576        '[Quartz -> Karura] transaction fees on Karura: %s QTZ',577        helper.util.bigIntToDecimals(karUnqFees),578      );579      console.log('[Quartz -> Karura] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));580      expect(karFees == 0n).to.be.true;581      expect(582        karUnqFees == expectedKaruraIncomeFee,583        'Karura took different income fee, check the Karura foreign asset config',584      ).to.be.true;585    });586  });587588  itSub('Should connect to Karura and send QTZ back', async ({helper}) => {589    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {590      const destination = {591        V1: {592          parents: 1,593          interior: {594            X2: [595              {Parachain: QUARTZ_CHAIN},596              {597                AccountId32: {598                  network: 'Any',599                  id: randomAccount.addressRaw,600                },601              },602            ],603          },604        },605      };606607      const id = {608        ForeignAsset: 0,609      };610611      await helper.xTokens.transfer(randomAccount, id, KARURA_BACKWARD_TRANSFER_AMOUNT, destination, 'Unlimited');612      balanceKaruraTokenFinal = await helper.balance.getSubstrate(randomAccount.address);613      balanceQuartzForeignTokenFinal = await helper.tokens.accounts(randomAccount.address, id);614615      const karFees = balanceKaruraTokenMiddle - balanceKaruraTokenFinal;616      const qtzOutcomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenFinal;617618      console.log(619        '[Karura -> Quartz] transaction fees on Karura: %s KAR',620        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),621      );622      console.log('[Karura -> Quartz] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));623624      expect(karFees > 0, 'Negative fees KAR, looks like nothing was transferred').to.be.true;625      expect(qtzOutcomeTransfer == KARURA_BACKWARD_TRANSFER_AMOUNT).to.be.true;626    });627628    await helper.wait.newBlocks(3);629630    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccount.address);631    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;632    expect(actuallyDelivered > 0).to.be.true;633634    console.log('[Karura -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));635636    const qtzFees = KARURA_BACKWARD_TRANSFER_AMOUNT - actuallyDelivered;637    console.log('[Karura -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));638    expect(qtzFees == 0n).to.be.true;639  });640});641642// These tests are relevant only when the foreign asset pallet is disabled643describeXCM('[XCM] Integration test: Quartz rejects non-native tokens', () => {644  let alice: IKeyringPair;645646  before(async () => {647    await usingPlaygrounds(async (helper, privateKey) => {648      alice = await privateKey('//Alice');649650      // Set the default version to wrap the first message to other chains.651      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);652    });653  });654655  itSub('Quartz rejects KAR tokens from Karura', async ({helper}) => {656    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {657      const destination = {658        V1: {659          parents: 1,660          interior: {661            X2: [662              {Parachain: QUARTZ_CHAIN},663              {664                AccountId32: {665                  network: 'Any',666                  id: alice.addressRaw,667                },668              },669            ],670          },671        },672      };673674      const id = {675        Token: 'KAR',676      };677678      await helper.xTokens.transfer(alice, id, 100_000_000_000n, destination, 'Unlimited');679    });680681    const maxWaitBlocks = 3;682683    const xcmpQueueFailEvent = await helper.wait.event(maxWaitBlocks, 'xcmpQueue', 'Fail');684685    expect(686      xcmpQueueFailEvent != null,687      '[Karura] xcmpQueue.FailEvent event is expected',688    ).to.be.true;689690    const event = xcmpQueueFailEvent!.event;691    const outcome = event.data[1] as XcmV2TraitsError;692693    expect(694      outcome.isFailedToTransactAsset,695      '[Karura] The XCM error should be `FailedToTransactAsset`',696    ).to.be.true;697  });698});699700describeXCM('[XCM] Integration test: Exchanging QTZ with Moonriver', () => {701  // Quartz constants702  let quartzDonor: IKeyringPair;703  let quartzAssetLocation;704705  let randomAccountQuartz: IKeyringPair;706  let randomAccountMoonriver: IKeyringPair;707708  // Moonriver constants709  let assetId: string;710711  const councilVotingThreshold = 2;712  const technicalCommitteeThreshold = 2;713  const votingPeriod = 3;714  const delayPeriod = 0;715716  const quartzAssetMetadata = {717    name: 'xcQuartz',718    symbol: 'xcQTZ',719    decimals: 18,720    isFrozen: false,721    minimalBalance: 1n,722  };723724  let balanceQuartzTokenInit: bigint;725  let balanceQuartzTokenMiddle: bigint;726  let balanceQuartzTokenFinal: bigint;727  let balanceForeignQtzTokenInit: bigint;728  let balanceForeignQtzTokenMiddle: bigint;729  let balanceForeignQtzTokenFinal: bigint;730  let balanceMovrTokenInit: bigint;731  let balanceMovrTokenMiddle: bigint;732  let balanceMovrTokenFinal: bigint;733734  before(async () => {735    await usingPlaygrounds(async (helper, privateKey) => {736      quartzDonor = await privateKey('//Alice');737      [randomAccountQuartz] = await helper.arrange.createAccounts([0n], quartzDonor);738739      balanceForeignQtzTokenInit = 0n;740      741      // Set the default version to wrap the first message to other chains.742      const alice = quartzDonor;743      await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);744    });745746    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {747      const alithAccount = helper.account.alithAccount();748      const baltatharAccount = helper.account.baltatharAccount();749      const dorothyAccount = helper.account.dorothyAccount();750751      randomAccountMoonriver = helper.account.create();752753      // >>> Sponsoring Dorothy >>>754      console.log('Sponsoring Dorothy.......');755      await helper.balance.transferToEthereum(alithAccount, dorothyAccount.address, 11_000_000_000_000_000_000n);756      console.log('Sponsoring Dorothy.......DONE');757      // <<< Sponsoring Dorothy <<<758759      quartzAssetLocation = {760        XCM: {761          parents: 1,762          interior: {X1: {Parachain: QUARTZ_CHAIN}},763        },764      };765      const existentialDeposit = 1n;766      const isSufficient = true;767      const unitsPerSecond = 1n;768      const numAssetsWeightHint = 0;769770      const encodedProposal = helper.assetManager.makeRegisterForeignAssetProposal({771        location: quartzAssetLocation,772        metadata: quartzAssetMetadata,773        existentialDeposit,774        isSufficient,775        unitsPerSecond,776        numAssetsWeightHint,777      });778      const proposalHash = blake2AsHex(encodedProposal);779780      console.log('Encoded proposal for registerForeignAsset & setAssetUnitsPerSecond is %s', encodedProposal);781      console.log('Encoded length %d', encodedProposal.length);782      console.log('Encoded proposal hash for batch utility after schedule is %s', proposalHash);783784      // >>> Note motion preimage >>>785      console.log('Note motion preimage.......');786      await helper.democracy.notePreimage(baltatharAccount, encodedProposal);787      console.log('Note motion preimage.......DONE');788      // <<< Note motion preimage <<<789790      // >>> Propose external motion through council >>>791      console.log('Propose external motion through council.......');792      const externalMotion = helper.democracy.externalProposeMajority({Legacy: proposalHash});793      const encodedMotion = externalMotion?.method.toHex() || '';794      const motionHash = blake2AsHex(encodedMotion);795      console.log('Motion hash is %s', motionHash);796797      await helper.collective.council.propose(baltatharAccount, councilVotingThreshold, externalMotion, externalMotion.encodedLength);798799      const councilProposalIdx = await helper.collective.council.proposalCount() - 1;800      await helper.collective.council.vote(dorothyAccount, motionHash, councilProposalIdx, true);801      await helper.collective.council.vote(baltatharAccount, motionHash, councilProposalIdx, true);802803      await helper.collective.council.close(804        dorothyAccount,805        motionHash,806        councilProposalIdx,807        {808          refTime: 1_000_000_000,809          proofSize: 1_000_000,810        },811        externalMotion.encodedLength,812      );813      console.log('Propose external motion through council.......DONE');814      // <<< Propose external motion through council <<<815816      // >>> Fast track proposal through technical committee >>>817      console.log('Fast track proposal through technical committee.......');818      const fastTrack = helper.democracy.fastTrack(proposalHash, votingPeriod, delayPeriod);819      const encodedFastTrack = fastTrack?.method.toHex() || '';820      const fastTrackHash = blake2AsHex(encodedFastTrack);821      console.log('FastTrack hash is %s', fastTrackHash);822823      await helper.collective.techCommittee.propose(alithAccount, technicalCommitteeThreshold, fastTrack, fastTrack.encodedLength);824825      const techProposalIdx = await helper.collective.techCommittee.proposalCount() - 1;826      await helper.collective.techCommittee.vote(baltatharAccount, fastTrackHash, techProposalIdx, true);827      await helper.collective.techCommittee.vote(alithAccount, fastTrackHash, techProposalIdx, true);828829      await helper.collective.techCommittee.close(830        baltatharAccount,831        fastTrackHash,832        techProposalIdx,833        {834          refTime: 1_000_000_000,835          proofSize: 1_000_000,836        },837        fastTrack.encodedLength,838      );839      console.log('Fast track proposal through technical committee.......DONE');840      // <<< Fast track proposal through technical committee <<<841842      // >>> Referendum voting >>>843      console.log('Referendum voting.......');844      await helper.democracy.referendumVote(dorothyAccount, 0, {845        balance: 10_000_000_000_000_000_000n,846        vote: {aye: true, conviction: 1},847      });848      console.log('Referendum voting.......DONE');849      // <<< Referendum voting <<<850851      // >>> Acquire Quartz AssetId Info on Moonriver >>>852      console.log('Acquire Quartz AssetId Info on Moonriver.......');853854      // Wait for the democracy execute855      await helper.wait.newBlocks(5);856857      assetId = (await helper.assetManager.assetTypeId(quartzAssetLocation)).toString();858859      console.log('QTZ asset ID is %s', assetId);860      console.log('Acquire Quartz AssetId Info on Moonriver.......DONE');861      // >>> Acquire Quartz AssetId Info on Moonriver >>>862863      // >>> Sponsoring random Account >>>864      console.log('Sponsoring random Account.......');865      await helper.balance.transferToEthereum(baltatharAccount, randomAccountMoonriver.address, 11_000_000_000_000_000_000n);866      console.log('Sponsoring random Account.......DONE');867      // <<< Sponsoring random Account <<<868869      balanceMovrTokenInit = await helper.balance.getEthereum(randomAccountMoonriver.address);870    });871872    await usingPlaygrounds(async (helper) => {873      await helper.balance.transferToSubstrate(quartzDonor, randomAccountQuartz.address, 10n * TRANSFER_AMOUNT);874      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccountQuartz.address);875    });876  });877878  itSub('Should connect and send QTZ to Moonriver', async ({helper}) => {879    const currencyId = {880      NativeAssetId: 'Here',881    };882    const dest = {883      V2: {884        parents: 1,885        interior: {886          X2: [887            {Parachain: MOONRIVER_CHAIN},888            {AccountKey20: {network: 'Any', key: randomAccountMoonriver.address}},889          ],890        },891      },892    };893    const amount = TRANSFER_AMOUNT;894895    await helper.xTokens.transfer(randomAccountQuartz, currencyId, amount, dest, 'Unlimited');896897    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccountQuartz.address);898    expect(balanceQuartzTokenMiddle < balanceQuartzTokenInit).to.be.true;899900    const transactionFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;901    console.log('[Quartz -> Moonriver] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(transactionFees));902    expect(transactionFees > 0, 'Negative fees QTZ, looks like nothing was transferred').to.be.true;903904    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {905      await helper.wait.newBlocks(3);906907      balanceMovrTokenMiddle = await helper.balance.getEthereum(randomAccountMoonriver.address);908909      const movrFees = balanceMovrTokenInit - balanceMovrTokenMiddle;910      console.log('[Quartz -> Moonriver] transaction fees on Moonriver: %s MOVR',helper.util.bigIntToDecimals(movrFees));911      expect(movrFees == 0n).to.be.true;912913      balanceForeignQtzTokenMiddle = (await helper.assets.account(assetId, randomAccountMoonriver.address))!; // BigInt(qtzRandomAccountAsset['balance']);914      const qtzIncomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenInit;915      console.log('[Quartz -> Moonriver] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));916      expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;917    });918  });919920  itSub('Should connect to Moonriver and send QTZ back', async ({helper}) => {921    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {922      const asset = {923        V1: {924          id: {925            Concrete: {926              parents: 1,927              interior: {928                X1: {Parachain: QUARTZ_CHAIN},929              },930            },931          },932          fun: {933            Fungible: TRANSFER_AMOUNT,934          },935        },936      };937      const destination = {938        V1: {939          parents: 1,940          interior: {941            X2: [942              {Parachain: QUARTZ_CHAIN},943              {AccountId32: {network: 'Any', id: randomAccountQuartz.addressRaw}},944            ],945          },946        },947      };948949      await helper.xTokens.transferMultiasset(randomAccountMoonriver, asset, destination, 'Unlimited');950951      balanceMovrTokenFinal = await helper.balance.getEthereum(randomAccountMoonriver.address);952953      const movrFees = balanceMovrTokenMiddle - balanceMovrTokenFinal;954      console.log('[Moonriver -> Quartz] transaction fees on Moonriver: %s MOVR', helper.util.bigIntToDecimals(movrFees));955      expect(movrFees > 0, 'Negative fees MOVR, looks like nothing was transferred').to.be.true;956957      const qtzRandomAccountAsset = await helper.assets.account(assetId, randomAccountMoonriver.address);958959      expect(qtzRandomAccountAsset).to.be.null;960961      balanceForeignQtzTokenFinal = 0n;962963      const qtzOutcomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenFinal;964      console.log('[Quartz -> Moonriver] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));965      expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;966    });967968    await helper.wait.newBlocks(3);969970    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccountQuartz.address);971    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;972    expect(actuallyDelivered > 0).to.be.true;973974    console.log('[Moonriver -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));975976    const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;977    console.log('[Moonriver -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));978    expect(qtzFees == 0n).to.be.true;979  });980});