difftreelog
fix make _uniqueChainMultilocationForRelay private
in: master
1 file changed
tests/src/xcm/xcm.types.tsdiffbeforeafterboth1import {IKeyringPair} from '@polkadot/types/types';2import {hexToString} from '@polkadot/util';3import {expect, usingAcalaPlaygrounds, usingAstarPlaygrounds, usingKaruraPlaygrounds, usingMoonbeamPlaygrounds, usingMoonriverPlaygrounds, usingPlaygrounds, usingPolkadexPlaygrounds, usingRelayPlaygrounds, usingShidenPlaygrounds} from '../util';4import {DevUniqueHelper, Event} from '../util/playgrounds/unique.dev';5import config from '../config';67export const UNIQUE_CHAIN = +(process.env.RELAY_UNIQUE_ID || 2037);8export const STATEMINT_CHAIN = +(process.env.RELAY_STATEMINT_ID || 1000);9export const ACALA_CHAIN = +(process.env.RELAY_ACALA_ID || 2000);10export const MOONBEAM_CHAIN = +(process.env.RELAY_MOONBEAM_ID || 2004);11export const ASTAR_CHAIN = +(process.env.RELAY_ASTAR_ID || 2006);12export const POLKADEX_CHAIN = +(process.env.RELAY_POLKADEX_ID || 2040);1314export const QUARTZ_CHAIN = +(process.env.RELAY_QUARTZ_ID || 2095);15export const STATEMINE_CHAIN = +(process.env.RELAY_STATEMINE_ID || 1000);16export const KARURA_CHAIN = +(process.env.RELAY_KARURA_ID || 2000);17export const MOONRIVER_CHAIN = +(process.env.RELAY_MOONRIVER_ID || 2023);18export const SHIDEN_CHAIN = +(process.env.RELAY_SHIDEN_ID || 2007);1920export const relayUrl = config.relayUrl;21export const statemintUrl = config.statemintUrl;22export const statemineUrl = config.statemineUrl;2324export const acalaUrl = config.acalaUrl;25export const moonbeamUrl = config.moonbeamUrl;26export const astarUrl = config.astarUrl;27export const polkadexUrl = config.polkadexUrl;2829export const karuraUrl = config.karuraUrl;30export const moonriverUrl = config.moonriverUrl;31export const shidenUrl = config.shidenUrl;3233export const SAFE_XCM_VERSION = 3;343536export const RELAY_DECIMALS = 12;37export const STATEMINE_DECIMALS = 12;38export const KARURA_DECIMALS = 12;39export const SHIDEN_DECIMALS = 18n;40export const QTZ_DECIMALS = 18n;4142export const ASTAR_DECIMALS = 18n;43export const UNQ_DECIMALS = 18n;4445export const maxWaitBlocks = 6;4647export const uniqueMultilocation = {48 parents: 1,49 interior: {50 X1: {51 Parachain: UNIQUE_CHAIN,52 },53 },54};55export const uniqueVersionedMultilocation = {56 V3: uniqueMultilocation,57};5859export const uniqueAssetId = {60 Concrete: uniqueMultilocation,61};6263export const expectFailedToTransact = async (helper: DevUniqueHelper, messageSent: any) => {64 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash65 && event.outcome.isFailedToTransactAsset);66};67export const expectUntrustedReserveLocationFail = async (helper: DevUniqueHelper, messageSent: any) => {68 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash69 && event.outcome.isUntrustedReserveLocation);70};7172export const expectDownwardXcmNoPermission = async (helper: DevUniqueHelper) => {73 // The correct messageHash for downward messages can't be reliably obtained74 await helper.wait.expectEvent(maxWaitBlocks, Event.DmpQueue.ExecutedDownward, event => event.outcome.asIncomplete[1].isNoPermission);75};7677export const expectDownwardXcmComplete = async (helper: DevUniqueHelper) => {78 // The correct messageHash for downward messages can't be reliably obtained79 await helper.wait.expectEvent(maxWaitBlocks, Event.DmpQueue.ExecutedDownward, event => event.outcome.isComplete);80};8182export const NETWORKS = {83 acala: usingAcalaPlaygrounds,84 astar: usingAstarPlaygrounds,85 polkadex: usingPolkadexPlaygrounds,86 moonbeam: usingMoonbeamPlaygrounds,87 moonriver: usingMoonriverPlaygrounds,88 karura: usingKaruraPlaygrounds,89 shiden: usingShidenPlaygrounds,90} as const;91type NetworkNames = keyof typeof NETWORKS;9293type NativeRuntime = 'opal' | 'quartz' | 'unique';9495export function mapToChainId(networkName: keyof typeof NETWORKS): number {96 switch (networkName) {97 case 'acala':98 return ACALA_CHAIN;99 case 'astar':100 return ASTAR_CHAIN;101 case 'moonbeam':102 return MOONBEAM_CHAIN;103 case 'polkadex':104 return POLKADEX_CHAIN;105 case 'moonriver':106 return MOONRIVER_CHAIN;107 case 'karura':108 return KARURA_CHAIN;109 case 'shiden':110 return SHIDEN_CHAIN;111 }112}113114export function mapToChainUrl(networkName: NetworkNames): string {115 switch (networkName) {116 case 'acala':117 return acalaUrl;118 case 'astar':119 return astarUrl;120 case 'moonbeam':121 return moonbeamUrl;122 case 'polkadex':123 return polkadexUrl;124 case 'moonriver':125 return moonriverUrl;126 case 'karura':127 return karuraUrl;128 case 'shiden':129 return shidenUrl;130 }131}132133export function getDevPlayground(name: NetworkNames) {134 return NETWORKS[name];135}136137export const TRANSFER_AMOUNT = 2000000_000_000_000_000_000_000n;138export const SENDER_BUDGET = 2n * TRANSFER_AMOUNT;139export const SENDBACK_AMOUNT = TRANSFER_AMOUNT / 2n;140export const STAYED_ON_TARGET_CHAIN = TRANSFER_AMOUNT - SENDBACK_AMOUNT;141export const TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT = 100_000_000_000n;142143export class XcmTestHelper {144 private _balanceUniqueTokenInit: bigint = 0n;145 private _balanceUniqueTokenMiddle: bigint = 0n;146 private _balanceUniqueTokenFinal: bigint = 0n;147 private _unqFees: bigint = 0n;148 private _nativeRuntime: NativeRuntime;149150 constructor(runtime: NativeRuntime) {151 this._nativeRuntime = runtime;152 }153154 private _getNativeId() {155 switch (this._nativeRuntime) {156 case 'opal':157 // To-Do158 return 10;159 case 'quartz':160 return QUARTZ_CHAIN;161 case 'unique':162 return UNIQUE_CHAIN;163 }164 }165166 private _isAddress20FormatFor(network: NetworkNames) {167 switch (network) {168 case 'moonbeam':169 case 'moonriver':170 return true;171 default:172 return false;173 }174 }175176 private _runtimeVersionedMultilocation() {177 return {178 V3: {179 parents: 1,180 interior: {181 X1: {182 Parachain: this._getNativeId(),183 },184 },185 },186 };187 }188189 uniqueChainMultilocationForRelay() {190 return {191 V3: {192 parents: 0,193 interior: {194 X1: {Parachain: this._getNativeId()},195 },196 },197 };198 }199200 async sendUnqTo(201 networkName: keyof typeof NETWORKS,202 randomAccount: IKeyringPair,203 randomAccountOnTargetChain = randomAccount,204 ) {205 const networkUrl = mapToChainUrl(networkName);206 const targetPlayground = getDevPlayground(networkName);207 await usingPlaygrounds(async (helper) => {208 this._balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);209 const destination = {210 V2: {211 parents: 1,212 interior: {213 X1: {214 Parachain: mapToChainId(networkName),215 },216 },217 },218 };219220 const beneficiary = {221 V2: {222 parents: 0,223 interior: {224 X1: (225 this._isAddress20FormatFor(networkName) ?226 {227 AccountKey20: {228 network: 'Any',229 key: randomAccountOnTargetChain.address,230 },231 }232 :233 {234 AccountId32: {235 network: 'Any',236 id: randomAccountOnTargetChain.addressRaw,237 },238 }239 ),240 },241 },242 };243244 const assets = {245 V2: [246 {247 id: {248 Concrete: {249 parents: 0,250 interior: 'Here',251 },252 },253 fun: {254 Fungible: TRANSFER_AMOUNT,255 },256 },257 ],258 };259 const feeAssetItem = 0;260261 await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');262 const messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);263 this._balanceUniqueTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);264265 this._unqFees = this._balanceUniqueTokenInit - this._balanceUniqueTokenMiddle - TRANSFER_AMOUNT;266 console.log('[%s -> %s] transaction fees: %s', this._nativeRuntime, networkName, helper.util.bigIntToDecimals(this._unqFees));267 expect(this._unqFees > 0n, 'Negative fees, looks like nothing was transferred').to.be.true;268269 await targetPlayground(networkUrl, async (helper) => {270 /*271 Since only the parachain part of the Polkadex272 infrastructure is launched (without their273 solochain validators), processing incoming274 assets will lead to an error.275 This error indicates that the Polkadex chain276 received a message from the Unique network,277 since the hash is being checked to ensure278 it matches what was sent.279 */280 if(networkName == 'polkadex') {281 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash);282 } else {283 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == messageSent.messageHash);284 }285 });286287 });288 }289290 async sendUnqBack(291 networkName: keyof typeof NETWORKS,292 sudoer: IKeyringPair,293 randomAccountOnUnq: IKeyringPair,294 ) {295 const networkUrl = mapToChainUrl(networkName);296297 const targetPlayground = getDevPlayground(networkName);298 await usingPlaygrounds(async (helper) => {299300 const xcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(301 randomAccountOnUnq.addressRaw,302 {303 Concrete: {304 parents: 1,305 interior: {306 X1: {Parachain: this._getNativeId()},307 },308 },309 },310 SENDBACK_AMOUNT,311 );312313 let xcmProgramSent: any;314315316 await targetPlayground(networkUrl, async (helper) => {317 if('getSudo' in helper) {318 await helper.getSudo().xcm.send(sudoer, this._runtimeVersionedMultilocation(), xcmProgram);319 xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);320 } else if('fastDemocracy' in helper) {321 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [this._runtimeVersionedMultilocation(), xcmProgram]);322 // Needed to bypass the call filter.323 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);324 await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);325 xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);326 }327 });328329 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == xcmProgramSent.messageHash);330331 this._balanceUniqueTokenFinal = await helper.balance.getSubstrate(randomAccountOnUnq.address);332333 expect(this._balanceUniqueTokenFinal).to.be.equal(this._balanceUniqueTokenInit - this._unqFees - STAYED_ON_TARGET_CHAIN);334335 });336 }337338 async sendOnlyOwnedBalance(339 networkName: keyof typeof NETWORKS,340 sudoer: IKeyringPair,341 ) {342 const networkUrl = mapToChainUrl(networkName);343 const targetPlayground = getDevPlayground(networkName);344345 const targetChainBalance = 10000n * (10n ** UNQ_DECIMALS);346347 await usingPlaygrounds(async (helper) => {348 const targetChainSovereignAccount = helper.address.paraSiblingSovereignAccount(mapToChainId(networkName));349 await helper.getSudo().balance.setBalanceSubstrate(sudoer, targetChainSovereignAccount, targetChainBalance);350 const moreThanTargetChainHas = 2n * targetChainBalance;351352 const targetAccount = helper.arrange.createEmptyAccount();353354 const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(355 targetAccount.addressRaw,356 {357 Concrete: {358 parents: 0,359 interior: 'Here',360 },361 },362 moreThanTargetChainHas,363 );364365 let maliciousXcmProgramSent: any;366367368 await targetPlayground(networkUrl, async (helper) => {369 if('getSudo' in helper) {370 await helper.getSudo().xcm.send(sudoer, this._runtimeVersionedMultilocation(), maliciousXcmProgram);371 maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);372 } else if('fastDemocracy' in helper) {373 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [this._runtimeVersionedMultilocation(), maliciousXcmProgram]);374 // Needed to bypass the call filter.375 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);376 await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);377 maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);378 }379 });380381 await expectFailedToTransact(helper, maliciousXcmProgramSent);382383 const targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);384 expect(targetAccountBalance).to.be.equal(0n);385 });386 }387388 async reserveTransferUNQfrom(netwokrName: keyof typeof NETWORKS, sudoer: IKeyringPair) {389 const networkUrl = mapToChainUrl(netwokrName);390 const targetPlayground = getDevPlayground(netwokrName);391392 await usingPlaygrounds(async (helper) => {393 const testAmount = 10_000n * (10n ** UNQ_DECIMALS);394 const targetAccount = helper.arrange.createEmptyAccount();395396 const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(397 targetAccount.addressRaw,398 {399 Concrete: {400 parents: 1,401 interior: {402 X1: {403 Parachain: this._getNativeId(),404 },405 },406 },407 },408 testAmount,409 );410411 const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(412 targetAccount.addressRaw,413 {414 Concrete: {415 parents: 0,416 interior: 'Here',417 },418 },419 testAmount,420 );421422 let maliciousXcmProgramFullIdSent: any;423 let maliciousXcmProgramHereIdSent: any;424 const maxWaitBlocks = 3;425426 // Try to trick Unique using full UNQ identification427 await targetPlayground(networkUrl, async (helper) => {428 if('getSudo' in helper) {429 await helper.getSudo().xcm.send(sudoer, this._runtimeVersionedMultilocation(), maliciousXcmProgramFullId);430 maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);431 }432 // Moonbeam case433 else if('fastDemocracy' in helper) {434 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [this._runtimeVersionedMultilocation(), maliciousXcmProgramFullId]);435 // Needed to bypass the call filter.436 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);437 await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using path asset identification`,batchCall);438439 maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);440 }441 });442443444 await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramFullIdSent);445446 let accountBalance = await helper.balance.getSubstrate(targetAccount.address);447 expect(accountBalance).to.be.equal(0n);448449 // Try to trick Unique using shortened UNQ identification450 await targetPlayground(networkUrl, async (helper) => {451 if('getSudo' in helper) {452 await helper.getSudo().xcm.send(sudoer, this._runtimeVersionedMultilocation(), maliciousXcmProgramHereId);453 maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);454 }455 else if('fastDemocracy' in helper) {456 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [this._runtimeVersionedMultilocation(), maliciousXcmProgramHereId]);457 // Needed to bypass the call filter.458 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);459 await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using "here" asset identification`, batchCall);460461 maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);462 }463 });464465 await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramHereIdSent);466467 accountBalance = await helper.balance.getSubstrate(targetAccount.address);468 expect(accountBalance).to.be.equal(0n);469 });470 }471472 async rejectNativeTokensFrom(networkName: keyof typeof NETWORKS, sudoerOnTargetChain: IKeyringPair) {473 const networkUrl = mapToChainUrl(networkName);474 const targetPlayground = getDevPlayground(networkName);475 let messageSent: any;476477 await usingPlaygrounds(async (helper) => {478 const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(479 helper.arrange.createEmptyAccount().addressRaw,480 {481 Concrete: {482 parents: 1,483 interior: {484 X1: {485 Parachain: mapToChainId(networkName),486 },487 },488 },489 },490 TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT,491 );492 await targetPlayground(networkUrl, async (helper) => {493 if('getSudo' in helper) {494 await helper.getSudo().xcm.send(sudoerOnTargetChain, this._runtimeVersionedMultilocation(), maliciousXcmProgramFullId);495 messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);496 } else if('fastDemocracy' in helper) {497 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [this._runtimeVersionedMultilocation(), maliciousXcmProgramFullId]);498 // Needed to bypass the call filter.499 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);500 await helper.fastDemocracy.executeProposal(`${networkName} sending native tokens to the Unique via fast democracy`, batchCall);501502 messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);503 }504 });505 await expectFailedToTransact(helper, messageSent);506 });507 }508509 private async _relayXcmTransactSetStorage(variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch') {510 // eslint-disable-next-line require-await511 return await usingPlaygrounds(async (helper) => {512 const relayForceKV = () => {513 const random = Math.random();514 const key = `relay-forced-key (instance: ${random})`;515 const val = `relay-forced-value (instance: ${random})`;516 const call = helper.constructApiCall('api.tx.system.setStorage', [[[key, val]]]).method.toHex();517518 return {519 call,520 key,521 val,522 };523 };524525 if(variant == 'plain') {526 const kv = relayForceKV();527 return {528 program: helper.arrange.makeUnpaidSudoTransactProgram({529 weightMultiplier: 1,530 call: kv.call,531 }),532 kvs: [kv],533 };534 } else {535 const kv0 = relayForceKV();536 const kv1 = relayForceKV();537538 const batchCall = helper.constructApiCall(`api.tx.utility.${variant}`, [[kv0.call, kv1.call]]).method.toHex();539 return {540 program: helper.arrange.makeUnpaidSudoTransactProgram({541 weightMultiplier: 2,542 call: batchCall,543 }),544 kvs: [kv0, kv1],545 };546 }547 });548 }549550 async relayIsPermittedToSetStorage(relaySudoer: IKeyringPair, variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch') {551 const {program, kvs} = await this._relayXcmTransactSetStorage(variant);552553 await usingRelayPlaygrounds(relayUrl, async (helper) => {554 await helper.getSudo().executeExtrinsic(relaySudoer, 'api.tx.xcmPallet.send', [555 this.uniqueChainMultilocationForRelay(),556 program,557 ]);558 });559560 await usingPlaygrounds(async (helper) => {561 await expectDownwardXcmComplete(helper);562563 for(const kv of kvs) {564 const forcedValue = await helper.callRpc('api.rpc.state.getStorage', [kv.key]);565 expect(hexToString(forcedValue.toHex())).to.be.equal(kv.val);566 }567 });568 }569570 private async _relayXcmTransactSetBalance(variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch' | 'dispatchAs') {571 // eslint-disable-next-line require-await572 return await usingPlaygrounds(async (helper) => {573 const emptyAccount = helper.arrange.createEmptyAccount().address;574575 const forceSetBalanceCall = helper.constructApiCall('api.tx.balances.forceSetBalance', [emptyAccount, 10_000n]).method.toHex();576577 let call;578579 if(variant == 'plain') {580 call = forceSetBalanceCall;581582 } else if(variant == 'dispatchAs') {583 call = helper.constructApiCall('api.tx.utility.dispatchAs', [584 {585 system: 'Root',586 },587 forceSetBalanceCall,588 ]).method.toHex();589 } else {590 call = helper.constructApiCall(`api.tx.utility.${variant}`, [[forceSetBalanceCall]]).method.toHex();591 }592593 return {594 program: helper.arrange.makeUnpaidSudoTransactProgram({595 weightMultiplier: 1,596 call,597 }),598 emptyAccount,599 };600 });601 }602603 async relayIsNotPermittedToSetBalance(604 relaySudoer: IKeyringPair,605 variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch' | 'dispatchAs',606 ) {607 const {program, emptyAccount} = await this._relayXcmTransactSetBalance(variant);608609 await usingRelayPlaygrounds(relayUrl, async (helper) => {610 await helper.getSudo().executeExtrinsic(relaySudoer, 'api.tx.xcmPallet.send', [611 this.uniqueChainMultilocationForRelay(),612 program,613 ]);614 });615616 await usingPlaygrounds(async (helper) => {617 await expectDownwardXcmNoPermission(helper);618 expect(await helper.balance.getSubstrate(emptyAccount)).to.be.equal(0n);619 });620 }621}1import {IKeyringPair} from '@polkadot/types/types';2import {hexToString} from '@polkadot/util';3import {expect, usingAcalaPlaygrounds, usingAstarPlaygrounds, usingKaruraPlaygrounds, usingMoonbeamPlaygrounds, usingMoonriverPlaygrounds, usingPlaygrounds, usingPolkadexPlaygrounds, usingRelayPlaygrounds, usingShidenPlaygrounds} from '../util';4import {DevUniqueHelper, Event} from '../util/playgrounds/unique.dev';5import config from '../config';67export const UNIQUE_CHAIN = +(process.env.RELAY_UNIQUE_ID || 2037);8export const STATEMINT_CHAIN = +(process.env.RELAY_STATEMINT_ID || 1000);9export const ACALA_CHAIN = +(process.env.RELAY_ACALA_ID || 2000);10export const MOONBEAM_CHAIN = +(process.env.RELAY_MOONBEAM_ID || 2004);11export const ASTAR_CHAIN = +(process.env.RELAY_ASTAR_ID || 2006);12export const POLKADEX_CHAIN = +(process.env.RELAY_POLKADEX_ID || 2040);1314export const QUARTZ_CHAIN = +(process.env.RELAY_QUARTZ_ID || 2095);15export const STATEMINE_CHAIN = +(process.env.RELAY_STATEMINE_ID || 1000);16export const KARURA_CHAIN = +(process.env.RELAY_KARURA_ID || 2000);17export const MOONRIVER_CHAIN = +(process.env.RELAY_MOONRIVER_ID || 2023);18export const SHIDEN_CHAIN = +(process.env.RELAY_SHIDEN_ID || 2007);1920export const relayUrl = config.relayUrl;21export const statemintUrl = config.statemintUrl;22export const statemineUrl = config.statemineUrl;2324export const acalaUrl = config.acalaUrl;25export const moonbeamUrl = config.moonbeamUrl;26export const astarUrl = config.astarUrl;27export const polkadexUrl = config.polkadexUrl;2829export const karuraUrl = config.karuraUrl;30export const moonriverUrl = config.moonriverUrl;31export const shidenUrl = config.shidenUrl;3233export const SAFE_XCM_VERSION = 3;343536export const RELAY_DECIMALS = 12;37export const STATEMINE_DECIMALS = 12;38export const KARURA_DECIMALS = 12;39export const SHIDEN_DECIMALS = 18n;40export const QTZ_DECIMALS = 18n;4142export const ASTAR_DECIMALS = 18n;43export const UNQ_DECIMALS = 18n;4445export const maxWaitBlocks = 6;4647export const uniqueMultilocation = {48 parents: 1,49 interior: {50 X1: {51 Parachain: UNIQUE_CHAIN,52 },53 },54};55export const uniqueVersionedMultilocation = {56 V3: uniqueMultilocation,57};5859export const uniqueAssetId = {60 Concrete: uniqueMultilocation,61};6263export const expectFailedToTransact = async (helper: DevUniqueHelper, messageSent: any) => {64 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash65 && event.outcome.isFailedToTransactAsset);66};67export const expectUntrustedReserveLocationFail = async (helper: DevUniqueHelper, messageSent: any) => {68 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash69 && event.outcome.isUntrustedReserveLocation);70};7172export const expectDownwardXcmNoPermission = async (helper: DevUniqueHelper) => {73 // The correct messageHash for downward messages can't be reliably obtained74 await helper.wait.expectEvent(maxWaitBlocks, Event.DmpQueue.ExecutedDownward, event => event.outcome.asIncomplete[1].isNoPermission);75};7677export const expectDownwardXcmComplete = async (helper: DevUniqueHelper) => {78 // The correct messageHash for downward messages can't be reliably obtained79 await helper.wait.expectEvent(maxWaitBlocks, Event.DmpQueue.ExecutedDownward, event => event.outcome.isComplete);80};8182export const NETWORKS = {83 acala: usingAcalaPlaygrounds,84 astar: usingAstarPlaygrounds,85 polkadex: usingPolkadexPlaygrounds,86 moonbeam: usingMoonbeamPlaygrounds,87 moonriver: usingMoonriverPlaygrounds,88 karura: usingKaruraPlaygrounds,89 shiden: usingShidenPlaygrounds,90} as const;91type NetworkNames = keyof typeof NETWORKS;9293type NativeRuntime = 'opal' | 'quartz' | 'unique';9495export function mapToChainId(networkName: keyof typeof NETWORKS): number {96 switch (networkName) {97 case 'acala':98 return ACALA_CHAIN;99 case 'astar':100 return ASTAR_CHAIN;101 case 'moonbeam':102 return MOONBEAM_CHAIN;103 case 'polkadex':104 return POLKADEX_CHAIN;105 case 'moonriver':106 return MOONRIVER_CHAIN;107 case 'karura':108 return KARURA_CHAIN;109 case 'shiden':110 return SHIDEN_CHAIN;111 }112}113114export function mapToChainUrl(networkName: NetworkNames): string {115 switch (networkName) {116 case 'acala':117 return acalaUrl;118 case 'astar':119 return astarUrl;120 case 'moonbeam':121 return moonbeamUrl;122 case 'polkadex':123 return polkadexUrl;124 case 'moonriver':125 return moonriverUrl;126 case 'karura':127 return karuraUrl;128 case 'shiden':129 return shidenUrl;130 }131}132133export function getDevPlayground(name: NetworkNames) {134 return NETWORKS[name];135}136137export const TRANSFER_AMOUNT = 2000000_000_000_000_000_000_000n;138export const SENDER_BUDGET = 2n * TRANSFER_AMOUNT;139export const SENDBACK_AMOUNT = TRANSFER_AMOUNT / 2n;140export const STAYED_ON_TARGET_CHAIN = TRANSFER_AMOUNT - SENDBACK_AMOUNT;141export const TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT = 100_000_000_000n;142143export class XcmTestHelper {144 private _balanceUniqueTokenInit: bigint = 0n;145 private _balanceUniqueTokenMiddle: bigint = 0n;146 private _balanceUniqueTokenFinal: bigint = 0n;147 private _unqFees: bigint = 0n;148 private _nativeRuntime: NativeRuntime;149150 constructor(runtime: NativeRuntime) {151 this._nativeRuntime = runtime;152 }153154 private _getNativeId() {155 switch (this._nativeRuntime) {156 case 'opal':157 // To-Do158 return 10;159 case 'quartz':160 return QUARTZ_CHAIN;161 case 'unique':162 return UNIQUE_CHAIN;163 }164 }165166 private _isAddress20FormatFor(network: NetworkNames) {167 switch (network) {168 case 'moonbeam':169 case 'moonriver':170 return true;171 default:172 return false;173 }174 }175176 private _runtimeVersionedMultilocation() {177 return {178 V3: {179 parents: 1,180 interior: {181 X1: {182 Parachain: this._getNativeId(),183 },184 },185 },186 };187 }188189 private _uniqueChainMultilocationForRelay() {190 return {191 V3: {192 parents: 0,193 interior: {194 X1: {Parachain: this._getNativeId()},195 },196 },197 };198 }199200 async sendUnqTo(201 networkName: keyof typeof NETWORKS,202 randomAccount: IKeyringPair,203 randomAccountOnTargetChain = randomAccount,204 ) {205 const networkUrl = mapToChainUrl(networkName);206 const targetPlayground = getDevPlayground(networkName);207 await usingPlaygrounds(async (helper) => {208 this._balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);209 const destination = {210 V2: {211 parents: 1,212 interior: {213 X1: {214 Parachain: mapToChainId(networkName),215 },216 },217 },218 };219220 const beneficiary = {221 V2: {222 parents: 0,223 interior: {224 X1: (225 this._isAddress20FormatFor(networkName) ?226 {227 AccountKey20: {228 network: 'Any',229 key: randomAccountOnTargetChain.address,230 },231 }232 :233 {234 AccountId32: {235 network: 'Any',236 id: randomAccountOnTargetChain.addressRaw,237 },238 }239 ),240 },241 },242 };243244 const assets = {245 V2: [246 {247 id: {248 Concrete: {249 parents: 0,250 interior: 'Here',251 },252 },253 fun: {254 Fungible: TRANSFER_AMOUNT,255 },256 },257 ],258 };259 const feeAssetItem = 0;260261 await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, 'Unlimited');262 const messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);263 this._balanceUniqueTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);264265 this._unqFees = this._balanceUniqueTokenInit - this._balanceUniqueTokenMiddle - TRANSFER_AMOUNT;266 console.log('[%s -> %s] transaction fees: %s', this._nativeRuntime, networkName, helper.util.bigIntToDecimals(this._unqFees));267 expect(this._unqFees > 0n, 'Negative fees, looks like nothing was transferred').to.be.true;268269 await targetPlayground(networkUrl, async (helper) => {270 /*271 Since only the parachain part of the Polkadex272 infrastructure is launched (without their273 solochain validators), processing incoming274 assets will lead to an error.275 This error indicates that the Polkadex chain276 received a message from the Unique network,277 since the hash is being checked to ensure278 it matches what was sent.279 */280 if(networkName == 'polkadex') {281 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Fail, event => event.messageHash == messageSent.messageHash);282 } else {283 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == messageSent.messageHash);284 }285 });286287 });288 }289290 async sendUnqBack(291 networkName: keyof typeof NETWORKS,292 sudoer: IKeyringPair,293 randomAccountOnUnq: IKeyringPair,294 ) {295 const networkUrl = mapToChainUrl(networkName);296297 const targetPlayground = getDevPlayground(networkName);298 await usingPlaygrounds(async (helper) => {299300 const xcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(301 randomAccountOnUnq.addressRaw,302 {303 Concrete: {304 parents: 1,305 interior: {306 X1: {Parachain: this._getNativeId()},307 },308 },309 },310 SENDBACK_AMOUNT,311 );312313 let xcmProgramSent: any;314315316 await targetPlayground(networkUrl, async (helper) => {317 if('getSudo' in helper) {318 await helper.getSudo().xcm.send(sudoer, this._runtimeVersionedMultilocation(), xcmProgram);319 xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);320 } else if('fastDemocracy' in helper) {321 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [this._runtimeVersionedMultilocation(), xcmProgram]);322 // Needed to bypass the call filter.323 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);324 await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);325 xcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);326 }327 });328329 await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.Success, event => event.messageHash == xcmProgramSent.messageHash);330331 this._balanceUniqueTokenFinal = await helper.balance.getSubstrate(randomAccountOnUnq.address);332333 expect(this._balanceUniqueTokenFinal).to.be.equal(this._balanceUniqueTokenInit - this._unqFees - STAYED_ON_TARGET_CHAIN);334335 });336 }337338 async sendOnlyOwnedBalance(339 networkName: keyof typeof NETWORKS,340 sudoer: IKeyringPair,341 ) {342 const networkUrl = mapToChainUrl(networkName);343 const targetPlayground = getDevPlayground(networkName);344345 const targetChainBalance = 10000n * (10n ** UNQ_DECIMALS);346347 await usingPlaygrounds(async (helper) => {348 const targetChainSovereignAccount = helper.address.paraSiblingSovereignAccount(mapToChainId(networkName));349 await helper.getSudo().balance.setBalanceSubstrate(sudoer, targetChainSovereignAccount, targetChainBalance);350 const moreThanTargetChainHas = 2n * targetChainBalance;351352 const targetAccount = helper.arrange.createEmptyAccount();353354 const maliciousXcmProgram = helper.arrange.makeXcmProgramWithdrawDeposit(355 targetAccount.addressRaw,356 {357 Concrete: {358 parents: 0,359 interior: 'Here',360 },361 },362 moreThanTargetChainHas,363 );364365 let maliciousXcmProgramSent: any;366367368 await targetPlayground(networkUrl, async (helper) => {369 if('getSudo' in helper) {370 await helper.getSudo().xcm.send(sudoer, this._runtimeVersionedMultilocation(), maliciousXcmProgram);371 maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);372 } else if('fastDemocracy' in helper) {373 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [this._runtimeVersionedMultilocation(), maliciousXcmProgram]);374 // Needed to bypass the call filter.375 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);376 await helper.fastDemocracy.executeProposal(`sending ${networkName} -> Unique via XCM program`, batchCall);377 maliciousXcmProgramSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);378 }379 });380381 await expectFailedToTransact(helper, maliciousXcmProgramSent);382383 const targetAccountBalance = await helper.balance.getSubstrate(targetAccount.address);384 expect(targetAccountBalance).to.be.equal(0n);385 });386 }387388 async reserveTransferUNQfrom(netwokrName: keyof typeof NETWORKS, sudoer: IKeyringPair) {389 const networkUrl = mapToChainUrl(netwokrName);390 const targetPlayground = getDevPlayground(netwokrName);391392 await usingPlaygrounds(async (helper) => {393 const testAmount = 10_000n * (10n ** UNQ_DECIMALS);394 const targetAccount = helper.arrange.createEmptyAccount();395396 const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(397 targetAccount.addressRaw,398 {399 Concrete: {400 parents: 1,401 interior: {402 X1: {403 Parachain: this._getNativeId(),404 },405 },406 },407 },408 testAmount,409 );410411 const maliciousXcmProgramHereId = helper.arrange.makeXcmProgramReserveAssetDeposited(412 targetAccount.addressRaw,413 {414 Concrete: {415 parents: 0,416 interior: 'Here',417 },418 },419 testAmount,420 );421422 let maliciousXcmProgramFullIdSent: any;423 let maliciousXcmProgramHereIdSent: any;424 const maxWaitBlocks = 3;425426 // Try to trick Unique using full UNQ identification427 await targetPlayground(networkUrl, async (helper) => {428 if('getSudo' in helper) {429 await helper.getSudo().xcm.send(sudoer, this._runtimeVersionedMultilocation(), maliciousXcmProgramFullId);430 maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);431 }432 // Moonbeam case433 else if('fastDemocracy' in helper) {434 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [this._runtimeVersionedMultilocation(), maliciousXcmProgramFullId]);435 // Needed to bypass the call filter.436 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);437 await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using path asset identification`,batchCall);438439 maliciousXcmProgramFullIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);440 }441 });442443444 await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramFullIdSent);445446 let accountBalance = await helper.balance.getSubstrate(targetAccount.address);447 expect(accountBalance).to.be.equal(0n);448449 // Try to trick Unique using shortened UNQ identification450 await targetPlayground(networkUrl, async (helper) => {451 if('getSudo' in helper) {452 await helper.getSudo().xcm.send(sudoer, this._runtimeVersionedMultilocation(), maliciousXcmProgramHereId);453 maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);454 }455 else if('fastDemocracy' in helper) {456 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [this._runtimeVersionedMultilocation(), maliciousXcmProgramHereId]);457 // Needed to bypass the call filter.458 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);459 await helper.fastDemocracy.executeProposal(`${netwokrName} try to act like a reserve location for UNQ using "here" asset identification`, batchCall);460461 maliciousXcmProgramHereIdSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);462 }463 });464465 await expectUntrustedReserveLocationFail(helper, maliciousXcmProgramHereIdSent);466467 accountBalance = await helper.balance.getSubstrate(targetAccount.address);468 expect(accountBalance).to.be.equal(0n);469 });470 }471472 async rejectNativeTokensFrom(networkName: keyof typeof NETWORKS, sudoerOnTargetChain: IKeyringPair) {473 const networkUrl = mapToChainUrl(networkName);474 const targetPlayground = getDevPlayground(networkName);475 let messageSent: any;476477 await usingPlaygrounds(async (helper) => {478 const maliciousXcmProgramFullId = helper.arrange.makeXcmProgramReserveAssetDeposited(479 helper.arrange.createEmptyAccount().addressRaw,480 {481 Concrete: {482 parents: 1,483 interior: {484 X1: {485 Parachain: mapToChainId(networkName),486 },487 },488 },489 },490 TARGET_CHAIN_TOKEN_TRANSFER_AMOUNT,491 );492 await targetPlayground(networkUrl, async (helper) => {493 if('getSudo' in helper) {494 await helper.getSudo().xcm.send(sudoerOnTargetChain, this._runtimeVersionedMultilocation(), maliciousXcmProgramFullId);495 messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);496 } else if('fastDemocracy' in helper) {497 const xcmSend = helper.constructApiCall('api.tx.polkadotXcm.send', [this._runtimeVersionedMultilocation(), maliciousXcmProgramFullId]);498 // Needed to bypass the call filter.499 const batchCall = helper.encodeApiCall('api.tx.utility.batch', [[xcmSend]]);500 await helper.fastDemocracy.executeProposal(`${networkName} sending native tokens to the Unique via fast democracy`, batchCall);501502 messageSent = await helper.wait.expectEvent(maxWaitBlocks, Event.XcmpQueue.XcmpMessageSent);503 }504 });505 await expectFailedToTransact(helper, messageSent);506 });507 }508509 private async _relayXcmTransactSetStorage(variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch') {510 // eslint-disable-next-line require-await511 return await usingPlaygrounds(async (helper) => {512 const relayForceKV = () => {513 const random = Math.random();514 const key = `relay-forced-key (instance: ${random})`;515 const val = `relay-forced-value (instance: ${random})`;516 const call = helper.constructApiCall('api.tx.system.setStorage', [[[key, val]]]).method.toHex();517518 return {519 call,520 key,521 val,522 };523 };524525 if(variant == 'plain') {526 const kv = relayForceKV();527 return {528 program: helper.arrange.makeUnpaidSudoTransactProgram({529 weightMultiplier: 1,530 call: kv.call,531 }),532 kvs: [kv],533 };534 } else {535 const kv0 = relayForceKV();536 const kv1 = relayForceKV();537538 const batchCall = helper.constructApiCall(`api.tx.utility.${variant}`, [[kv0.call, kv1.call]]).method.toHex();539 return {540 program: helper.arrange.makeUnpaidSudoTransactProgram({541 weightMultiplier: 2,542 call: batchCall,543 }),544 kvs: [kv0, kv1],545 };546 }547 });548 }549550 async relayIsPermittedToSetStorage(relaySudoer: IKeyringPair, variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch') {551 const {program, kvs} = await this._relayXcmTransactSetStorage(variant);552553 await usingRelayPlaygrounds(relayUrl, async (helper) => {554 await helper.getSudo().executeExtrinsic(relaySudoer, 'api.tx.xcmPallet.send', [555 this._uniqueChainMultilocationForRelay(),556 program,557 ]);558 });559560 await usingPlaygrounds(async (helper) => {561 await expectDownwardXcmComplete(helper);562563 for(const kv of kvs) {564 const forcedValue = await helper.callRpc('api.rpc.state.getStorage', [kv.key]);565 expect(hexToString(forcedValue.toHex())).to.be.equal(kv.val);566 }567 });568 }569570 private async _relayXcmTransactSetBalance(variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch' | 'dispatchAs') {571 // eslint-disable-next-line require-await572 return await usingPlaygrounds(async (helper) => {573 const emptyAccount = helper.arrange.createEmptyAccount().address;574575 const forceSetBalanceCall = helper.constructApiCall('api.tx.balances.forceSetBalance', [emptyAccount, 10_000n]).method.toHex();576577 let call;578579 if(variant == 'plain') {580 call = forceSetBalanceCall;581582 } else if(variant == 'dispatchAs') {583 call = helper.constructApiCall('api.tx.utility.dispatchAs', [584 {585 system: 'Root',586 },587 forceSetBalanceCall,588 ]).method.toHex();589 } else {590 call = helper.constructApiCall(`api.tx.utility.${variant}`, [[forceSetBalanceCall]]).method.toHex();591 }592593 return {594 program: helper.arrange.makeUnpaidSudoTransactProgram({595 weightMultiplier: 1,596 call,597 }),598 emptyAccount,599 };600 });601 }602603 async relayIsNotPermittedToSetBalance(604 relaySudoer: IKeyringPair,605 variant: 'plain' | 'batch' | 'batchAll' | 'forceBatch' | 'dispatchAs',606 ) {607 const {program, emptyAccount} = await this._relayXcmTransactSetBalance(variant);608609 await usingRelayPlaygrounds(relayUrl, async (helper) => {610 await helper.getSudo().executeExtrinsic(relaySudoer, 'api.tx.xcmPallet.send', [611 this._uniqueChainMultilocationForRelay(),612 program,613 ]);614 });615616 await usingPlaygrounds(async (helper) => {617 await expectDownwardXcmNoPermission(helper);618 expect(await helper.balance.getSubstrate(emptyAccount)).to.be.equal(0n);619 });620 }621}