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

difftreelog

source

tests/src/xcmTransferMoonbeam.test.ts13.9 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 chai from 'chai';18import chaiAsPromised from 'chai-as-promised';1920import {Keyring, WsProvider} from '@polkadot/api';21import {ApiOptions} from '@polkadot/api/types';22import {IKeyringPair} from '@polkadot/types/types';23import usingApi, {submitTransactionAsync} from './substrate/substrate-api';24import {getGenericResult, generateKeyringPair} from './util/helpers';25import {MultiLocation} from '@polkadot/types/interfaces';26import {blake2AsHex} from '@polkadot/util-crypto';27import getBalance from './substrate/get-balance';28import waitNewBlocks from './substrate/wait-new-blocks';2930chai.use(chaiAsPromised);31const expect = chai.expect;3233const UNIQUE_CHAIN = 5000;34const MOONBEAM_CHAIN = 1000;35const UNIQUE_PORT = '9944';36const MOONBEAM_PORT = '9946';37const TRANSFER_AMOUNT = 2000000000000000000000000n;3839describe('Integration test: Exchanging UNQ with Moonbeam', () => {4041  // Unique constants42  let uniqueAlice: IKeyringPair;43  let uniqueAssetLocation;4445  let randomAccountUnique: IKeyringPair;46  let randomAccountMoonbeam: IKeyringPair;4748  // Moonbeam constants49  let assetId: Uint8Array;5051  const moonbeamKeyring = new Keyring({type: 'ethereum'});52  const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';53  const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';54  const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';5556  const alithAccount = moonbeamKeyring.addFromUri(alithPrivateKey, undefined, 'ethereum');57  const baltatharAccount = moonbeamKeyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');58  const dorothyAccount = moonbeamKeyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');5960  const councilVotingThreshold = 2;61  const technicalCommitteeThreshold = 2;62  const votingPeriod = 3;63  const delayPeriod = 0;6465  const uniqueAssetMetadata = {66    name: 'xcUnique',67    symbol: 'xcUNQ',68    decimals: 18,69    isFrozen: false,70    minimalBalance: 1,71  };7273  // let actuallySent1: bigint;74  // let actuallySent2: bigint;7576  // let balanceUnique1: bigint;77  // let balanceUnique2: bigint;78  // let balanceUnique3: bigint;79  80  // let balanceMoonbeamGlmr1: bigint;81  // let balanceMoonbeamGlmr2: bigint;82  // let balanceMoonbeamGlmr3: bigint;8384  let balanceUniqueTokenBefore: bigint;85  let balanceUniqueTokenAfter: bigint;86  let balanceUniqueTokenFinal: bigint;87  let balanceGlmrTokenBefore: bigint;88  let balanceGlmrTokenAfter: bigint;89  let balanceGlmrTokenFinal: bigint;9091  before(async () => {92    await usingApi(async (api, privateKeyWrapper) => {93      uniqueAlice = privateKeyWrapper('//Alice');94      randomAccountUnique = generateKeyringPair();95      randomAccountMoonbeam = generateKeyringPair('ethereum');96    });9798    const moonbeamApiOptions: ApiOptions = {99      provider: new WsProvider('ws://127.0.0.1:' + MOONBEAM_PORT),100    };101102    await usingApi(103      async (api) => {104105        // >>> Sponsoring Dorothy >>>106        const tx0 = api.tx.balances.transfer(dorothyAccount.address, 11_000_000_000_000_000_000n);107        const events0 = await submitTransactionAsync(alithAccount, tx0);108        const result0 = getGenericResult(events0);109        expect(result0.success).to.be.true;110        // <<< Sponsoring Dorothy <<<111112        const sourceLocation: MultiLocation = api.createType(113          'MultiLocation',114          {115            parents: 1,116            interior: {X1: {Parachain: UNIQUE_CHAIN}},117          },118        );119120        assetId = api.registry.hash(sourceLocation.toU8a()).slice(0, 16).reverse();121        console.log('Internal asset ID is %s', assetId);122        uniqueAssetLocation = {XCM: sourceLocation};123        const existentialDeposit = 1;124        const isSufficient = true;125        const unitsPerSecond = '1';126        const numAssetsWeightHint = 0;127128        const registerTx = api.tx.assetManager.registerForeignAsset(129          uniqueAssetLocation,130          uniqueAssetMetadata,131          existentialDeposit,132          isSufficient,133        );134        console.log('Encoded proposal for registerAsset is %s', registerTx.method.toHex() || '');135136        const setUnitsTx = api.tx.assetManager.setAssetUnitsPerSecond(137          uniqueAssetLocation,138          unitsPerSecond,139          numAssetsWeightHint,140        );141        console.log('Encoded proposal for setAssetUnitsPerSecond is %s', setUnitsTx.method.toHex() || '');142143        const batchCall = api.tx.utility.batchAll([registerTx, setUnitsTx]);144        console.log('Encoded proposal for batchCall is %s', batchCall.method.toHex() || '');145146        // >>> Note motion preimage >>>147        const encodedProposal = batchCall?.method.toHex() || '';148        const proposalHash = blake2AsHex(encodedProposal);149        console.log('Encoded proposal for batch utility after schedule is %s', encodedProposal);150        console.log('Encoded proposal hash for batch utility after schedule is %s', proposalHash);151        console.log('Encoded length %d', encodedProposal.length);152153        const tx1 = api.tx.democracy.notePreimage(encodedProposal);154        const events1 = await submitTransactionAsync(baltatharAccount, tx1);155        const result1 = getGenericResult(events1);156        expect(result1.success).to.be.true;157        // <<< Note motion preimage <<<158159        // >>> Propose external motion through council >>>160        const externalMotion = api.tx.democracy.externalProposeMajority(proposalHash);161        const tx2 = api.tx.councilCollective.propose(162          councilVotingThreshold,163          externalMotion,164          externalMotion.encodedLength,165        );166        const events2 = await submitTransactionAsync(baltatharAccount, tx2);167        const result2 = getGenericResult(events2);168        expect(result2.success).to.be.true;169170        const encodedMotion = externalMotion?.method.toHex() || '';171        const motionHash = blake2AsHex(encodedMotion);172        console.log('Motion hash is %s', motionHash);173174        const tx3 = api.tx.councilCollective.vote(motionHash, 0, true);175        {176          const events3 = await submitTransactionAsync(dorothyAccount, tx3);177          const result3 = getGenericResult(events3);178          expect(result3.success).to.be.true;179        }180        {181          const events3 = await submitTransactionAsync(baltatharAccount, tx3);182          const result3 = getGenericResult(events3);183          expect(result3.success).to.be.true;184        }185186        const tx4 = api.tx.councilCollective.close(motionHash, 0, 1_000_000_000, externalMotion.encodedLength);187        const events4 = await submitTransactionAsync(dorothyAccount, tx4);188        const result4 = getGenericResult(events4);189        expect(result4.success).to.be.true;190        // <<< Propose external motion through council <<<191192        // >>> Fast track proposal through technical committee >>>193        const fastTrack = api.tx.democracy.fastTrack(proposalHash, votingPeriod, delayPeriod);194        const tx5 = api.tx.techCommitteeCollective.propose(195          technicalCommitteeThreshold,196          fastTrack,197          fastTrack.encodedLength,198        );199        const events5 = await submitTransactionAsync(alithAccount, tx5);200        const result5 = getGenericResult(events5);201        expect(result5.success).to.be.true;202203        const encodedFastTrack = fastTrack?.method.toHex() || '';204        const fastTrackHash = blake2AsHex(encodedFastTrack);205        console.log('FastTrack hash is %s', fastTrackHash);206207        const proposalIdx = Number(await api.query.techCommitteeCollective.proposalCount()) - 1;208        const tx6 = api.tx.techCommitteeCollective.vote(fastTrackHash, proposalIdx, true);209        {210          const events6 = await submitTransactionAsync(baltatharAccount, tx6);211          const result6 = getGenericResult(events6);212          expect(result6.success).to.be.true;213        }214        {215          const events6 = await submitTransactionAsync(alithAccount, tx6);216          const result6 = getGenericResult(events6);217          expect(result6.success).to.be.true;218        }219220        const tx7 = api.tx.techCommitteeCollective221          .close(fastTrackHash, proposalIdx, 1_000_000_000, fastTrack.encodedLength);222        const events7 = await submitTransactionAsync(baltatharAccount, tx7);223        const result7 = getGenericResult(events7);224        expect(result7.success).to.be.true;225        // <<< Fast track proposal through technical committee <<<226227        // >>> Referendum voting >>>228        const tx8 = api.tx.democracy.vote(229          0,230          {Standard: {balance: 10_000_000_000_000_000_000n, vote: {aye: true, conviction: 1}}},231        );232        const events8 = await submitTransactionAsync(dorothyAccount, tx8);233        const result8 = getGenericResult(events8);234        expect(result8.success).to.be.true;235        // <<< Referendum voting <<<236237        // >>> Sponsoring random Account >>>238        const tx9 = api.tx.balances.transfer(randomAccountMoonbeam.address, 11_000_000_000_000_000_000n);239        const events9 = await submitTransactionAsync(baltatharAccount, tx9);240        const result9 = getGenericResult(events9);241        expect(result9.success).to.be.true;242        // <<< Sponsoring random Account <<<243244        [balanceGlmrTokenBefore] = await getBalance(api, [randomAccountMoonbeam.address]);245      },246      moonbeamApiOptions,247    );248249    await usingApi(async (api) => {250      const tx0 = api.tx.balances.transfer(randomAccountUnique.address, 10n * TRANSFER_AMOUNT);251      const events0 = await submitTransactionAsync(uniqueAlice, tx0);252      const result0 = getGenericResult(events0);253      expect(result0.success).to.be.true;254255      [balanceUniqueTokenBefore] = await getBalance(api, [randomAccountUnique.address]);256    });257  });258259  it('Should connect and send UNQ to Moonbeam', async () => {260    await usingApi(async (api) => {261      const currencyId = {262        NativeAssetId: 'Here',263      };264      const dest = {265        V1: {266          parents: 1,267          interior: {268            X2: [269              {Parachain: MOONBEAM_CHAIN},270              {AccountKey20: {network: 'Any', key: randomAccountMoonbeam.address}},271            ],272          },273        },274      };275      const amount = TRANSFER_AMOUNT;276      const destWeight = 50000000;277278      const tx = api.tx.xTokens.transfer(currencyId, amount, dest, destWeight);279      const events = await submitTransactionAsync(uniqueAlice, tx);280      const result = getGenericResult(events);281      expect(result.success).to.be.true;282283      [balanceUniqueTokenAfter] = await getBalance(api, [randomAccountUnique.address]);284      expect(balanceUniqueTokenAfter < balanceUniqueTokenBefore).to.be.true;285286      const transactionFees = balanceUniqueTokenBefore - balanceUniqueTokenAfter - TRANSFER_AMOUNT;287      console.log('Unique to Moonbeam transaction fees on Unique: %s UNQ', transactionFees);288      expect(transactionFees > 0).to.be.true;289    });290291    await usingApi(292      async (api) => {293        // todo do something about instant sealing, where there might not be any new blocks294        await waitNewBlocks(api, 3);295296        [balanceGlmrTokenAfter] = await getBalance(api, [randomAccountMoonbeam.address]);297298        const glmrFees = balanceGlmrTokenBefore - balanceGlmrTokenAfter;299        console.log('Unique to Moonbeam transaction fees on Moonbeam: %s GLMR', glmrFees);300        expect(glmrFees == 0n).to.be.true;301      },302      {provider: new WsProvider('ws://127.0.0.1:' + MOONBEAM_PORT)},303    );304  });305306  it('Should connect to Moonbeam and send UNQ back', async () => {307    await usingApi(308      async (api) => {309        const amount = TRANSFER_AMOUNT / 2n;310        const asset = {311          V1: {312            id: {313              Concrete: {314                parents: 1,315                interior: {316                  X1: {Parachain: UNIQUE_CHAIN},317                },318              },319            },320            fun: {321              Fungible: amount,322            },323          },324        };325        const destination = {326          V1: {327            parents: 1,328            interior: {329              X2: [330                {Parachain: UNIQUE_CHAIN},331                {AccountId32: {network: 'Any', id: randomAccountUnique.addressRaw}},332              ],333            },334          },335        };336        const destWeight = 50000000;337338        const tx = api.tx.xTokens.transferMultiasset(asset, destination, destWeight);339        const events = await submitTransactionAsync(randomAccountMoonbeam, tx);340        const result = getGenericResult(events);341        expect(result.success).to.be.true;342343        [balanceGlmrTokenFinal] = await getBalance(api, [randomAccountMoonbeam.address]);344345        const glmrFees = balanceGlmrTokenAfter - balanceGlmrTokenFinal;346        console.log('Moonbeam to Unique transaction fees on Moonbeam: %s GLMR', glmrFees);347        expect(glmrFees > 0).to.be.true;348      },349      {provider: new WsProvider('ws://127.0.0.1:' + MOONBEAM_PORT)},350    );351352    await usingApi(async (api) => {353      // todo do something about instant sealing, where there might not be any new blocks354      await waitNewBlocks(api, 3);355356      [balanceUniqueTokenFinal] = await getBalance(api, [randomAccountUnique.address]);357      const actuallyDelivered = balanceUniqueTokenFinal - balanceUniqueTokenAfter;358      expect(actuallyDelivered > 0).to.be.true;359360      const unqFees = TRANSFER_AMOUNT - actuallyDelivered;361      console.log('Moonbeam to Unique transaction fees on Unique: %s UNQ', unqFees);362      expect(unqFees > 0).to.be.true;363    });364  });365});