difftreelog
test(xcm qtz) added `XcmTestHelper`
in: master
5 files changed
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -116,6 +116,8 @@
"testXcmUnique": "RUN_XCM_TESTS=1 yarn _test ./**/xcm/xcmUnique.test.ts",
"testFullXcmUnique": "RUN_XCM_TESTS=1 yarn _test ./**/xcm/*Unique.test.ts",
"testXcmQuartz": "RUN_XCM_TESTS=1 yarn _test ./**/xcm/xcmQuartz.test.ts",
+ "testLowLevelXcmQuartz": "RUN_XCM_TESTS=1 yarn _test ./**/xcm/lowLevelXcmQuartz.test.ts",
+ "testFullXcmQuartz": "RUN_XCM_TESTS=1 yarn _test ./**/xcm/*Quartz.test.ts",
"testXcmOpal": "RUN_XCM_TESTS=1 yarn _test ./**/xcm/xcmOpal.test.ts",
"testXcmTransferAcala": "yarn _test ./**/xcm/xcmTransferAcala.test.ts acalaId=2000 uniqueId=5000",
"testXcmTransferStatemine": "yarn _test ./**/xcm/xcmTransferStatemine.test.ts statemineId=1000 uniqueId=5000",
tests/src/xcm/lowLevelXcmQuartz.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/xcm/lowLevelXcmQuartz.test.ts
@@ -0,0 +1,381 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {itSub, expect, describeXCM, usingPlaygrounds, usingKaruraPlaygrounds, usingMoonriverPlaygrounds, usingShidenPlaygrounds} from '../util';
+import {DevUniqueHelper, Event} from '../util/playgrounds/unique.dev';
+import {STATEMINE_CHAIN, QUARTZ_CHAIN, KARURA_CHAIN, MOONRIVER_CHAIN, SHIDEN_CHAIN, STATEMINE_DECIMALS, KARURA_DECIMALS, QTZ_DECIMALS, RELAY_DECIMALS, SHIDEN_DECIMALS, karuraUrl, moonriverUrl, relayUrl, shidenUrl, statemineUrl, SAFE_XCM_VERSION, XcmTestHelper, TRANSFER_AMOUNT} from './xcm.types';
+
+
+const testHelper = new XcmTestHelper('quartz');
+
+describeXCM('[XCMLL] Integration test: Exchanging tokens with Karura', () => {
+ let alice: IKeyringPair;
+ let randomAccount: IKeyringPair;
+
+ let balanceQuartzTokenInit: bigint;
+ let balanceQuartzTokenMiddle: bigint;
+ let balanceQuartzTokenFinal: bigint;
+ let balanceKaruraTokenInit: bigint;
+ let balanceKaruraTokenMiddle: bigint;
+ let balanceKaruraTokenFinal: bigint;
+ let balanceQuartzForeignTokenInit: bigint;
+ let balanceQuartzForeignTokenMiddle: bigint;
+ let balanceQuartzForeignTokenFinal: bigint;
+
+ // computed by a test transfer from prod Quartz to prod Karura.
+ // 2 QTZ sent https://quartz.subscan.io/xcm_message/kusama-f60d821b049f8835a3005ce7102285006f5b61e9
+ // 1.919176000000000000 QTZ received (you can check Karura's chain state in the corresponding block)
+ const expectedKaruraIncomeFee = 2000000000000000000n - 1919176000000000000n;
+ const karuraEps = 8n * 10n ** 16n;
+
+ let karuraBackwardTransferAmount: bigint;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ alice = await privateKey('//Alice');
+ [randomAccount] = await helper.arrange.createAccounts([0n], alice);
+
+ // Set the default version to wrap the first message to other chains.
+ await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);
+ });
+
+ await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
+ const destination = {
+ V2: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: QUARTZ_CHAIN,
+ },
+ },
+ },
+ };
+
+ const metadata = {
+ name: 'Quartz',
+ symbol: 'QTZ',
+ decimals: 18,
+ minimalBalance: 1000000000000000000n,
+ };
+
+ await helper.getSudo().assetRegistry.registerForeignAsset(alice, destination, metadata);
+ await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);
+ balanceKaruraTokenInit = await helper.balance.getSubstrate(randomAccount.address);
+ balanceQuartzForeignTokenInit = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});
+ });
+
+ await usingPlaygrounds(async (helper) => {
+ await helper.balance.transferToSubstrate(alice, randomAccount.address, 10n * TRANSFER_AMOUNT);
+ balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccount.address);
+ });
+ });
+
+ itSub('Should connect and send QTZ to Karura', async () => {
+ await testHelper.sendUnqTo('karura', randomAccount);
+ });
+
+ itSub('Should connect to Karura and send QTZ back', async () => {
+ await testHelper.sendUnqBack('karura', alice, randomAccount);
+ });
+
+ itSub('Karura can send only up to its balance', async () => {
+ await testHelper.sendOnlyOwnedBalance('karura', alice);
+ });
+});
+// These tests are relevant only when
+// the the corresponding foreign assets are not registered
+describeXCM('[XCMLL] Integration test: Quartz rejects non-native tokens', () => {
+ let alice: IKeyringPair;
+ let alith: IKeyringPair;
+
+ const testAmount = 100_000_000_000n;
+ let quartzParachainJunction;
+ let quartzAccountJunction;
+
+ let quartzParachainMultilocation: any;
+ let quartzAccountMultilocation: any;
+ let quartzCombinedMultilocation: any;
+
+ let messageSent: any;
+
+ const maxWaitBlocks = 3;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ alice = await privateKey('//Alice');
+
+ quartzParachainJunction = {Parachain: QUARTZ_CHAIN};
+ quartzAccountJunction = {
+ AccountId32: {
+ network: 'Any',
+ id: alice.addressRaw,
+ },
+ };
+
+ quartzParachainMultilocation = {
+ V2: {
+ parents: 1,
+ interior: {
+ X1: quartzParachainJunction,
+ },
+ },
+ };
+
+ quartzAccountMultilocation = {
+ V2: {
+ parents: 0,
+ interior: {
+ X1: quartzAccountJunction,
+ },
+ },
+ };
+
+ quartzCombinedMultilocation = {
+ V2: {
+ parents: 1,
+ interior: {
+ X2: [quartzParachainJunction, quartzAccountJunction],
+ },
+ },
+ };
+
+ // Set the default version to wrap the first message to other chains.
+ await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);
+ });
+
+ // eslint-disable-next-line require-await
+ await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {
+ alith = helper.account.alithAccount();
+ });
+ });
+
+ itSub('Quartz rejects KAR tokens from Karura', async () => {
+ await testHelper.rejectNativeTokensFrom('karura', alice);
+ });
+
+ itSub('Quartz rejects MOVR tokens from Moonriver', async () => {
+ await testHelper.rejectNativeTokensFrom('moonriver', alice);
+ });
+
+ itSub('Quartz rejects SDN tokens from Shiden', async () => {
+ await testHelper.rejectNativeTokensFrom('shiden', alice);
+ });
+});
+
+describeXCM('[XCMLL] Integration test: Exchanging QTZ with Moonriver', () => {
+ // Quartz constants
+ let alice: IKeyringPair;
+ let quartzAssetLocation;
+
+ let randomAccountQuartz: IKeyringPair;
+ let randomAccountMoonriver: IKeyringPair;
+
+ // Moonriver constants
+ let assetId: string;
+
+ const quartzAssetMetadata = {
+ name: 'xcQuartz',
+ symbol: 'xcQTZ',
+ decimals: 18,
+ isFrozen: false,
+ minimalBalance: 1n,
+ };
+
+ let balanceQuartzTokenInit: bigint;
+ let balanceQuartzTokenMiddle: bigint;
+ let balanceQuartzTokenFinal: bigint;
+ let balanceForeignQtzTokenInit: bigint;
+ let balanceForeignQtzTokenMiddle: bigint;
+ let balanceForeignQtzTokenFinal: bigint;
+ let balanceMovrTokenInit: bigint;
+ let balanceMovrTokenMiddle: bigint;
+ let balanceMovrTokenFinal: bigint;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ alice = await privateKey('//Alice');
+ [randomAccountQuartz] = await helper.arrange.createAccounts([0n], alice);
+
+ balanceForeignQtzTokenInit = 0n;
+
+ // Set the default version to wrap the first message to other chains.
+ await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);
+ });
+
+ await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {
+ const alithAccount = helper.account.alithAccount();
+ const baltatharAccount = helper.account.baltatharAccount();
+ const dorothyAccount = helper.account.dorothyAccount();
+
+ randomAccountMoonriver = helper.account.create();
+
+ // >>> Sponsoring Dorothy >>>
+ console.log('Sponsoring Dorothy.......');
+ await helper.balance.transferToEthereum(alithAccount, dorothyAccount.address, 11_000_000_000_000_000_000n);
+ console.log('Sponsoring Dorothy.......DONE');
+ // <<< Sponsoring Dorothy <<<
+
+ quartzAssetLocation = {
+ XCM: {
+ parents: 1,
+ interior: {X1: {Parachain: QUARTZ_CHAIN}},
+ },
+ };
+ const existentialDeposit = 1n;
+ const isSufficient = true;
+ const unitsPerSecond = 1n;
+ const numAssetsWeightHint = 0;
+
+ const encodedProposal = helper.assetManager.makeRegisterForeignAssetProposal({
+ location: quartzAssetLocation,
+ metadata: quartzAssetMetadata,
+ existentialDeposit,
+ isSufficient,
+ unitsPerSecond,
+ numAssetsWeightHint,
+ });
+
+ console.log('Encoded proposal for registerForeignAsset & setAssetUnitsPerSecond is %s', encodedProposal);
+
+ await helper.fastDemocracy.executeProposal('register QTZ foreign asset', encodedProposal);
+
+ // >>> Acquire Quartz AssetId Info on Moonriver >>>
+ console.log('Acquire Quartz AssetId Info on Moonriver.......');
+
+ assetId = (await helper.assetManager.assetTypeId(quartzAssetLocation)).toString();
+
+ console.log('QTZ asset ID is %s', assetId);
+ console.log('Acquire Quartz AssetId Info on Moonriver.......DONE');
+ // >>> Acquire Quartz AssetId Info on Moonriver >>>
+
+ // >>> Sponsoring random Account >>>
+ console.log('Sponsoring random Account.......');
+ await helper.balance.transferToEthereum(baltatharAccount, randomAccountMoonriver.address, 11_000_000_000_000_000_000n);
+ console.log('Sponsoring random Account.......DONE');
+ // <<< Sponsoring random Account <<<
+
+ balanceMovrTokenInit = await helper.balance.getEthereum(randomAccountMoonriver.address);
+ });
+
+ await usingPlaygrounds(async (helper) => {
+ await helper.balance.transferToSubstrate(alice, randomAccountQuartz.address, 10n * TRANSFER_AMOUNT);
+ balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccountQuartz.address);
+ });
+ });
+
+ itSub('Should connect and send QTZ to Moonriver', async () => {
+ await testHelper.sendUnqTo('moonriver', randomAccountQuartz, randomAccountMoonriver);
+ });
+
+ itSub('Should connect to Moonriver and send QTZ back', async () => {
+ await testHelper.sendUnqBack('moonriver', alice, randomAccountQuartz);
+ });
+
+ itSub('Moonriver can send only up to its balance', async () => {
+ await testHelper.sendOnlyOwnedBalance('moonriver', alice);
+ });
+
+ itSub('Should not accept reserve transfer of QTZ from Moonriver', async () => {
+ await testHelper.reserveTransferUNQfrom('moonriver', alice);
+ });
+});
+
+describeXCM('[XCMLL] Integration test: Exchanging tokens with Shiden', () => {
+ let alice: IKeyringPair;
+ let sender: IKeyringPair;
+
+ const QTZ_ASSET_ID_ON_SHIDEN = 1;
+ const QTZ_MINIMAL_BALANCE_ON_SHIDEN = 1n;
+
+ // Quartz -> Shiden
+ const shidenInitialBalance = 1n * (10n ** SHIDEN_DECIMALS); // 1 SHD, existential deposit required to actually create the account on Shiden
+ const unitsPerSecond = 228_000_000_000n; // This is Phala's value. What will be ours?
+ const qtzToShidenTransferred = 10n * (10n ** QTZ_DECIMALS); // 10 QTZ
+ const qtzToShidenArrived = 9_999_999_999_088_000_000n; // 9.999 ... QTZ, Shiden takes a commision in foreign tokens
+
+ // Shiden -> Quartz
+ const qtzFromShidenTransfered = 5n * (10n ** QTZ_DECIMALS); // 5 QTZ
+ const qtzOnShidenLeft = qtzToShidenArrived - qtzFromShidenTransfered; // 4.999_999_999_088_000_000n QTZ
+
+ let balanceAfterQuartzToShidenXCM: bigint;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ alice = await privateKey('//Alice');
+ [sender] = await helper.arrange.createAccounts([100n], alice);
+ console.log('sender', sender.address);
+
+ // Set the default version to wrap the first message to other chains.
+ await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);
+ });
+
+ await usingShidenPlaygrounds(shidenUrl, async (helper) => {
+ console.log('1. Create foreign asset and metadata');
+ // TODO update metadata with values from production
+ await helper.assets.create(
+ alice,
+ QTZ_ASSET_ID_ON_SHIDEN,
+ alice.address,
+ QTZ_MINIMAL_BALANCE_ON_SHIDEN,
+ );
+
+ await helper.assets.setMetadata(
+ alice,
+ QTZ_ASSET_ID_ON_SHIDEN,
+ 'Cross chain QTZ',
+ 'xcQTZ',
+ Number(QTZ_DECIMALS),
+ );
+
+ console.log('2. Register asset location on Shiden');
+ const assetLocation = {
+ V2: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: QUARTZ_CHAIN,
+ },
+ },
+ },
+ };
+
+ await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.registerAssetLocation', [assetLocation, QTZ_ASSET_ID_ON_SHIDEN]);
+
+ console.log('3. Set QTZ payment for XCM execution on Shiden');
+ await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.setAssetUnitsPerSecond', [assetLocation, unitsPerSecond]);
+
+ console.log('4. Transfer 1 SDN to recipient to create the account (needed due to existential balance)');
+ await helper.balance.transferToSubstrate(alice, sender.address, shidenInitialBalance);
+ });
+ });
+
+ itSub('Should connect and send QTZ to Shiden', async () => {
+ await testHelper.sendUnqTo('shiden', sender);
+ });
+
+ itSub('Should connect to Shiden and send QTZ back', async () => {
+ await testHelper.sendUnqBack('shiden', alice, sender);
+ });
+
+ itSub('Shiden can send only up to its balance', async () => {
+ await testHelper.sendOnlyOwnedBalance('shiden', alice);
+ });
+
+ itSub('Should not accept reserve transfer of QTZ from Shiden', async () => {
+ await testHelper.reserveTransferUNQfrom('shiden', alice);
+ });
+});
tests/src/xcm/lowLevelXcmUnique.test.tsdiffbeforeafterboth1// 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, usingAcalaPlaygrounds, usingMoonbeamPlaygrounds, usingAstarPlaygrounds, usingPolkadexPlaygrounds} from '../util';20import {Event} from '../util/playgrounds/unique.dev';21import {nToBigInt} from '@polkadot/util';22import {hexToString} from '@polkadot/util';23import {ASTAR_DECIMALS, NETWORKS, SAFE_XCM_VERSION, UNIQUE_CHAIN, UNQ_DECIMALS, acalaUrl, astarUrl, expectFailedToTransact, expectUntrustedReserveLocationFail, getDevPlayground, mapToChainId, mapToChainUrl, maxWaitBlocks, moonbeamUrl, polkadexUrl, uniqueAssetId, uniqueVersionedMultilocation} from './xcm.types';242526const TRANSFER_AMOUNT = 2000000_000_000_000_000_000_000n;27const SENDER_BUDGET = 2n * TRANSFER_AMOUNT;28const SENDBACK_AMOUNT = TRANSFER_AMOUNT / 2n;29const STAYED_ON_TARGET_CHAIN = TRANSFER_AMOUNT - SENDBACK_AMOUNT;30const TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT = 100_000_000_000n;3132let balanceUniqueTokenInit: bigint;33let balanceUniqueTokenMiddle: bigint;34let balanceUniqueTokenFinal: bigint;35let unqFees: bigint;363738async function genericSendUnqTo(39 networkName: keyof typeof NETWORKS,40 randomAccount: IKeyringPair,41 randomAccountOnTargetChain = randomAccount,42) {43 const networkUrl = mapToChainUrl(networkName);44 const targetPlayground = getDevPlayground(networkName);45 await usingPlaygrounds(async (helper) => {46 balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);47 const destination = {48 V2: {49 parents: 1,50 interior: {51 X1: {52 Parachain: mapToChainId(networkName),53 },54 },55 },56 };5758 const beneficiary = {59 V2: {60 parents: 0,61 interior: {62 X1: (63 networkName == 'moonbeam' ?64 {65 AccountKey20: {66 network: 'Any',67 key: randomAccountOnTargetChain.address,68 },69 }70 :71 {72 AccountId32: {73 network: 'Any',74 id: randomAccountOnTargetChain.addressRaw,75 },76 }77 ),78 },79 },80 };8182 const assets = {83 V2: [84 {85 id: {86 Concrete: {87 parents: 0,88 interior: 'Here',89 },90 },91 fun: {92 Fungible: TRANSFER_AMOUNT,93 },94 },95 ],96 };97 const feeAssetItem = 0;9899 await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');100 const messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);101 balanceUniqueTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);102103 unqFees = balanceUniqueTokenInit - balanceUniqueTokenMiddle - TRANSFER_AMOUNT;104 console.log('[Unique -> %s] transaction fees on Unique: %s UNQ', networkName, helper.util.bigIntToDecimals(unqFees));105 expect(unqFees > 0n, 'Negative fees UNQ, looks like nothing was transferred').to.be.true;106107 await targetPlayground(networkUrl, async (helper) => {108 /*109 Since only the parachain part of the Polkadex110 infrastructure is launched (without their111 solochain validators), processing incoming112 assets will lead to an error.113 This error indicates that the Polkadex chain114 received a message from the Unique network,115 since the hash is being checked to ensure116 it matches what was sent.117 */118 if(networkName == 'polkadex') {119 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash);120 } else {121 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == messageSent.messageHash);122 }123 });124125 });126}127128async function genericSendUnqBack(129 networkName: keyof typeof NETWORKS,130 sudoer: IKeyringPair,131 randomAccountOnUnq: IKeyringPair,132) {133 const networkUrl = mapToChainUrl(networkName);134135 const targetPlayground = getDevPlayground(networkName);136 await usingPlaygrounds(async (helper) => {137138 const xcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(139 randomAccountOnUnq.addressRaw,140 uniqueAssetId,141 SENDBACK_AMOUNT,142 );143144 let xcmProgramSent: any;145146147 await targetPlayground(networkUrl, async (helper) => {148 if('getSudo' in helper) {149 await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, xcmProgram);150 xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);151 } else if('fastDemocracy' in helper) {152 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, xcmProgram]);153 // Needed to bypass the call filter.154 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);155 await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);156 xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);157 }158 });159160 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == xcmProgramSent.messageHash);161162 balanceUniqueTokenFinal = await helper.balance.getSubstrate(randomAccountOnUnq.address);163164 expect(balanceUniqueTokenFinal).to.be.equal(balanceUniqueTokenInit - unqFees - STAYED_ON_TARGET_CHAIN);165166 });167}168169async function genericSendOnlyOwnedBalance(170 networkName: keyof typeof NETWORKS,171 sudoer: IKeyringPair,172) {173 const networkUrl = mapToChainUrl(networkName);174 const targetPlayground = getDevPlayground(networkName);175176 const targetChainBalance = 10000n * (10n ** UNQ_DECIMALS);177178 await usingPlaygrounds(async (helper) => {179 const targetChainSovereignAccount = helper.address.paraSiblingSovereignAccount(mapToChainId(networkName));180 await helper.getSudo().balance.setBalanceSubstrate(sudoer, targetChainSovereignAccount, targetChainBalance);181 const moreThanTargetChainHas = 2n * targetChainBalance;182183 const targetAccount = helper.arrange.createEmptyAccount();184185 const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(186 targetAccount.addressRaw,187 {188 Concrete: {189 parents: 0,190 interior: 'Here',191 },192 },193 moreThanTargetChainHas,194 );195196 let maliciousXcmProgramSent: any;197198199 await targetPlayground(networkUrl, async (helper) => {200 if('getSudo' in helper) {201 await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgram);202 maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);203 } else if('fastDemocracy' in helper) {204 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgram]);205 // Needed to bypass the call filter.206 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);207 await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);208 maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);209 }210 });211212 await expectFailedToTransact(helper, maliciousXcmProgramSent);213214 const targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);215 expect(targetAccountBalance).to.be.equal(0n);216 });217}218219async function genericReserveTransferUNQfrom(netwokrName: keyof typeof NETWORKS, sudoer: IKeyringPair) {220 const networkUrl = mapToChainUrl(netwokrName);221 const targetPlayground = getDevPlayground(netwokrName);222223 await usingPlaygrounds(async (helper) => {224 const testAmount = 10_000n * (10n ** UNQ_DECIMALS);225 const targetAccount = helper.arrange.createEmptyAccount();226227 const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(228 targetAccount.addressRaw,229 uniqueAssetId,230 testAmount,231 );232233 const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(234 targetAccount.addressRaw,235 {236 Concrete: {237 parents: 0,238 interior: 'Here',239 },240 },241 testAmount,242 );243244 let maliciousXcmProgramFullIdSent: any;245 let maliciousXcmProgramHereIdSent: any;246 const maxWaitBlocks = 3;247248 // Try to trick Unique using full UNQ identification249 await targetPlayground(networkUrl, async (helper) => {250 if('getSudo' in helper) {251 await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgramFullId);252 maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);253 }254 // Moonbeam case255 else if('fastDemocracy' in helper) {256 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramFullId]);257 // Needed to bypass the call filter.258 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);259 await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using path asset identification`,batchCall);260261 maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);262 }263 });264265266 await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramFullIdSent);267268 let accountBalance = await helper.balance.getSubstrate(targetAccount.address);269 expect(accountBalance).to.be.equal(0n);270271 // Try to trick Unique using shortened UNQ identification272 await targetPlayground(networkUrl, async (helper) => {273 if('getSudo' in helper) {274 await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgramHereId);275 maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);276 }277 else if('fastDemocracy' in helper) {278 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramHereId]);279 // Needed to bypass the call filter.280 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);281 await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using "here" asset identification`, batchCall);282283 maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);284 }285 });286287 await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramHereIdSent);288289 accountBalance = await helper.balance.getSubstrate(targetAccount.address);290 expect(accountBalance).to.be.equal(0n);291 });292}293294async function genericRejectNativeTokensFrom(networkName: keyof typeof NETWORKS, sudoerOnTargetChain: IKeyringPair) {295 const networkUrl = mapToChainUrl(networkName);296 const targetPlayground = getDevPlayground(networkName);297 let messageSent: any;298299 await usingPlaygrounds(async (helper) => {300 const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(301 helper.arrange.createEmptyAccount().addressRaw,302 {303 Concrete: {304 parents: 1,305 interior: {306 X1: {307 Parachain: mapToChainId(networkName),308 },309 },310 },311 },312 TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT,313 );314 await targetPlayground(networkUrl, async (helper) => {315 if('getSudo' in helper) {316 await helper.getSudo().xcm.send(sudoerOnTargetChain, uniqueVersionedMultilocation, maliciousXcmProgramFullId);317 messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);318 } else if('fastDemocracy' in helper) {319 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramFullId]);320 // Needed to bypass the call filter.321 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);322 await helper.fastDemocracy.executeProposal(`${networkName} sending native tokens to the Unique via fast democracy`, batchCall);323324 messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);325 }326 });327 await expectFailedToTransact(helper, messageSent);328 });329}330331332describeXCM('[XCMLL] Integration test: Exchanging tokens with Acala', () => {333 let alice: IKeyringPair;334 let randomAccount: IKeyringPair;335336 before(async () => {337 await usingPlaygrounds(async (helper, privateKey) => {338 alice = await privateKey('//Alice');339 console.log(config.acalaUrl);340 randomAccount = helper.arrange.createEmptyAccount();341342 // Set the default version to wrap the first message to other chains.343 await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);344 });345346 await usingAcalaPlaygrounds(acalaUrl, async (helper) => {347 const destination = {348 V2: {349 parents: 1,350 interior: {351 X1: {352 Parachain: UNIQUE_CHAIN,353 },354 },355 },356 };357358 const metadata = {359 name: 'Unique Network',360 symbol: 'UNQ',361 decimals: 18,362 minimalBalance: 1250_000_000_000_000_000n,363 };364 const assets = (await (helper.callRpc('api.query.assetRegistry.assetMetadatas.entries'))).map(([_k, v] : [any, any]) =>365 hexToString(v.toJSON()['symbol'])) as string[];366367 if(!assets.includes('UNQ')) {368 await helper.getSudo().assetRegistry.registerForeignAsset(alice, destination, metadata);369 } else {370 console.log('UNQ token already registered on Acala assetRegistry pallet');371 }372 await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);373 });374375 await usingPlaygrounds(async (helper) => {376 await helper.balance.transferToSubstrate(alice, randomAccount.address, SENDER_BUDGET);377 balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);378 });379 });380381 itSub('Should connect and send UNQ to Acala', async () => {382 await genericSendUnqTo('acala', randomAccount);383 });384385 itSub('Should connect to Acala and send UNQ back', async () => {386 await genericSendUnqBack('acala', alice, randomAccount);387 });388389 itSub('Acala can send only up to its balance', async () => {390 await genericSendOnlyOwnedBalance('acala', alice);391 });392393 itSub('Should not accept reserve transfer of UNQ from Acala', async () => {394 await genericReserveTransferUNQfrom('acala', alice);395 });396});397398describeXCM('[XCMLL] Integration test: Exchanging tokens with Polkadex', () => {399 let alice: IKeyringPair;400 let randomAccount: IKeyringPair;401402 before(async () => {403 await usingPlaygrounds(async (helper, privateKey) => {404 alice = await privateKey('//Alice');405 randomAccount = helper.arrange.createEmptyAccount();406407 // Set the default version to wrap the first message to other chains.408 await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);409 });410411 await usingPolkadexPlaygrounds(polkadexUrl, async (helper) => {412 const isWhitelisted = ((await helper.callRpc('api.query.xcmHelper.whitelistedTokens', []))413 .toJSON() as [])414 .map(nToBigInt).length != 0;415 /*416 Check whether the Unique token has been added417 to the whitelist, since an error will occur418 if it is added again. Needed for debugging419 when this test is run multiple times.420 */421 if(isWhitelisted) {422 console.log('UNQ token is already whitelisted on Polkadex');423 } else {424 await helper.getSudo().xcmHelper.whitelistToken(alice, uniqueAssetId);425 }426427 await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);428 });429430 await usingPlaygrounds(async (helper) => {431 await helper.balance.transferToSubstrate(alice, randomAccount.address, SENDER_BUDGET);432 balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);433 });434 });435436 itSub('Should connect and send UNQ to Polkadex', async () => {437 await genericSendUnqTo('polkadex', randomAccount);438 });439440441 itSub('Should connect to Polkadex and send UNQ back', async () => {442 await genericSendUnqBack('polkadex', alice, randomAccount);443 });444445 itSub('Polkadex can send only up to its balance', async () => {446 await genericSendOnlyOwnedBalance('polkadex', alice);447 });448449 itSub('Should not accept reserve transfer of UNQ from Polkadex', async () => {450 await genericReserveTransferUNQfrom('polkadex', alice);451 });452});453454// These tests are relevant only when455// the the corresponding foreign assets are not registered456describeXCM('[XCMLL] Integration test: Unique rejects non-native tokens', () => {457 let alice: IKeyringPair;458459 before(async () => {460 await usingPlaygrounds(async (helper, privateKey) => {461 alice = await privateKey('//Alice');462463 // Set the default version to wrap the first message to other chains.464 await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);465 });466 });467468 itSub('Unique rejects ACA tokens from Acala', async () => {469 await genericRejectNativeTokensFrom('acala', alice);470 });471472 itSub('Unique rejects GLMR tokens from Moonbeam', async () => {473 await genericRejectNativeTokensFrom('moonbeam', alice);474 });475476 itSub('Unique rejects ASTR tokens from Astar', async () => {477 await genericRejectNativeTokensFrom('astar', alice);478 });479480 itSub('Unique rejects PDX tokens from Polkadex', async () => {481 await genericRejectNativeTokensFrom('polkadex', alice);482 });483});484485describeXCM('[XCMLL] Integration test: Exchanging UNQ with Moonbeam', () => {486 // Unique constants487 let alice: IKeyringPair;488 let uniqueAssetLocation;489490 let randomAccountUnique: IKeyringPair;491 let randomAccountMoonbeam: IKeyringPair;492493 // Moonbeam constants494 let assetId: string;495496 const uniqueAssetMetadata = {497 name: 'xcUnique',498 symbol: 'xcUNQ',499 decimals: 18,500 isFrozen: false,501 minimalBalance: 1n,502 };503504505 before(async () => {506 await usingPlaygrounds(async (helper, privateKey) => {507 alice = await privateKey('//Alice');508 [randomAccountUnique] = await helper.arrange.createAccounts([0n], alice);509510511 // Set the default version to wrap the first message to other chains.512 await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);513 });514515 await usingMoonbeamPlaygrounds(moonbeamUrl, async (helper) => {516 const alithAccount = helper.account.alithAccount();517 const baltatharAccount = helper.account.baltatharAccount();518 const dorothyAccount = helper.account.dorothyAccount();519520 randomAccountMoonbeam = helper.account.create();521522 // >>> Sponsoring Dorothy >>>523 console.log('Sponsoring Dorothy.......');524 await helper.balance.transferToEthereum(alithAccount, dorothyAccount.address, 11_000_000_000_000_000_000n);525 console.log('Sponsoring Dorothy.......DONE');526 // <<< Sponsoring Dorothy <<<527 uniqueAssetLocation = {528 XCM: {529 parents: 1,530 interior: {X1: {Parachain: UNIQUE_CHAIN}},531 },532 };533 const existentialDeposit = 1n;534 const isSufficient = true;535 const unitsPerSecond = 1n;536 const numAssetsWeightHint = 0;537538 if((await helper.assetManager.assetTypeId(uniqueAssetLocation)).toJSON()) {539 console.log('Unique asset already registered on Moonbeam');540 } else {541 const encodedProposal = helper.assetManager.makeRegisterForeignAssetProposal({542 location: uniqueAssetLocation,543 metadata: uniqueAssetMetadata,544 existentialDeposit,545 isSufficient,546 unitsPerSecond,547 numAssetsWeightHint,548 });549550 console.log('Encoded proposal for registerForeignAsset & setAssetUnitsPerSecond is %s', encodedProposal);551552 await helper.fastDemocracy.executeProposal('register UNQ foreign asset', encodedProposal);553 }554555 // >>> Acquire Unique AssetId Info on Moonbeam >>>556 console.log('Acquire Unique AssetId Info on Moonbeam.......');557558 assetId = (await helper.assetManager.assetTypeId(uniqueAssetLocation)).toString();559560 console.log('UNQ asset ID is %s', assetId);561 console.log('Acquire Unique AssetId Info on Moonbeam.......DONE');562563 // >>> Sponsoring random Account >>>564 console.log('Sponsoring random Account.......');565 await helper.balance.transferToEthereum(baltatharAccount, randomAccountMoonbeam.address, 11_000_000_000_000_000_000n);566 console.log('Sponsoring random Account.......DONE');567 // <<< Sponsoring random Account <<<568 });569570 await usingPlaygrounds(async (helper) => {571 await helper.balance.transferToSubstrate(alice, randomAccountUnique.address, SENDER_BUDGET);572 balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccountUnique.address);573 });574 });575576 itSub('Should connect and send UNQ to Moonbeam', async () => {577 await genericSendUnqTo('moonbeam', randomAccountUnique, randomAccountMoonbeam);578 });579580 itSub('Should connect to Moonbeam and send UNQ back', async () => {581 await genericSendUnqBack('moonbeam', alice, randomAccountUnique);582 });583584 itSub('Moonbeam can send only up to its balance', async () => {585 await genericSendOnlyOwnedBalance('moonbeam', alice);586 });587588 itSub('Should not accept reserve transfer of UNQ from Moonbeam', async () => {589 await genericReserveTransferUNQfrom('moonbeam', alice);590 });591});592593describeXCM('[XCMLL] Integration test: Exchanging tokens with Astar', () => {594 let alice: IKeyringPair;595 let randomAccount: IKeyringPair;596597 const UNQ_ASSET_ID_ON_ASTAR = 1;598 const UNQ_MINIMAL_BALANCE_ON_ASTAR = 1n;599600 // Unique -> Astar601 const astarInitialBalance = 1n * (10n ** ASTAR_DECIMALS); // 1 ASTR, existential deposit required to actually create the account on Astar.602 const unitsPerSecond = 228_000_000_000n; // This is Phala's value. What will be ours?603604 before(async () => {605 await usingPlaygrounds(async (helper, privateKey) => {606 alice = await privateKey('//Alice');607 randomAccount = helper.arrange.createEmptyAccount();608 await helper.balance.transferToSubstrate(alice, randomAccount.address, SENDER_BUDGET);609 console.log('randomAccount', randomAccount.address);610611 // Set the default version to wrap the first message to other chains.612 await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);613 });614615 await usingAstarPlaygrounds(astarUrl, async (helper) => {616 if(!(await helper.callRpc('api.query.assets.asset', [UNQ_ASSET_ID_ON_ASTAR])).toJSON()) {617 console.log('1. Create foreign asset and metadata');618 // TODO update metadata with values from production619 await helper.assets.create(620 alice,621 UNQ_ASSET_ID_ON_ASTAR,622 alice.address,623 UNQ_MINIMAL_BALANCE_ON_ASTAR,624 );625626 await helper.assets.setMetadata(627 alice,628 UNQ_ASSET_ID_ON_ASTAR,629 'Cross chain UNQ',630 'xcUNQ',631 Number(UNQ_DECIMALS),632 );633634 console.log('2. Register asset location on Astar');635 const assetLocation = {636 V2: {637 parents: 1,638 interior: {639 X1: {640 Parachain: UNIQUE_CHAIN,641 },642 },643 },644 };645646 await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.registerAssetLocation', [assetLocation, UNQ_ASSET_ID_ON_ASTAR]);647648 console.log('3. Set UNQ payment for XCM execution on Astar');649 await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.setAssetUnitsPerSecond', [assetLocation, unitsPerSecond]);650 } else {651 console.log('UNQ is already registered on Astar');652 }653 console.log('4. Transfer 1 ASTR to recipient to create the account (needed due to existential balance)');654 await helper.balance.transferToSubstrate(alice, randomAccount.address, astarInitialBalance);655 });656 });657658 itSub('Should connect and send UNQ to Astar', async () => {659 await genericSendUnqTo('astar', randomAccount);660 });661662 itSub('Should connect to Astar and send UNQ back', async () => {663 await genericSendUnqBack('astar', alice, randomAccount);664 });665666 itSub('Astar can send only up to its balance', async () => {667 await genericSendOnlyOwnedBalance('astar', alice);668 });669670 itSub('Should not accept reserve transfer of UNQ from Astar', async () => {671 await genericReserveTransferUNQfrom('astar', alice);672 });673});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, usingAcalaPlaygrounds, usingMoonbeamPlaygrounds, usingAstarPlaygrounds, usingPolkadexPlaygrounds} from '../util';20import {Event} from '../util/playgrounds/unique.dev';21import {nToBigInt} from '@polkadot/util';22import {hexToString} from '@polkadot/util';23import {ASTAR_DECIMALS, NETWORKS, SAFE_XCM_VERSION, UNIQUE_CHAIN, UNQ_DECIMALS, XcmTestHelper, acalaUrl, astarUrl, expectFailedToTransact, expectUntrustedReserveLocationFail, getDevPlayground, mapToChainId, mapToChainUrl, maxWaitBlocks, moonbeamUrl, polkadexUrl, uniqueAssetId, uniqueVersionedMultilocation} from './xcm.types';242526const TRANSFER_AMOUNT = 2000000_000_000_000_000_000_000n;27const SENDER_BUDGET = 2n * TRANSFER_AMOUNT;28const SENDBACK_AMOUNT = TRANSFER_AMOUNT / 2n;29const STAYED_ON_TARGET_CHAIN = TRANSFER_AMOUNT - SENDBACK_AMOUNT;30const TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT = 100_000_000_000n;3132let balanceUniqueTokenInit: bigint;33let balanceUniqueTokenMiddle: bigint;34let balanceUniqueTokenFinal: bigint;35let unqFees: bigint;3637const testHelper = new XcmTestHelper('unique');3839async function genericSendUnqTo(40 networkName: keyof typeof NETWORKS,41 randomAccount: IKeyringPair,42 randomAccountOnTargetChain = randomAccount,43) {44 const networkUrl = mapToChainUrl(networkName);45 const targetPlayground = getDevPlayground(networkName);46 await usingPlaygrounds(async (helper) => {47 balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);48 const destination = {49 V2: {50 parents: 1,51 interior: {52 X1: {53 Parachain: mapToChainId(networkName),54 },55 },56 },57 };5859 const beneficiary = {60 V2: {61 parents: 0,62 interior: {63 X1: (64 networkName == 'moonbeam' ?65 {66 AccountKey20: {67 network: 'Any',68 key: randomAccountOnTargetChain.address,69 },70 }71 :72 {73 AccountId32: {74 network: 'Any',75 id: randomAccountOnTargetChain.addressRaw,76 },77 }78 ),79 },80 },81 };8283 const assets = {84 V2: [85 {86 id: {87 Concrete: {88 parents: 0,89 interior: 'Here',90 },91 },92 fun: {93 Fungible: TRANSFER_AMOUNT,94 },95 },96 ],97 };98 const feeAssetItem = 0;99100 await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');101 const messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);102 balanceUniqueTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);103104 unqFees = balanceUniqueTokenInit - balanceUniqueTokenMiddle - TRANSFER_AMOUNT;105 console.log('[Unique -> %s] transaction fees on Unique: %s UNQ', networkName, helper.util.bigIntToDecimals(unqFees));106 expect(unqFees > 0n, 'Negative fees UNQ, looks like nothing was transferred').to.be.true;107108 await targetPlayground(networkUrl, async (helper) => {109 /*110 Since only the parachain part of the Polkadex111 infrastructure is launched (without their112 solochain validators), processing incoming113 assets will lead to an error.114 This error indicates that the Polkadex chain115 received a message from the Unique network,116 since the hash is being checked to ensure117 it matches what was sent.118 */119 if(networkName == 'polkadex') {120 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash);121 } else {122 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == messageSent.messageHash);123 }124 });125126 });127}128129async function genericSendUnqBack(130 networkName: keyof typeof NETWORKS,131 sudoer: IKeyringPair,132 randomAccountOnUnq: IKeyringPair,133) {134 const networkUrl = mapToChainUrl(networkName);135136 const targetPlayground = getDevPlayground(networkName);137 await usingPlaygrounds(async (helper) => {138139 const xcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(140 randomAccountOnUnq.addressRaw,141 uniqueAssetId,142 SENDBACK_AMOUNT,143 );144145 let xcmProgramSent: any;146147148 await targetPlayground(networkUrl, async (helper) => {149 if('getSudo' in helper) {150 await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, xcmProgram);151 xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);152 } else if('fastDemocracy' in helper) {153 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, xcmProgram]);154 // Needed to bypass the call filter.155 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);156 await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);157 xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);158 }159 });160161 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == xcmProgramSent.messageHash);162163 balanceUniqueTokenFinal = await helper.balance.getSubstrate(randomAccountOnUnq.address);164165 expect(balanceUniqueTokenFinal).to.be.equal(balanceUniqueTokenInit - unqFees - STAYED_ON_TARGET_CHAIN);166167 });168}169170async function genericSendOnlyOwnedBalance(171 networkName: keyof typeof NETWORKS,172 sudoer: IKeyringPair,173) {174 const networkUrl = mapToChainUrl(networkName);175 const targetPlayground = getDevPlayground(networkName);176177 const targetChainBalance = 10000n * (10n ** UNQ_DECIMALS);178179 await usingPlaygrounds(async (helper) => {180 const targetChainSovereignAccount = helper.address.paraSiblingSovereignAccount(mapToChainId(networkName));181 await helper.getSudo().balance.setBalanceSubstrate(sudoer, targetChainSovereignAccount, targetChainBalance);182 const moreThanTargetChainHas = 2n * targetChainBalance;183184 const targetAccount = helper.arrange.createEmptyAccount();185186 const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(187 targetAccount.addressRaw,188 {189 Concrete: {190 parents: 0,191 interior: 'Here',192 },193 },194 moreThanTargetChainHas,195 );196197 let maliciousXcmProgramSent: any;198199200 await targetPlayground(networkUrl, async (helper) => {201 if('getSudo' in helper) {202 await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgram);203 maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);204 } else if('fastDemocracy' in helper) {205 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgram]);206 // Needed to bypass the call filter.207 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);208 await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);209 maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);210 }211 });212213 await expectFailedToTransact(helper, maliciousXcmProgramSent);214215 const targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);216 expect(targetAccountBalance).to.be.equal(0n);217 });218}219220async function genericReserveTransferUNQfrom(netwokrName: keyof typeof NETWORKS, sudoer: IKeyringPair) {221 const networkUrl = mapToChainUrl(netwokrName);222 const targetPlayground = getDevPlayground(netwokrName);223224 await usingPlaygrounds(async (helper) => {225 const testAmount = 10_000n * (10n ** UNQ_DECIMALS);226 const targetAccount = helper.arrange.createEmptyAccount();227228 const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(229 targetAccount.addressRaw,230 uniqueAssetId,231 testAmount,232 );233234 const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(235 targetAccount.addressRaw,236 {237 Concrete: {238 parents: 0,239 interior: 'Here',240 },241 },242 testAmount,243 );244245 let maliciousXcmProgramFullIdSent: any;246 let maliciousXcmProgramHereIdSent: any;247 const maxWaitBlocks = 3;248249 // Try to trick Unique using full UNQ identification250 await targetPlayground(networkUrl, async (helper) => {251 if('getSudo' in helper) {252 await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgramFullId);253 maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);254 }255 // Moonbeam case256 else if('fastDemocracy' in helper) {257 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramFullId]);258 // Needed to bypass the call filter.259 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);260 await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using path asset identification`,batchCall);261262 maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);263 }264 });265266267 await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramFullIdSent);268269 let accountBalance = await helper.balance.getSubstrate(targetAccount.address);270 expect(accountBalance).to.be.equal(0n);271272 // Try to trick Unique using shortened UNQ identification273 await targetPlayground(networkUrl, async (helper) => {274 if('getSudo' in helper) {275 await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgramHereId);276 maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);277 }278 else if('fastDemocracy' in helper) {279 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramHereId]);280 // Needed to bypass the call filter.281 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);282 await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using "here" asset identification`, batchCall);283284 maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);285 }286 });287288 await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramHereIdSent);289290 accountBalance = await helper.balance.getSubstrate(targetAccount.address);291 expect(accountBalance).to.be.equal(0n);292 });293}294295async function genericRejectNativeTokensFrom(networkName: keyof typeof NETWORKS, sudoerOnTargetChain: IKeyringPair) {296 const networkUrl = mapToChainUrl(networkName);297 const targetPlayground = getDevPlayground(networkName);298 let messageSent: any;299300 await usingPlaygrounds(async (helper) => {301 const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(302 helper.arrange.createEmptyAccount().addressRaw,303 {304 Concrete: {305 parents: 1,306 interior: {307 X1: {308 Parachain: mapToChainId(networkName),309 },310 },311 },312 },313 TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT,314 );315 await targetPlayground(networkUrl, async (helper) => {316 if('getSudo' in helper) {317 await helper.getSudo().xcm.send(sudoerOnTargetChain, uniqueVersionedMultilocation, maliciousXcmProgramFullId);318 messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);319 } else if('fastDemocracy' in helper) {320 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramFullId]);321 // Needed to bypass the call filter.322 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);323 await helper.fastDemocracy.executeProposal(`${networkName} sending native tokens to the Unique via fast democracy`, batchCall);324325 messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);326 }327 });328 await expectFailedToTransact(helper, messageSent);329 });330}331332333describeXCM('[XCMLL] Integration test: Exchanging tokens with Acala', () => {334 let alice: IKeyringPair;335 let randomAccount: IKeyringPair;336337 before(async () => {338 await usingPlaygrounds(async (helper, privateKey) => {339 alice = await privateKey('//Alice');340 console.log(config.acalaUrl);341 randomAccount = helper.arrange.createEmptyAccount();342343 // Set the default version to wrap the first message to other chains.344 await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);345 });346347 await usingAcalaPlaygrounds(acalaUrl, async (helper) => {348 const destination = {349 V2: {350 parents: 1,351 interior: {352 X1: {353 Parachain: UNIQUE_CHAIN,354 },355 },356 },357 };358359 const metadata = {360 name: 'Unique Network',361 symbol: 'UNQ',362 decimals: 18,363 minimalBalance: 1250_000_000_000_000_000n,364 };365 const assets = (await (helper.callRpc('api.query.assetRegistry.assetMetadatas.entries'))).map(([_k, v] : [any, any]) =>366 hexToString(v.toJSON()['symbol'])) as string[];367368 if(!assets.includes('UNQ')) {369 await helper.getSudo().assetRegistry.registerForeignAsset(alice, destination, metadata);370 } else {371 console.log('UNQ token already registered on Acala assetRegistry pallet');372 }373 await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);374 });375376 await usingPlaygrounds(async (helper) => {377 await helper.balance.transferToSubstrate(alice, randomAccount.address, SENDER_BUDGET);378 balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);379 });380 });381382 itSub('Should connect and send UNQ to Acala', async () => {383 await genericSendUnqTo('acala', randomAccount);384 });385386 itSub('Should connect to Acala and send UNQ back', async () => {387 await genericSendUnqBack('acala', alice, randomAccount);388 });389390 itSub('Acala can send only up to its balance', async () => {391 await genericSendOnlyOwnedBalance('acala', alice);392 });393394 itSub('Should not accept reserve transfer of UNQ from Acala', async () => {395 await genericReserveTransferUNQfrom('acala', alice);396 });397});398399describeXCM('[XCMLL] Integration test: Exchanging tokens with Polkadex', () => {400 let alice: IKeyringPair;401 let randomAccount: IKeyringPair;402403 before(async () => {404 await usingPlaygrounds(async (helper, privateKey) => {405 alice = await privateKey('//Alice');406 randomAccount = helper.arrange.createEmptyAccount();407408 // Set the default version to wrap the first message to other chains.409 await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);410 });411412 await usingPolkadexPlaygrounds(polkadexUrl, async (helper) => {413 const isWhitelisted = ((await helper.callRpc('api.query.xcmHelper.whitelistedTokens', []))414 .toJSON() as [])415 .map(nToBigInt).length != 0;416 /*417 Check whether the Unique token has been added418 to the whitelist, since an error will occur419 if it is added again. Needed for debugging420 when this test is run multiple times.421 */422 if(isWhitelisted) {423 console.log('UNQ token is already whitelisted on Polkadex');424 } else {425 await helper.getSudo().xcmHelper.whitelistToken(alice, uniqueAssetId);426 }427428 await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);429 });430431 await usingPlaygrounds(async (helper) => {432 await helper.balance.transferToSubstrate(alice, randomAccount.address, SENDER_BUDGET);433 balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);434 });435 });436437 itSub('Should connect and send UNQ to Polkadex', async () => {438 await testHelper.sendUnqTo('polkadex', randomAccount);439 });440441442 itSub('Should connect to Polkadex and send UNQ back', async () => {443 await testHelper.sendUnqBack('polkadex', alice, randomAccount);444 });445446 itSub('Polkadex can send only up to its balance', async () => {447 await testHelper.sendOnlyOwnedBalance('polkadex', alice);448 });449450 itSub('Should not accept reserve transfer of UNQ from Polkadex', async () => {451 await testHelper.reserveTransferUNQfrom('polkadex', alice);452 });453});454455// These tests are relevant only when456// the the corresponding foreign assets are not registered457describeXCM('[XCMLL] Integration test: Unique rejects non-native tokens', () => {458 let alice: IKeyringPair;459460 before(async () => {461 await usingPlaygrounds(async (helper, privateKey) => {462 alice = await privateKey('//Alice');463464 // Set the default version to wrap the first message to other chains.465 await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);466 });467 });468469 itSub('Unique rejects ACA tokens from Acala', async () => {470 await genericRejectNativeTokensFrom('acala', alice);471 });472473 itSub('Unique rejects GLMR tokens from Moonbeam', async () => {474 await genericRejectNativeTokensFrom('moonbeam', alice);475 });476477 itSub('Unique rejects ASTR tokens from Astar', async () => {478 await genericRejectNativeTokensFrom('astar', alice);479 });480481 itSub('Unique rejects PDX tokens from Polkadex', async () => {482 await genericRejectNativeTokensFrom('polkadex', alice);483 });484});485486describeXCM('[XCMLL] Integration test: Exchanging UNQ with Moonbeam', () => {487 // Unique constants488 let alice: IKeyringPair;489 let uniqueAssetLocation;490491 let randomAccountUnique: IKeyringPair;492 let randomAccountMoonbeam: IKeyringPair;493494 // Moonbeam constants495 let assetId: string;496497 const uniqueAssetMetadata = {498 name: 'xcUnique',499 symbol: 'xcUNQ',500 decimals: 18,501 isFrozen: false,502 minimalBalance: 1n,503 };504505506 before(async () => {507 await usingPlaygrounds(async (helper, privateKey) => {508 alice = await privateKey('//Alice');509 [randomAccountUnique] = await helper.arrange.createAccounts([0n], alice);510511512 // Set the default version to wrap the first message to other chains.513 await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);514 });515516 await usingMoonbeamPlaygrounds(moonbeamUrl, async (helper) => {517 const alithAccount = helper.account.alithAccount();518 const baltatharAccount = helper.account.baltatharAccount();519 const dorothyAccount = helper.account.dorothyAccount();520521 randomAccountMoonbeam = helper.account.create();522523 // >>> Sponsoring Dorothy >>>524 console.log('Sponsoring Dorothy.......');525 await helper.balance.transferToEthereum(alithAccount, dorothyAccount.address, 11_000_000_000_000_000_000n);526 console.log('Sponsoring Dorothy.......DONE');527 // <<< Sponsoring Dorothy <<<528 uniqueAssetLocation = {529 XCM: {530 parents: 1,531 interior: {X1: {Parachain: UNIQUE_CHAIN}},532 },533 };534 const existentialDeposit = 1n;535 const isSufficient = true;536 const unitsPerSecond = 1n;537 const numAssetsWeightHint = 0;538539 if((await helper.assetManager.assetTypeId(uniqueAssetLocation)).toJSON()) {540 console.log('Unique asset already registered on Moonbeam');541 } else {542 const encodedProposal = helper.assetManager.makeRegisterForeignAssetProposal({543 location: uniqueAssetLocation,544 metadata: uniqueAssetMetadata,545 existentialDeposit,546 isSufficient,547 unitsPerSecond,548 numAssetsWeightHint,549 });550551 console.log('Encoded proposal for registerForeignAsset & setAssetUnitsPerSecond is %s', encodedProposal);552553 await helper.fastDemocracy.executeProposal('register UNQ foreign asset', encodedProposal);554 }555556 // >>> Acquire Unique AssetId Info on Moonbeam >>>557 console.log('Acquire Unique AssetId Info on Moonbeam.......');558559 assetId = (await helper.assetManager.assetTypeId(uniqueAssetLocation)).toString();560561 console.log('UNQ asset ID is %s', assetId);562 console.log('Acquire Unique AssetId Info on Moonbeam.......DONE');563564 // >>> Sponsoring random Account >>>565 console.log('Sponsoring random Account.......');566 await helper.balance.transferToEthereum(baltatharAccount, randomAccountMoonbeam.address, 11_000_000_000_000_000_000n);567 console.log('Sponsoring random Account.......DONE');568 // <<< Sponsoring random Account <<<569 });570571 await usingPlaygrounds(async (helper) => {572 await helper.balance.transferToSubstrate(alice, randomAccountUnique.address, SENDER_BUDGET);573 balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccountUnique.address);574 });575 });576577 itSub('Should connect and send UNQ to Moonbeam', async () => {578 await testHelper.sendUnqTo('moonbeam', randomAccountUnique, randomAccountMoonbeam);579 });580581 itSub('Should connect to Moonbeam and send UNQ back', async () => {582 await testHelper.sendUnqBack('moonbeam', alice, randomAccountUnique);583 });584585 itSub('Moonbeam can send only up to its balance', async () => {586 await testHelper.sendOnlyOwnedBalance('moonbeam', alice);587 });588589 itSub('Should not accept reserve transfer of UNQ from Moonbeam', async () => {590 await testHelper.reserveTransferUNQfrom('moonbeam', alice);591 });592});593594describeXCM('[XCMLL] Integration test: Exchanging tokens with Astar', () => {595 let alice: IKeyringPair;596 let randomAccount: IKeyringPair;597598 const UNQ_ASSET_ID_ON_ASTAR = 1;599 const UNQ_MINIMAL_BALANCE_ON_ASTAR = 1n;600601 // Unique -> Astar602 const astarInitialBalance = 1n * (10n ** ASTAR_DECIMALS); // 1 ASTR, existential deposit required to actually create the account on Astar.603 const unitsPerSecond = 228_000_000_000n; // This is Phala's value. What will be ours?604605 before(async () => {606 await usingPlaygrounds(async (helper, privateKey) => {607 alice = await privateKey('//Alice');608 randomAccount = helper.arrange.createEmptyAccount();609 await helper.balance.transferToSubstrate(alice, randomAccount.address, SENDER_BUDGET);610 console.log('randomAccount', randomAccount.address);611612 // Set the default version to wrap the first message to other chains.613 await helper.getSudo().xcm.setSafeXcmVersion(alice, SAFE_XCM_VERSION);614 });615616 await usingAstarPlaygrounds(astarUrl, async (helper) => {617 if(!(await helper.callRpc('api.query.assets.asset', [UNQ_ASSET_ID_ON_ASTAR])).toJSON()) {618 console.log('1. Create foreign asset and metadata');619 // TODO update metadata with values from production620 await helper.assets.create(621 alice,622 UNQ_ASSET_ID_ON_ASTAR,623 alice.address,624 UNQ_MINIMAL_BALANCE_ON_ASTAR,625 );626627 await helper.assets.setMetadata(628 alice,629 UNQ_ASSET_ID_ON_ASTAR,630 'Cross chain UNQ',631 'xcUNQ',632 Number(UNQ_DECIMALS),633 );634635 console.log('2. Register asset location on Astar');636 const assetLocation = {637 V2: {638 parents: 1,639 interior: {640 X1: {641 Parachain: UNIQUE_CHAIN,642 },643 },644 },645 };646647 await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.registerAssetLocation', [assetLocation, UNQ_ASSET_ID_ON_ASTAR]);648649 console.log('3. Set UNQ payment for XCM execution on Astar');650 await helper.getSudo().executeExtrinsic(alice, 'api.tx.xcAssetConfig.setAssetUnitsPerSecond', [assetLocation, unitsPerSecond]);651 } else {652 console.log('UNQ is already registered on Astar');653 }654 console.log('4. Transfer 1 ASTR to recipient to create the account (needed due to existential balance)');655 await helper.balance.transferToSubstrate(alice, randomAccount.address, astarInitialBalance);656 });657 });658659 itSub('Should connect and send UNQ to Astar', async () => {660 await genericSendUnqTo('astar', randomAccount);661 });662663 itSub('Should connect to Astar and send UNQ back', async () => {664 await genericSendUnqBack('astar', alice, randomAccount);665 });666667 itSub('Astar can send only up to its balance', async () => {668 await genericSendOnlyOwnedBalance('astar', alice);669 });670671 itSub('Should not accept reserve transfer of UNQ from Astar', async () => {672 await genericReserveTransferUNQfrom('astar', alice);673 });674});tests/src/xcm/xcm.types.tsdiffbeforeafterboth--- a/tests/src/xcm/xcm.types.ts
+++ b/tests/src/xcm/xcm.types.ts
@@ -1,4 +1,5 @@
-import {usingAcalaPlaygrounds, usingAstarPlaygrounds, usingMoonbeamPlaygrounds, usingPolkadexPlaygrounds} from '../util';
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect, usingAcalaPlaygrounds, usingAstarPlaygrounds, usingKaruraPlaygrounds, usingMoonbeamPlaygrounds, usingMoonriverPlaygrounds, usingPlaygrounds, usingPolkadexPlaygrounds, usingShidenPlaygrounds} from '../util';
import {DevUniqueHelper, Event} from '../util/playgrounds/unique.dev';
import config from '../config';
@@ -9,19 +10,39 @@
export const ASTAR_CHAIN = +(process.env.RELAY_ASTAR_ID || 2006);
export const POLKADEX_CHAIN = +(process.env.RELAY_POLKADEX_ID || 2040);
+export const QUARTZ_CHAIN = +(process.env.RELAY_QUARTZ_ID || 2095);
+export const STATEMINE_CHAIN = +(process.env.RELAY_STATEMINE_ID || 1000);
+export const KARURA_CHAIN = +(process.env.RELAY_KARURA_ID || 2000);
+export const MOONRIVER_CHAIN = +(process.env.RELAY_MOONRIVER_ID || 2023);
+export const SHIDEN_CHAIN = +(process.env.RELAY_SHIDEN_ID || 2007);
+
+export const relayUrl = config.relayUrl;
+export const statemintUrl = config.statemintUrl;
+export const statemineUrl = config.statemineUrl;
+
export const acalaUrl = config.acalaUrl;
export const moonbeamUrl = config.moonbeamUrl;
export const astarUrl = config.astarUrl;
export const polkadexUrl = config.polkadexUrl;
+export const karuraUrl = config.karuraUrl;
+export const moonriverUrl = config.moonriverUrl;
+export const shidenUrl = config.shidenUrl;
+
export const SAFE_XCM_VERSION = 3;
-export const maxWaitBlocks = 6;
+export const RELAY_DECIMALS = 12;
+export const STATEMINE_DECIMALS = 12;
+export const KARURA_DECIMALS = 12;
+export const SHIDEN_DECIMALS = 18n;
+export const QTZ_DECIMALS = 18n;
export const ASTAR_DECIMALS = 18n;
export const UNQ_DECIMALS = 18n;
+export const maxWaitBlocks = 6;
+
export const uniqueMultilocation = {
parents: 1,
interior: {
@@ -52,9 +73,15 @@
astar: usingAstarPlaygrounds,
polkadex: usingPolkadexPlaygrounds,
moonbeam: usingMoonbeamPlaygrounds,
+ moonriver: usingMoonriverPlaygrounds,
+ karura: usingKaruraPlaygrounds,
+ shiden: usingShidenPlaygrounds,
} as const;
+type NetworkNames = keyof typeof NETWORKS;
-export function mapToChainId(networkName: keyof typeof NETWORKS) {
+type NativeRuntime = 'opal' | 'quartz' | 'unique';
+
+export function mapToChainId(networkName: keyof typeof NETWORKS): number {
switch (networkName) {
case 'acala':
return ACALA_CHAIN;
@@ -64,10 +91,16 @@
return MOONBEAM_CHAIN;
case 'polkadex':
return POLKADEX_CHAIN;
+ case 'moonriver':
+ return MOONRIVER_CHAIN;
+ case 'karura':
+ return KARURA_CHAIN;
+ case 'shiden':
+ return SHIDEN_CHAIN;
}
}
-export function mapToChainUrl(networkName: keyof typeof NETWORKS): string {
+export function mapToChainUrl(networkName: NetworkNames): string {
switch (networkName) {
case 'acala':
return acalaUrl;
@@ -77,9 +110,364 @@
return moonbeamUrl;
case 'polkadex':
return polkadexUrl;
+ case 'moonriver':
+ return moonriverUrl;
+ case 'karura':
+ return karuraUrl;
+ case 'shiden':
+ return shidenUrl;
}
}
-export function getDevPlayground<T extends keyof typeof NETWORKS>(name: T) {
+export function getDevPlayground(name: NetworkNames) {
return NETWORKS[name];
+}
+
+export const TRANSFER_AMOUNT = 2000000_000_000_000_000_000_000n;
+const SENDER_BUDGET = 2n * TRANSFER_AMOUNT;
+const SENDBACK_AMOUNT = TRANSFER_AMOUNT / 2n;
+const STAYED_ON_TARGET_CHAIN = TRANSFER_AMOUNT - SENDBACK_AMOUNT;
+const TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT = 100_000_000_000n;
+
+export class XcmTestHelper {
+ private _balanceUniqueTokenInit: bigint = 0n;
+ private _balanceUniqueTokenMiddle: bigint = 0n;
+ private _balanceUniqueTokenFinal: bigint = 0n;
+ private _unqFees: bigint = 0n;
+ private _nativeRuntime: NativeRuntime;
+
+ constructor(runtime: NativeRuntime) {
+ this._nativeRuntime = runtime;
+ }
+
+ private _getNativeId() {
+ switch (this._nativeRuntime) {
+ case 'opal':
+ // To-Do
+ return 10;
+ case 'quartz':
+ return QUARTZ_CHAIN;
+ case 'unique':
+ return UNIQUE_CHAIN;
+ }
+ }
+ private _isAddress20FormatFor(network: NetworkNames) {
+ switch (network) {
+ case 'moonbeam':
+ case 'moonriver':
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ async sendUnqTo(
+ networkName: keyof typeof NETWORKS,
+ randomAccount: IKeyringPair,
+ randomAccountOnTargetChain = randomAccount,
+ ) {
+ const networkUrl = mapToChainUrl(networkName);
+ const targetPlayground = getDevPlayground(networkName);
+ await usingPlaygrounds(async (helper) => {
+ this._balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);
+ const destination = {
+ V2: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: mapToChainId(networkName),
+ },
+ },
+ },
+ };
+
+ const beneficiary = {
+ V2: {
+ parents: 0,
+ interior: {
+ X1: (
+ this._isAddress20FormatFor(networkName) ?
+ {
+ AccountKey20: {
+ network: 'Any',
+ key: randomAccountOnTargetChain.address,
+ },
+ }
+ :
+ {
+ AccountId32: {
+ network: 'Any',
+ id: randomAccountOnTargetChain.addressRaw,
+ },
+ }
+ ),
+ },
+ },
+ };
+
+ const assets = {
+ V2: [
+ {
+ id: {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ fun: {
+ Fungible: TRANSFER_AMOUNT,
+ },
+ },
+ ],
+ };
+ const feeAssetItem = 0;
+
+ await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');
+ const messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
+ this._balanceUniqueTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);
+
+ this._unqFees = this._balanceUniqueTokenInit - this._balanceUniqueTokenMiddle - TRANSFER_AMOUNT;
+ console.log('[Unique -> %s] transaction fees on Unique: %s UNQ', networkName, helper.util.bigIntToDecimals(this._unqFees));
+ expect(this._unqFees > 0n, 'Negative fees UNQ, looks like nothing was transferred').to.be.true;
+
+ await targetPlayground(networkUrl, async (helper) => {
+ /*
+ Since only the parachain part of the Polkadex
+ infrastructure is launched (without their
+ solochain validators), processing incoming
+ assets will lead to an error.
+ This error indicates that the Polkadex chain
+ received a message from the Unique network,
+ since the hash is being checked to ensure
+ it matches what was sent.
+ */
+ if(networkName == 'polkadex') {
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash);
+ } else {
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == messageSent.messageHash);
+ }
+ });
+
+ });
+ }
+
+ async sendUnqBack(
+ networkName: keyof typeof NETWORKS,
+ sudoer: IKeyringPair,
+ randomAccountOnUnq: IKeyringPair,
+ ) {
+ const networkUrl = mapToChainUrl(networkName);
+
+ const targetPlayground = getDevPlayground(networkName);
+ await usingPlaygrounds(async (helper) => {
+
+ const xcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+ randomAccountOnUnq.addressRaw,
+ {
+ Concrete: {
+ parents: 1,
+ interior: {
+ X1: {Parachain: this._getNativeId()},
+ },
+ },
+ },
+ SENDBACK_AMOUNT,
+ );
+
+ let xcmProgramSent: any;
+
+
+ await targetPlayground(networkUrl, async (helper) => {
+ if('getSudo' in helper) {
+ await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, xcmProgram);
+ xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
+ } else if('fastDemocracy' in helper) {
+ const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, xcmProgram]);
+ // Needed to bypass the call filter.
+ const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);
+ await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);
+ xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
+ }
+ });
+
+ await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == xcmProgramSent.messageHash);
+
+ this._balanceUniqueTokenFinal = await helper.balance.getSubstrate(randomAccountOnUnq.address);
+
+ expect(this._balanceUniqueTokenFinal).to.be.equal(this._balanceUniqueTokenInit - this._unqFees - STAYED_ON_TARGET_CHAIN);
+
+ });
+ }
+
+ async sendOnlyOwnedBalance(
+ networkName: keyof typeof NETWORKS,
+ sudoer: IKeyringPair,
+ ) {
+ const networkUrl = mapToChainUrl(networkName);
+ const targetPlayground = getDevPlayground(networkName);
+
+ const targetChainBalance = 10000n * (10n ** UNQ_DECIMALS);
+
+ await usingPlaygrounds(async (helper) => {
+ const targetChainSovereignAccount = helper.address.paraSiblingSovereignAccount(mapToChainId(networkName));
+ await helper.getSudo().balance.setBalanceSubstrate(sudoer, targetChainSovereignAccount, targetChainBalance);
+ const moreThanTargetChainHas = 2n * targetChainBalance;
+
+ const targetAccount = helper.arrange.createEmptyAccount();
+
+ const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ moreThanTargetChainHas,
+ );
+
+ let maliciousXcmProgramSent: any;
+
+
+ await targetPlayground(networkUrl, async (helper) => {
+ if('getSudo' in helper) {
+ await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgram);
+ maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
+ } else if('fastDemocracy' in helper) {
+ const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgram]);
+ // Needed to bypass the call filter.
+ const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);
+ await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);
+ maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
+ }
+ });
+
+ await expectFailedToTransact(helper, maliciousXcmProgramSent);
+
+ const targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(targetAccountBalance).to.be.equal(0n);
+ });
+ }
+
+ async reserveTransferUNQfrom(netwokrName: keyof typeof NETWORKS, sudoer: IKeyringPair) {
+ const networkUrl = mapToChainUrl(netwokrName);
+ const targetPlayground = getDevPlayground(netwokrName);
+
+ await usingPlaygrounds(async (helper) => {
+ const testAmount = 10_000n * (10n ** UNQ_DECIMALS);
+ const targetAccount = helper.arrange.createEmptyAccount();
+
+ const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: this._getNativeId(),
+ },
+ },
+ },
+ },
+ testAmount,
+ );
+
+ const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(
+ targetAccount.addressRaw,
+ {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ testAmount,
+ );
+
+ let maliciousXcmProgramFullIdSent: any;
+ let maliciousXcmProgramHereIdSent: any;
+ const maxWaitBlocks = 3;
+
+ // Try to trick Unique using full UNQ identification
+ await targetPlayground(networkUrl, async (helper) => {
+ if('getSudo' in helper) {
+ await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgramFullId);
+ maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
+ }
+ // Moonbeam case
+ else if('fastDemocracy' in helper) {
+ const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramFullId]);
+ // Needed to bypass the call filter.
+ const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);
+ await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using path asset identification`,batchCall);
+
+ maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
+ }
+ });
+
+
+ await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramFullIdSent);
+
+ let accountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(accountBalance).to.be.equal(0n);
+
+ // Try to trick Unique using shortened UNQ identification
+ await targetPlayground(networkUrl, async (helper) => {
+ if('getSudo' in helper) {
+ await helper.getSudo().xcm.send(sudoer, uniqueVersionedMultilocation, maliciousXcmProgramHereId);
+ maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
+ }
+ else if('fastDemocracy' in helper) {
+ const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramHereId]);
+ // Needed to bypass the call filter.
+ const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);
+ await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using "here" asset identification`, batchCall);
+
+ maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
+ }
+ });
+
+ await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramHereIdSent);
+
+ accountBalance = await helper.balance.getSubstrate(targetAccount.address);
+ expect(accountBalance).to.be.equal(0n);
+ });
+ }
+
+ async rejectNativeTokensFrom(networkName: keyof typeof NETWORKS, sudoerOnTargetChain: IKeyringPair) {
+ const networkUrl = mapToChainUrl(networkName);
+ const targetPlayground = getDevPlayground(networkName);
+ let messageSent: any;
+
+ await usingPlaygrounds(async (helper) => {
+ const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(
+ helper.arrange.createEmptyAccount().addressRaw,
+ {
+ Concrete: {
+ parents: 1,
+ interior: {
+ X1: {
+ Parachain: mapToChainId(networkName),
+ },
+ },
+ },
+ },
+ TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT,
+ );
+ await targetPlayground(networkUrl, async (helper) => {
+ if('getSudo' in helper) {
+ await helper.getSudo().xcm.send(sudoerOnTargetChain, uniqueVersionedMultilocation, maliciousXcmProgramFullId);
+ messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
+ } else if('fastDemocracy' in helper) {
+ const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [uniqueVersionedMultilocation, maliciousXcmProgramFullId]);
+ // Needed to bypass the call filter.
+ const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);
+ await helper.fastDemocracy.executeProposal(`${networkName} sending native tokens to the Unique via fast democracy`, batchCall);
+
+ messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);
+ }
+ });
+ await expectFailedToTransact(helper, messageSent);
+ });
+ }
+
}
\ No newline at end of file
tests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmQuartz.test.ts
+++ b/tests/src/xcm/xcmQuartz.test.ts
@@ -15,29 +15,13 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import config from '../config';
import {itSub, expect, describeXCM, usingPlaygrounds, usingKaruraPlaygrounds, usingRelayPlaygrounds, usingMoonriverPlaygrounds, usingStateminePlaygrounds, usingShidenPlaygrounds} from '../util';
import {DevUniqueHelper, Event} from '../util/playgrounds/unique.dev';
+import {STATEMINE_CHAIN, QUARTZ_CHAIN, KARURA_CHAIN, MOONRIVER_CHAIN, SHIDEN_CHAIN, STATEMINE_DECIMALS, KARURA_DECIMALS, QTZ_DECIMALS, RELAY_DECIMALS, SHIDEN_DECIMALS, karuraUrl, moonriverUrl, relayUrl, shidenUrl, statemineUrl} from './xcm.types';
+
-const QUARTZ_CHAIN = +(process.env.RELAY_QUARTZ_ID || 2095);
-const STATEMINE_CHAIN = +(process.env.RELAY_STATEMINE_ID || 1000);
-const KARURA_CHAIN = +(process.env.RELAY_KARURA_ID || 2000);
-const MOONRIVER_CHAIN = +(process.env.RELAY_MOONRIVER_ID || 2023);
-const SHIDEN_CHAIN = +(process.env.RELAY_SHIDEN_ID || 2007);
const STATEMINE_PALLET_INSTANCE = 50;
-
-const relayUrl = config.relayUrl;
-const statemineUrl = config.statemineUrl;
-const karuraUrl = config.karuraUrl;
-const moonriverUrl = config.moonriverUrl;
-const shidenUrl = config.shidenUrl;
-
-const RELAY_DECIMALS = 12;
-const STATEMINE_DECIMALS = 12;
-const KARURA_DECIMALS = 12;
-const SHIDEN_DECIMALS = 18n;
-const QTZ_DECIMALS = 18n;
const TRANSFER_AMOUNT = 2000000000000000000000000n;