@paraspell/sdk-core 8.12.1 → 8.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { isTMultiLocation, Parents, isRelayChain, NODE_NAMES_DOT_KSM, hasJunction, deepEqual } from '@paraspell/sdk-common';
2
2
  export * from '@paraspell/sdk-common';
3
3
  import { ethers, Contract } from 'ethers';
4
- import { InvalidCurrencyError, getNativeAssetSymbol, getOtherAssets, isNodeEvm, getRelayChainSymbol, isForeignAsset, findAssetByMultiLocation, isAssetEqual, getAssetId, getAssetsObject, findAsset, isOverrideMultiLocationSpecifier, hasDryRunSupport, isTMultiAsset, isSymbolSpecifier, getNativeAssets, hasSupportForAsset, extractMultiAssetLoc, getExistentialDeposit } from '@paraspell/assets';
4
+ import { InvalidCurrencyError, isForeignAsset, getOtherAssets, isNodeEvm, findAssetByMultiLocation, getNativeAssetSymbol, isAssetEqual, getAssetId, getRelayChainSymbol, hasDryRunSupport, findAsset, getAssetsObject, isOverrideMultiLocationSpecifier, isTMultiAsset, isSymbolSpecifier, getNativeAssets, hasSupportForAsset, extractMultiAssetLoc, getExistentialDeposit } from '@paraspell/assets';
5
5
  export * from '@paraspell/assets';
6
6
  import { getSupportedPalletsDetails, getDefaultPallet } from '@paraspell/pallets';
7
7
  export * from '@paraspell/pallets';
@@ -955,25 +955,6 @@ var ScenarioNotSupportedError = /*#__PURE__*/function (_Error) {
955
955
  return _createClass(ScenarioNotSupportedError);
956
956
  }(/*#__PURE__*/_wrapNativeSuper(Error));
957
957
 
958
- var DEFAULT_FEE_ASSET = 0;
959
- var ETH_PARA_ID = 1;
960
- var ETH_CHAIN_ID = BigInt(ETH_PARA_ID);
961
- var ETHEREUM_JUNCTION = {
962
- GlobalConsensus: {
963
- Ethereum: {
964
- chainId: ETH_CHAIN_ID
965
- }
966
- }
967
- };
968
- var DOT_MULTILOCATION = {
969
- parents: Parents.ONE,
970
- interior: 'Here'
971
- };
972
- var SYSTEM_NODES_POLKADOT = ['PeoplePolkadot', 'CoretimePolkadot', 'Collectives'];
973
- var SYSTEM_NODES_KUSAMA = ['PeopleKusama', 'CoretimeKusama'];
974
- var ASSET_HUB_EXECUTION_FEE = 2200000000n; // 0.22 DOT
975
- // 30% padding
976
-
977
958
  var AssetHubPolkadot$1 = {
978
959
  name: "AssetHub",
979
960
  info: "PolkadotAssetHub",
@@ -1227,14 +1208,14 @@ var Centrifuge$1 = {
1227
1208
  info: "centrifuge",
1228
1209
  paraId: 2031,
1229
1210
  providers: [
1230
- {
1231
- name: "Centrifuge",
1232
- endpoint: "wss://fullnode.centrifuge.io"
1233
- },
1234
1211
  {
1235
1212
  name: "LuckyFriday",
1236
1213
  endpoint: "wss://rpc-centrifuge.luckyfriday.io"
1237
1214
  },
1215
+ {
1216
+ name: "Centrifuge",
1217
+ endpoint: "wss://fullnode.centrifuge.io"
1218
+ },
1238
1219
  {
1239
1220
  name: "OnFinality",
1240
1221
  endpoint: "wss://centrifuge-parachain.api.onfinality.io/public-ws"
@@ -2301,57 +2282,24 @@ var getNodeProviders = function getNodeProviders(node) {
2301
2282
  });
2302
2283
  };
2303
2284
 
2304
- /**
2305
- * Retrieves the parachain ID for a specified node.
2306
- *
2307
- * @param node - The node for which to get the paraId.
2308
- * @returns The parachain ID of the node.
2309
- */
2310
- var getParaId = function getParaId(node) {
2311
- if (node === 'Ethereum') {
2312
- return ETH_PARA_ID;
2313
- }
2314
- return getNodeConfig(node).paraId;
2315
- };
2316
-
2317
- var shuffleArray = function shuffleArray(array) {
2318
- var copy = _toConsumableArray(array);
2319
- for (var i = copy.length - 1; i > 0; i--) {
2320
- var j = Math.floor(Math.random() * (i + 1));
2321
- var _ref = [copy[j], copy[i]];
2322
- copy[i] = _ref[0];
2323
- copy[j] = _ref[1];
2285
+ var DEFAULT_FEE_ASSET = 0;
2286
+ var ETH_PARA_ID = 1;
2287
+ var ETH_CHAIN_ID = BigInt(ETH_PARA_ID);
2288
+ var ETHEREUM_JUNCTION = {
2289
+ GlobalConsensus: {
2290
+ Ethereum: {
2291
+ chainId: ETH_CHAIN_ID
2292
+ }
2324
2293
  }
2325
- return copy;
2326
2294
  };
2327
-
2328
- var shuffleWsProviders = function shuffleWsProviders(node, wsProviders) {
2329
- var ALLOWED_NODES = ['Hydration', 'Acala'];
2330
- if (ALLOWED_NODES.includes(node)) {
2331
- return shuffleArray(wsProviders);
2332
- }
2333
- return wsProviders;
2295
+ var DOT_MULTILOCATION = {
2296
+ parents: Parents.ONE,
2297
+ interior: 'Here'
2334
2298
  };
2335
-
2336
- var createApiInstanceForNode = /*#__PURE__*/function () {
2337
- var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(api, node) {
2338
- var wsUrl, resolvedWsUrl;
2339
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2340
- while (1) switch (_context.prev = _context.next) {
2341
- case 0:
2342
- wsUrl = getNodeProviders(node);
2343
- resolvedWsUrl = Array.isArray(wsUrl) ? shuffleWsProviders(node, wsUrl) : wsUrl;
2344
- return _context.abrupt("return", api.createApiInstance(resolvedWsUrl));
2345
- case 3:
2346
- case "end":
2347
- return _context.stop();
2348
- }
2349
- }, _callee);
2350
- }));
2351
- return function createApiInstanceForNode(_x, _x2) {
2352
- return _ref.apply(this, arguments);
2353
- };
2354
- }();
2299
+ var SYSTEM_NODES_POLKADOT = ['PeoplePolkadot', 'CoretimePolkadot', 'Collectives'];
2300
+ var SYSTEM_NODES_KUSAMA = ['PeopleKusama', 'CoretimeKusama'];
2301
+ var ASSET_HUB_EXECUTION_FEE = 2200000000n; // 0.22 DOT
2302
+ // 30% padding
2355
2303
 
2356
2304
  var createX1Payload = function createX1Payload(version, junction) {
2357
2305
  return version === Version.V4 ? {
@@ -2514,6 +2462,169 @@ var throwUnsupportedCurrency = function throwUnsupportedCurrency(currency, node)
2514
2462
  throw new InvalidCurrencyError("".concat(isDestination ? 'Destination' : 'Origin', " node ").concat(node, " does not support currency ").concat(JSON.stringify(currency), "."));
2515
2463
  };
2516
2464
 
2465
+ var buildMultiLocation = function buildMultiLocation(_ref) {
2466
+ var paraIdTo = _ref.paraIdTo,
2467
+ asset = _ref.asset,
2468
+ origin = _ref.origin,
2469
+ destination = _ref.destination;
2470
+ if (!isForeignAsset(asset)) {
2471
+ if (_typeof(destination) === 'object') {
2472
+ return destination;
2473
+ }
2474
+ // ParaToRelay scenario
2475
+ if (isRelayChain(destination)) {
2476
+ return DOT_MULTILOCATION;
2477
+ }
2478
+ // If it is a native asset, search by symbol on AssetHub and use the multiLocation from there
2479
+ var assetHubAsset = getOtherAssets(destination).find(function (ahAsset) {
2480
+ var _ahAsset$symbol, _asset$symbol;
2481
+ return ((_ahAsset$symbol = ahAsset.symbol) === null || _ahAsset$symbol === void 0 ? void 0 : _ahAsset$symbol.toLowerCase()) === ((_asset$symbol = asset.symbol) === null || _asset$symbol === void 0 ? void 0 : _asset$symbol.toLowerCase());
2482
+ });
2483
+ if (assetHubAsset === undefined) {
2484
+ throw new InvalidCurrencyError("Asset ".concat(asset.symbol, " not found in AssetHub"));
2485
+ }
2486
+ if (assetHubAsset.multiLocation) {
2487
+ return assetHubAsset.multiLocation;
2488
+ }
2489
+ throw new InvalidCurrencyError("Asset ".concat(asset.symbol, " has no multiLocation"));
2490
+ }
2491
+ var createDefaultMultiLocation = function createDefaultMultiLocation(assetId) {
2492
+ return {
2493
+ parents: Parents.ONE,
2494
+ interior: {
2495
+ X3: [{
2496
+ Parachain: paraIdTo
2497
+ }, {
2498
+ PalletInstance: '50'
2499
+ }, {
2500
+ GeneralIndex: BigInt(assetId)
2501
+ }]
2502
+ }
2503
+ };
2504
+ };
2505
+ var isBifrostOrigin = origin === 'BifrostPolkadot' || origin === 'BifrostKusama';
2506
+ if (isBifrostOrigin) {
2507
+ return createDefaultMultiLocation(asset.assetId);
2508
+ }
2509
+ if (asset.multiLocation) {
2510
+ return asset.multiLocation;
2511
+ } else {
2512
+ return createDefaultMultiLocation(asset.assetId);
2513
+ }
2514
+ };
2515
+ var getModifiedCurrencySelection = function getModifiedCurrencySelection(version, input) {
2516
+ var amount = input.asset.amount,
2517
+ overriddenAsset = input.overriddenAsset;
2518
+ if (overriddenAsset) {
2519
+ return addXcmVersionHeader(maybeOverrideMultiAssets(version, amount, [], overriddenAsset), version);
2520
+ }
2521
+ var multiLocation = buildMultiLocation(input);
2522
+ var multiAsset = createMultiAsset(version, amount, multiLocation);
2523
+ return addXcmVersionHeader(multiAsset, version);
2524
+ };
2525
+
2526
+ var getCurrencySelection = function getCurrencySelection(input, useMultiAssets, currencySelection) {
2527
+ var origin = input.origin;
2528
+ var _getNode = getNode(origin),
2529
+ version = _getNode.version;
2530
+ if (useMultiAssets) {
2531
+ return getModifiedCurrencySelection(version, input);
2532
+ }
2533
+ return currencySelection;
2534
+ };
2535
+
2536
+ var getXTokensParameters = function getXTokensParameters(isMultiAssetTransfer, currencySelection, addressSelection, amount, fees, overriddenAsset) {
2537
+ if (isMultiAssetTransfer) {
2538
+ var isOverridenMultiAssets = overriddenAsset && !isTMultiLocation(overriddenAsset);
2539
+ var feeAssetIndex = isOverridenMultiAssets ? overriddenAsset.findIndex(function (asset) {
2540
+ return asset.isFeeAsset;
2541
+ }) : undefined;
2542
+ return _objectSpread2(_objectSpread2(_defineProperty({}, isOverridenMultiAssets ? 'assets' : 'asset', currencySelection), isOverridenMultiAssets && {
2543
+ fee_item: feeAssetIndex
2544
+ }), {}, {
2545
+ dest: addressSelection,
2546
+ dest_weight_limit: fees
2547
+ });
2548
+ }
2549
+ return {
2550
+ currency_id: currencySelection,
2551
+ amount: BigInt(amount),
2552
+ dest: addressSelection,
2553
+ dest_weight_limit: fees
2554
+ };
2555
+ };
2556
+
2557
+ var XTokensTransferImpl = /*#__PURE__*/function () {
2558
+ function XTokensTransferImpl() {
2559
+ _classCallCheck(this, XTokensTransferImpl);
2560
+ }
2561
+ return _createClass(XTokensTransferImpl, null, [{
2562
+ key: "transferXTokens",
2563
+ value: function transferXTokens(input, currencySelection) {
2564
+ var fees = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'Unlimited';
2565
+ var api = input.api,
2566
+ origin = input.origin,
2567
+ asset = input.asset,
2568
+ addressSelection = input.addressSelection,
2569
+ destination = input.destination,
2570
+ scenario = input.scenario,
2571
+ overriddenAsset = input.overriddenAsset,
2572
+ pallet = input.pallet,
2573
+ method = input.method,
2574
+ _input$useMultiAssetT = input.useMultiAssetTransfer,
2575
+ useMultiAssetTransfer = _input$useMultiAssetT === void 0 ? false : _input$useMultiAssetT;
2576
+ var isMultiLocationDestination = _typeof(destination) === 'object';
2577
+ if (isMultiLocationDestination) {
2578
+ throw new Error('Multilocation destinations are not supported for specific transfer you are trying to create. In special cases such as xTokens or xTransfer pallet try using address multilocation instead (for both destination and address in same multilocation set (eg. X2 - Parachain, Address). For further assistance please open issue in our repository.');
2579
+ }
2580
+ var isBifrostOrigin = origin === 'BifrostPolkadot' || origin === 'BifrostKusama';
2581
+ var isAssetHubDest = destination === 'AssetHubPolkadot' || destination === 'AssetHubKusama';
2582
+ var isAstarOrShidenToRelay = scenario === 'ParaToRelay' && (origin === 'Astar' || origin === 'Shiden');
2583
+ var isOverridenMultiAssets = overriddenAsset && !isTMultiLocation(overriddenAsset);
2584
+ var shouldUseMultiasset = useMultiAssetTransfer || isAstarOrShidenToRelay || isAssetHubDest && !isBifrostOrigin || !!isOverridenMultiAssets;
2585
+ var modifiedCurrencySelection = getCurrencySelection(input, shouldUseMultiasset, currencySelection);
2586
+ var section = shouldUseMultiasset ? isOverridenMultiAssets ? 'transfer_multiassets' : 'transfer_multiasset' : 'transfer';
2587
+ var parameters = getXTokensParameters(shouldUseMultiasset, modifiedCurrencySelection, addressSelection, asset.amount, fees, overriddenAsset);
2588
+ var call = {
2589
+ module: pallet !== null && pallet !== void 0 ? pallet : 'XTokens',
2590
+ section: method !== null && method !== void 0 ? method : section,
2591
+ parameters: parameters
2592
+ };
2593
+ return api.callTxMethod(call);
2594
+ }
2595
+ }]);
2596
+ }();
2597
+
2598
+ var getBridgeStatus = /*#__PURE__*/function () {
2599
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(api) {
2600
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2601
+ while (1) switch (_context.prev = _context.next) {
2602
+ case 0:
2603
+ _context.next = 2;
2604
+ return api.init('BridgeHubPolkadot');
2605
+ case 2:
2606
+ _context.prev = 2;
2607
+ _context.next = 5;
2608
+ return api.getBridgeStatus();
2609
+ case 5:
2610
+ return _context.abrupt("return", _context.sent);
2611
+ case 6:
2612
+ _context.prev = 6;
2613
+ _context.next = 9;
2614
+ return api.disconnect();
2615
+ case 9:
2616
+ return _context.finish(6);
2617
+ case 10:
2618
+ case "end":
2619
+ return _context.stop();
2620
+ }
2621
+ }, _callee, null, [[2,, 6, 10]]);
2622
+ }));
2623
+ return function getBridgeStatus(_x) {
2624
+ return _ref.apply(this, arguments);
2625
+ };
2626
+ }();
2627
+
2517
2628
  var createBeneficiaryMultiLocation = function createBeneficiaryMultiLocation(_ref) {
2518
2629
  var api = _ref.api,
2519
2630
  scenario = _ref.scenario,
@@ -2606,548 +2717,159 @@ var transformMultiLocation = function transformMultiLocation(multiLocation) {
2606
2717
  });
2607
2718
  };
2608
2719
 
2609
- var createVersionedBeneficiary = function createVersionedBeneficiary(options) {
2610
- var version = options.version;
2611
- var multiLocation = createBeneficiaryMultiLocation(options);
2612
- return addXcmVersionHeader(multiLocation, version);
2613
- };
2614
-
2615
- var getMultiLocationTokenId = function getMultiLocationTokenId(location, node) {
2616
- if (location.interior.type === 'Here') {
2617
- // native token
2618
- return getNativeAssetSymbol(node);
2720
+ var createCustomXcmOnDest = function createCustomXcmOnDest(_ref, origin, version, messageId) {
2721
+ var api = _ref.api,
2722
+ address = _ref.address,
2723
+ asset = _ref.asset,
2724
+ scenario = _ref.scenario,
2725
+ senderAddress = _ref.senderAddress,
2726
+ ahAddress = _ref.ahAddress;
2727
+ if (!isForeignAsset(asset)) {
2728
+ throw new InvalidCurrencyError("Asset ".concat(JSON.stringify(asset), " is not a foreign asset"));
2619
2729
  }
2620
- var foreignAssets = getOtherAssets(node);
2621
- if (location.interior.type === 'X2') {
2622
- if (location.interior.value[0].type === 'PalletInstance' && location.interior.value[0].value === 50 && location.interior.value[1].type === 'GeneralIndex') {
2623
- var _foreignAssets$find$a, _foreignAssets$find;
2624
- var assetId = location.interior.value[1].value;
2625
- return (_foreignAssets$find$a = (_foreignAssets$find = foreignAssets.find(function (asset) {
2626
- return asset.assetId === String(assetId);
2627
- })) === null || _foreignAssets$find === void 0 ? void 0 : _foreignAssets$find.assetId) !== null && _foreignAssets$find$a !== void 0 ? _foreignAssets$find$a : null;
2628
- }
2730
+ if (!asset.multiLocation) {
2731
+ throw new InvalidCurrencyError("Asset ".concat(JSON.stringify(asset), " has no multiLocation"));
2629
2732
  }
2630
- return null;
2631
- };
2632
-
2633
- var computeFeeFromDryRun = function computeFeeFromDryRun(dryRun, node, executionFee) {
2634
- // Extract delivery fees from emitted events
2635
- var deliveryFees = [];
2636
- var _iterator = _createForOfIteratorHelper(dryRun.value.emitted_events),
2637
- _step;
2638
- try {
2639
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
2640
- var e = _step.value;
2641
- var isXcmEvent = e.type === 'XcmPallet' || e.type === 'PolkadotXcm' || e.type === 'CumulusXcm';
2642
- var isFeesPaid = e.value.type === 'FeesPaid';
2643
- if (isXcmEvent && isFeesPaid && e.value.value.fees) {
2644
- var _iterator2 = _createForOfIteratorHelper(e.value.value.fees),
2645
- _step2;
2646
- try {
2647
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2648
- var feeItem = _step2.value;
2649
- if (feeItem.fun.type === 'NonFungible') continue;
2650
- var plancks = feeItem.fun.value;
2651
- var tokenSymbol = getMultiLocationTokenId(feeItem.id, node);
2652
- if (!tokenSymbol || !plancks) continue;
2653
- deliveryFees.push({
2654
- plancks: plancks,
2655
- tokenSymbol: tokenSymbol
2656
- });
2657
- }
2658
- } catch (err) {
2659
- _iterator2.e(err);
2660
- } finally {
2661
- _iterator2.f();
2662
- }
2663
- }
2664
- }
2665
- } catch (err) {
2666
- _iterator.e(err);
2667
- } finally {
2668
- _iterator.f();
2733
+ if (!senderAddress) {
2734
+ throw new InvalidParameterError("Please provide senderAddress");
2669
2735
  }
2670
- var nativeAssetSymbol = getNativeAssetSymbol(node);
2671
- // Sum the fees that match the feeToken
2672
- var totalDeliveryFees = deliveryFees.filter(function (df) {
2673
- return df.tokenSymbol === nativeAssetSymbol;
2674
- }).reduce(function (acc, df) {
2675
- return acc + df.plancks;
2676
- }, 0n);
2677
- return totalDeliveryFees + executionFee;
2678
- };
2679
-
2680
- var getMultiLocationTokenIdPjs = function getMultiLocationTokenIdPjs(location, node) {
2681
- if (location.interior === 'Here') {
2682
- // native token
2683
- return getNativeAssetSymbol(node);
2736
+ if (isNodeEvm(origin) && !ahAddress) {
2737
+ throw new InvalidParameterError("Please provide ahAddress");
2684
2738
  }
2685
- var foreignAssets = getOtherAssets(node);
2686
- if (Object.keys(location.interior)[0] === 'X2') {
2687
- var junctions = Object.values(location.interior)[0];
2688
- if (Object.keys(junctions[0])[0] === 'PalletInstance' && junctions[0].PalletInstance === '50' && Object.keys(junctions[1])[0] === 'GeneralIndex') {
2689
- var _foreignAssets$find$s, _foreignAssets$find;
2690
- var assetId = junctions[1].GeneralIndex;
2691
- return (_foreignAssets$find$s = (_foreignAssets$find = foreignAssets.find(function (asset) {
2692
- return asset.assetId === String(assetId);
2693
- })) === null || _foreignAssets$find === void 0 ? void 0 : _foreignAssets$find.symbol) !== null && _foreignAssets$find$s !== void 0 ? _foreignAssets$find$s : null;
2694
- }
2739
+ var ethAsset = findAssetByMultiLocation(getOtherAssets('Ethereum'), asset.multiLocation);
2740
+ if (!ethAsset) {
2741
+ throw new InvalidCurrencyError("Could not obtain Ethereum asset address for ".concat(JSON.stringify(asset)));
2695
2742
  }
2696
- return null;
2697
- };
2698
-
2699
- var computeFeeFromDryRunPjs = function computeFeeFromDryRunPjs(dryRun, node, executionFee) {
2700
- // Extract delivery fees from emitted events
2701
- var deliveryFees = [];
2702
- var _iterator = _createForOfIteratorHelper(dryRun.Ok.emittedEvents),
2703
- _step;
2704
- try {
2705
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
2706
- var e = _step.value;
2707
- var isXcmEvent = e.section === 'xcmPallet' || e.section === 'polkadotXcm' || e.section === 'cumulusXcm';
2708
- var isFeesPaid = e.method === 'FeesPaid';
2709
- if (isXcmEvent && isFeesPaid && e.data.fees) {
2710
- var _iterator2 = _createForOfIteratorHelper(e.data.fees),
2711
- _step2;
2712
- try {
2713
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2714
- var feeItem = _step2.value;
2715
- if (feeItem.fun.NonFungible) continue;
2716
- var plancks = BigInt(feeItem.fun.Fungible.replace(/,/g, ''));
2717
- var tokenSymbol = getMultiLocationTokenIdPjs(feeItem.id, node);
2718
- if (!tokenSymbol || !plancks) continue;
2719
- deliveryFees.push({
2720
- plancks: plancks,
2721
- tokenSymbol: tokenSymbol
2722
- });
2743
+ var interiorSb = ethAsset.symbol === 'ETH' ? {
2744
+ Here: null
2745
+ } : {
2746
+ X1: [{
2747
+ AccountKey20: {
2748
+ network: null,
2749
+ key: ethAsset.assetId
2750
+ }
2751
+ }]
2752
+ };
2753
+ return _defineProperty({}, version, [{
2754
+ SetAppendix: [{
2755
+ DepositAsset: {
2756
+ assets: {
2757
+ Wild: 'All'
2758
+ },
2759
+ beneficiary: createBeneficiaryMultiLocation({
2760
+ api: api,
2761
+ scenario: scenario,
2762
+ pallet: 'PolkadotXcm',
2763
+ recipientAddress: isNodeEvm(origin) ? ahAddress : senderAddress,
2764
+ version: version
2765
+ })
2766
+ }
2767
+ }]
2768
+ }, {
2769
+ InitiateReserveWithdraw: {
2770
+ assets: {
2771
+ Wild: {
2772
+ AllOf: {
2773
+ id: asset.multiLocation,
2774
+ fun: 'Fungible'
2723
2775
  }
2724
- } catch (err) {
2725
- _iterator2.e(err);
2726
- } finally {
2727
- _iterator2.f();
2728
2776
  }
2729
- }
2730
- }
2731
- } catch (err) {
2732
- _iterator.e(err);
2733
- } finally {
2734
- _iterator.f();
2735
- }
2736
- var nativeAssetSymbol = getNativeAssetSymbol(node);
2737
- // Sum the fees that match the feeToken
2738
- var totalDeliveryFees = deliveryFees.filter(function (df) {
2739
- return df.tokenSymbol === nativeAssetSymbol;
2740
- }).reduce(function (acc, df) {
2741
- return acc + df.plancks;
2742
- }, 0n);
2743
- return totalDeliveryFees + executionFee;
2744
- };
2745
-
2746
- var resolveModuleError = function resolveModuleError(node, error) {
2747
- var palletDetails = getSupportedPalletsDetails(node).find(function (p) {
2748
- return p.index === Number(error.index);
2749
- });
2750
- if (!palletDetails) {
2751
- throw new Error("Pallet with index ".concat(error.index, " not found"));
2752
- }
2753
- // Use only the first byte of the error to get the error index
2754
- var errorIndex = Number(error.error.slice(0, 4));
2755
- var name = palletDetails.name;
2756
- if (name !== 'XTokens' && name !== 'PolkadotXcm' && name !== 'XcmPallet') {
2757
- throw new Error("Pallet ".concat(name, " is not supported"));
2758
- }
2759
- var failureReason = name === 'XTokens' ? Object.values(XTokensError)[errorIndex] : Object.values(PolkadotXcmError)[errorIndex];
2760
- if (!failureReason) {
2761
- throw new Error("Error index ".concat(errorIndex, " not found in ").concat(name, " pallet"));
2762
- }
2763
- return failureReason;
2764
- };
2765
-
2766
- var generateAddressMultiLocationV4 = function generateAddressMultiLocationV4(api, address) {
2767
- var isMultiLocation = _typeof(address) === 'object';
2768
- if (isMultiLocation) {
2769
- return _defineProperty({}, Version.V4, address);
2770
- }
2771
- var isEthAddress = ethers.isAddress(address);
2772
- return addXcmVersionHeader({
2773
- parents: Parents.ZERO,
2774
- interior: {
2775
- X1: [isEthAddress ? {
2776
- AccountKey20: {
2777
- key: address
2777
+ },
2778
+ reserve: {
2779
+ parents: Parents.TWO,
2780
+ interior: {
2781
+ X1: [ETHEREUM_JUNCTION]
2778
2782
  }
2779
- } : {
2780
- AccountId32: {
2781
- id: api.accountToHex(address),
2782
- network: null
2783
+ },
2784
+ xcm: [{
2785
+ BuyExecution: {
2786
+ fees: {
2787
+ id: {
2788
+ parents: Parents.ZERO,
2789
+ interior: interiorSb
2790
+ },
2791
+ fun: {
2792
+ Fungible: 1n
2793
+ }
2794
+ },
2795
+ weight_limit: 'Unlimited'
2796
+ }
2797
+ }, {
2798
+ DepositAsset: {
2799
+ assets: {
2800
+ Wild: {
2801
+ AllCounted: 1
2802
+ }
2803
+ },
2804
+ beneficiary: {
2805
+ parents: Parents.ZERO,
2806
+ interior: {
2807
+ X1: [{
2808
+ AccountKey20: {
2809
+ network: null,
2810
+ key: address
2811
+ }
2812
+ }]
2813
+ }
2814
+ }
2783
2815
  }
2816
+ }, {
2817
+ SetTopic: messageId
2784
2818
  }]
2785
2819
  }
2786
- }, Version.V4);
2820
+ }, {
2821
+ SetTopic: messageId
2822
+ }]);
2787
2823
  };
2788
2824
 
2789
- var getFees = function getFees(scenario) {
2790
- if (scenario === 'ParaToRelay') {
2791
- return 4600000000;
2792
- } else if (scenario === 'ParaToPara') {
2793
- return 399600000000;
2794
- }
2795
- throw new Error("Fees for scenario ".concat(scenario, " are not defined."));
2796
- };
2797
-
2798
- /**
2799
- * Retrieves the node instance for a given node.
2800
- *
2801
- * @param node - The node identifier.
2802
- * @returns The node instance
2803
- */
2804
- var getNode = function getNode(node) {
2805
- var nodeMap = nodes();
2806
- return nodeMap[node];
2807
- };
2808
-
2809
- var resolveParaId = function resolveParaId(paraId, destination) {
2810
- if (isTMultiLocation(destination) || isRelayChain(destination) || destination === 'Ethereum') {
2811
- return undefined;
2812
- }
2813
- return paraId !== null && paraId !== void 0 ? paraId : getParaId(destination);
2814
- };
2815
-
2816
- var validateAddress = function validateAddress(address, node) {
2817
- var isDestination = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
2818
- var isEvm = isNodeEvm(node);
2819
- var isEthereumAddress = ethers.isAddress(address);
2820
- if (isEvm) {
2821
- if (!isEthereumAddress) {
2822
- throw new InvalidAddressError("".concat(isDestination ? 'Destination node' : 'Node', " is an EVM chain, but the address provided is not a valid Ethereum address."));
2823
- }
2824
- } else {
2825
- if (isEthereumAddress) {
2826
- throw new InvalidAddressError("EVM address provided but ".concat(isDestination ? 'destination ' : '', "node is not an EVM chain."));
2827
- }
2828
- }
2829
- };
2830
-
2831
- // Contains important call creation utils (Selection of fees,formating of header and more.. )
2832
- /**
2833
- * Determines the relay chain for a given node.
2834
- *
2835
- * @param node - The node for which to determine the relay chain.
2836
- * @returns 'Kusama' if the node's relay chain symbol is 'KSM'; otherwise, 'Polkadot'.
2837
- */
2838
- var determineRelayChain = function determineRelayChain(node) {
2839
- return getRelayChainSymbol(node) === 'KSM' ? 'Kusama' : 'Polkadot';
2840
- };
2841
-
2842
- var buildMultiLocation = function buildMultiLocation(_ref) {
2843
- var paraIdTo = _ref.paraIdTo,
2844
- asset = _ref.asset,
2845
- origin = _ref.origin,
2846
- destination = _ref.destination;
2847
- if (!isForeignAsset(asset)) {
2848
- if (_typeof(destination) === 'object') {
2849
- return destination;
2850
- }
2851
- // ParaToRelay scenario
2852
- if (isRelayChain(destination)) {
2853
- return DOT_MULTILOCATION;
2854
- }
2855
- // If it is a native asset, search by symbol on AssetHub and use the multiLocation from there
2856
- var assetHubAsset = getOtherAssets(destination).find(function (ahAsset) {
2857
- var _ahAsset$symbol, _asset$symbol;
2858
- return ((_ahAsset$symbol = ahAsset.symbol) === null || _ahAsset$symbol === void 0 ? void 0 : _ahAsset$symbol.toLowerCase()) === ((_asset$symbol = asset.symbol) === null || _asset$symbol === void 0 ? void 0 : _asset$symbol.toLowerCase());
2859
- });
2860
- if (assetHubAsset === undefined) {
2861
- throw new InvalidCurrencyError("Asset ".concat(asset.symbol, " not found in AssetHub"));
2862
- }
2863
- if (assetHubAsset.multiLocation) {
2864
- return assetHubAsset.multiLocation;
2865
- }
2866
- throw new InvalidCurrencyError("Asset ".concat(asset.symbol, " has no multiLocation"));
2867
- }
2868
- var createDefaultMultiLocation = function createDefaultMultiLocation(assetId) {
2869
- return {
2870
- parents: Parents.ONE,
2871
- interior: {
2872
- X3: [{
2873
- Parachain: paraIdTo
2874
- }, {
2875
- PalletInstance: '50'
2876
- }, {
2877
- GeneralIndex: BigInt(assetId)
2878
- }]
2879
- }
2880
- };
2881
- };
2882
- var isBifrostOrigin = origin === 'BifrostPolkadot' || origin === 'BifrostKusama';
2883
- if (isBifrostOrigin) {
2884
- return createDefaultMultiLocation(asset.assetId);
2885
- }
2886
- if (asset.multiLocation) {
2887
- return asset.multiLocation;
2888
- } else {
2889
- return createDefaultMultiLocation(asset.assetId);
2890
- }
2891
- };
2892
- var getModifiedCurrencySelection = function getModifiedCurrencySelection(version, input) {
2893
- var amount = input.asset.amount,
2894
- overriddenAsset = input.overriddenAsset;
2895
- if (overriddenAsset) {
2896
- return addXcmVersionHeader(maybeOverrideMultiAssets(version, amount, [], overriddenAsset), version);
2897
- }
2898
- var multiLocation = buildMultiLocation(input);
2899
- var multiAsset = createMultiAsset(version, amount, multiLocation);
2900
- return addXcmVersionHeader(multiAsset, version);
2901
- };
2902
-
2903
- var getCurrencySelection = function getCurrencySelection(input, useMultiAssets, currencySelection) {
2904
- var origin = input.origin;
2905
- var _getNode = getNode(origin),
2906
- version = _getNode.version;
2907
- if (useMultiAssets) {
2908
- return getModifiedCurrencySelection(version, input);
2909
- }
2910
- return currencySelection;
2911
- };
2912
-
2913
- var getXTokensParameters = function getXTokensParameters(isMultiAssetTransfer, currencySelection, addressSelection, amount, fees, overriddenAsset) {
2914
- if (isMultiAssetTransfer) {
2915
- var isOverridenMultiAssets = overriddenAsset && !isTMultiLocation(overriddenAsset);
2916
- var feeAssetIndex = isOverridenMultiAssets ? overriddenAsset.findIndex(function (asset) {
2917
- return asset.isFeeAsset;
2918
- }) : undefined;
2919
- return _objectSpread2(_objectSpread2(_defineProperty({}, isOverridenMultiAssets ? 'assets' : 'asset', currencySelection), isOverridenMultiAssets && {
2920
- fee_item: feeAssetIndex
2921
- }), {}, {
2922
- dest: addressSelection,
2923
- dest_weight_limit: fees
2924
- });
2925
- }
2926
- return {
2927
- currency_id: currencySelection,
2928
- amount: BigInt(amount),
2929
- dest: addressSelection,
2930
- dest_weight_limit: fees
2931
- };
2932
- };
2933
-
2934
- var XTokensTransferImpl = /*#__PURE__*/function () {
2935
- function XTokensTransferImpl() {
2936
- _classCallCheck(this, XTokensTransferImpl);
2937
- }
2938
- return _createClass(XTokensTransferImpl, null, [{
2939
- key: "transferXTokens",
2940
- value: function transferXTokens(input, currencySelection) {
2941
- var fees = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'Unlimited';
2942
- var api = input.api,
2943
- origin = input.origin,
2944
- asset = input.asset,
2945
- addressSelection = input.addressSelection,
2946
- destination = input.destination,
2947
- scenario = input.scenario,
2948
- overriddenAsset = input.overriddenAsset,
2949
- pallet = input.pallet,
2950
- method = input.method,
2951
- _input$useMultiAssetT = input.useMultiAssetTransfer,
2952
- useMultiAssetTransfer = _input$useMultiAssetT === void 0 ? false : _input$useMultiAssetT;
2953
- var isMultiLocationDestination = _typeof(destination) === 'object';
2954
- if (isMultiLocationDestination) {
2955
- throw new Error('Multilocation destinations are not supported for specific transfer you are trying to create. In special cases such as xTokens or xTransfer pallet try using address multilocation instead (for both destination and address in same multilocation set (eg. X2 - Parachain, Address). For further assistance please open issue in our repository.');
2956
- }
2957
- var isBifrostOrigin = origin === 'BifrostPolkadot' || origin === 'BifrostKusama';
2958
- var isAssetHubDest = destination === 'AssetHubPolkadot' || destination === 'AssetHubKusama';
2959
- var isAstarOrShidenToRelay = scenario === 'ParaToRelay' && (origin === 'Astar' || origin === 'Shiden');
2960
- var isOverridenMultiAssets = overriddenAsset && !isTMultiLocation(overriddenAsset);
2961
- var shouldUseMultiasset = useMultiAssetTransfer || isAstarOrShidenToRelay || isAssetHubDest && !isBifrostOrigin || !!isOverridenMultiAssets;
2962
- var modifiedCurrencySelection = getCurrencySelection(input, shouldUseMultiasset, currencySelection);
2963
- var section = shouldUseMultiasset ? isOverridenMultiAssets ? 'transfer_multiassets' : 'transfer_multiasset' : 'transfer';
2964
- var parameters = getXTokensParameters(shouldUseMultiasset, modifiedCurrencySelection, addressSelection, asset.amount, fees, overriddenAsset);
2965
- var call = {
2966
- module: pallet !== null && pallet !== void 0 ? pallet : 'XTokens',
2967
- section: method !== null && method !== void 0 ? method : section,
2968
- parameters: parameters
2969
- };
2970
- return api.callTxMethod(call);
2971
- }
2972
- }]);
2973
- }();
2974
-
2975
- var getBridgeStatus = /*#__PURE__*/function () {
2976
- var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(api) {
2825
+ var generateMessageId = /*#__PURE__*/function () {
2826
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(api, senderAddress, sourceParaId, tokenAddress, recipientAddress, amount) {
2827
+ var accountNextId, sourceAccountHex, entropy;
2977
2828
  return _regeneratorRuntime().wrap(function _callee$(_context) {
2978
2829
  while (1) switch (_context.prev = _context.next) {
2979
2830
  case 0:
2980
2831
  _context.next = 2;
2981
- return api.init('BridgeHubPolkadot');
2832
+ return api.getFromRpc('system', 'accountNextIndex', senderAddress);
2982
2833
  case 2:
2983
- _context.prev = 2;
2984
- _context.next = 5;
2985
- return api.getBridgeStatus();
2986
- case 5:
2987
- return _context.abrupt("return", _context.sent);
2834
+ accountNextId = _context.sent;
2835
+ sourceAccountHex = api.accountToHex(senderAddress);
2836
+ entropy = new Uint8Array([].concat(_toConsumableArray(api.stringToUint8a(sourceParaId.toString())), _toConsumableArray(api.hexToUint8a(sourceAccountHex)), _toConsumableArray(api.stringToUint8a(accountNextId)), _toConsumableArray(api.hexToUint8a(tokenAddress)), _toConsumableArray(api.stringToUint8a(recipientAddress)), _toConsumableArray(api.stringToUint8a(amount.toString()))));
2837
+ return _context.abrupt("return", api.blake2AsHex(entropy));
2988
2838
  case 6:
2989
- _context.prev = 6;
2990
- _context.next = 9;
2991
- return api.disconnect();
2992
- case 9:
2993
- return _context.finish(6);
2994
- case 10:
2995
2839
  case "end":
2996
2840
  return _context.stop();
2997
2841
  }
2998
- }, _callee, null, [[2,, 6, 10]]);
2842
+ }, _callee);
2999
2843
  }));
3000
- return function getBridgeStatus(_x) {
2844
+ return function generateMessageId(_x, _x2, _x3, _x4, _x5, _x6) {
3001
2845
  return _ref.apply(this, arguments);
3002
2846
  };
3003
2847
  }();
3004
2848
 
3005
- var createCustomXcmOnDest = function createCustomXcmOnDest(_ref, origin, version, messageId) {
3006
- var api = _ref.api,
3007
- address = _ref.address,
3008
- asset = _ref.asset,
3009
- scenario = _ref.scenario,
3010
- senderAddress = _ref.senderAddress,
3011
- ahAddress = _ref.ahAddress;
3012
- if (!isForeignAsset(asset)) {
3013
- throw new InvalidCurrencyError("Asset ".concat(JSON.stringify(asset), " is not a foreign asset"));
3014
- }
3015
- if (!asset.multiLocation) {
3016
- throw new InvalidCurrencyError("Asset ".concat(JSON.stringify(asset), " has no multiLocation"));
3017
- }
3018
- if (!senderAddress) {
3019
- throw new InvalidParameterError("Please provide senderAddress");
3020
- }
3021
- if (isNodeEvm(origin) && !ahAddress) {
3022
- throw new InvalidParameterError("Please provide ahAddress");
2849
+ var resolveParaId = function resolveParaId(paraId, destination) {
2850
+ if (isTMultiLocation(destination) || isRelayChain(destination) || destination === 'Ethereum') {
2851
+ return undefined;
3023
2852
  }
3024
- var ethAsset = findAssetByMultiLocation(getOtherAssets('Ethereum'), asset.multiLocation);
3025
- if (!ethAsset) {
3026
- throw new InvalidCurrencyError("Could not obtain Ethereum asset address for ".concat(JSON.stringify(asset)));
3027
- }
3028
- var interiorSb = ethAsset.symbol === 'ETH' ? {
3029
- Here: null
3030
- } : {
3031
- X1: [{
3032
- AccountKey20: {
3033
- network: null,
3034
- key: ethAsset.assetId
3035
- }
3036
- }]
3037
- };
3038
- return _defineProperty({}, version, [{
3039
- SetAppendix: [{
3040
- DepositAsset: {
3041
- assets: {
3042
- Wild: 'All'
3043
- },
3044
- beneficiary: createBeneficiaryMultiLocation({
3045
- api: api,
3046
- scenario: scenario,
3047
- pallet: 'PolkadotXcm',
3048
- recipientAddress: isNodeEvm(origin) ? ahAddress : senderAddress,
3049
- version: version
3050
- })
3051
- }
3052
- }]
3053
- }, {
3054
- InitiateReserveWithdraw: {
3055
- assets: {
3056
- Wild: {
3057
- AllOf: {
3058
- id: asset.multiLocation,
3059
- fun: 'Fungible'
3060
- }
3061
- }
3062
- },
3063
- reserve: {
3064
- parents: Parents.TWO,
3065
- interior: {
3066
- X1: [ETHEREUM_JUNCTION]
3067
- }
3068
- },
3069
- xcm: [{
3070
- BuyExecution: {
3071
- fees: {
3072
- id: {
3073
- parents: Parents.ZERO,
3074
- interior: interiorSb
3075
- },
3076
- fun: {
3077
- Fungible: 1n
3078
- }
3079
- },
3080
- weight_limit: 'Unlimited'
3081
- }
3082
- }, {
3083
- DepositAsset: {
3084
- assets: {
3085
- Wild: {
3086
- AllCounted: 1
3087
- }
3088
- },
3089
- beneficiary: {
3090
- parents: Parents.ZERO,
3091
- interior: {
3092
- X1: [{
3093
- AccountKey20: {
3094
- network: null,
3095
- key: address
3096
- }
3097
- }]
3098
- }
3099
- }
3100
- }
3101
- }, {
3102
- SetTopic: messageId
3103
- }]
3104
- }
3105
- }, {
3106
- SetTopic: messageId
3107
- }]);
3108
- };
3109
-
3110
- var generateMessageId = /*#__PURE__*/function () {
3111
- var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(api, senderAddress, sourceParaId, tokenAddress, recipientAddress, amount) {
3112
- var accountNextId, sourceAccountHex, entropy;
3113
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3114
- while (1) switch (_context.prev = _context.next) {
3115
- case 0:
3116
- _context.next = 2;
3117
- return api.getFromRpc('system', 'accountNextIndex', senderAddress);
3118
- case 2:
3119
- accountNextId = _context.sent;
3120
- sourceAccountHex = api.accountToHex(senderAddress);
3121
- entropy = new Uint8Array([].concat(_toConsumableArray(api.stringToUint8a(sourceParaId.toString())), _toConsumableArray(api.hexToUint8a(sourceAccountHex)), _toConsumableArray(api.stringToUint8a(accountNextId)), _toConsumableArray(api.hexToUint8a(tokenAddress)), _toConsumableArray(api.stringToUint8a(recipientAddress)), _toConsumableArray(api.stringToUint8a(amount.toString()))));
3122
- return _context.abrupt("return", api.blake2AsHex(entropy));
3123
- case 6:
3124
- case "end":
3125
- return _context.stop();
3126
- }
3127
- }, _callee);
3128
- }));
3129
- return function generateMessageId(_x, _x2, _x3, _x4, _x5, _x6) {
3130
- return _ref.apply(this, arguments);
3131
- };
3132
- }();
3133
-
3134
- var supportsXTokens = function supportsXTokens(obj) {
3135
- return _typeof(obj) === 'object' && obj !== null && 'transferXTokens' in obj;
3136
- };
3137
- var supportsXTransfer = function supportsXTransfer(obj) {
3138
- return _typeof(obj) === 'object' && obj !== null && 'transferXTransfer' in obj;
3139
- };
3140
- var supportsPolkadotXCM = function supportsPolkadotXCM(obj) {
3141
- return _typeof(obj) === 'object' && obj !== null && 'transferPolkadotXCM' in obj;
3142
- };
3143
- var ParachainNode = /*#__PURE__*/function () {
3144
- function ParachainNode(node, info, type, version) {
3145
- _classCallCheck(this, ParachainNode);
3146
- this._assetCheckEnabled = true;
3147
- this._info = info;
3148
- this._type = type;
3149
- this._node = node;
3150
- this._version = version;
2853
+ return paraId !== null && paraId !== void 0 ? paraId : getParaId(destination);
2854
+ };
2855
+
2856
+ var supportsXTokens = function supportsXTokens(obj) {
2857
+ return _typeof(obj) === 'object' && obj !== null && 'transferXTokens' in obj;
2858
+ };
2859
+ var supportsXTransfer = function supportsXTransfer(obj) {
2860
+ return _typeof(obj) === 'object' && obj !== null && 'transferXTransfer' in obj;
2861
+ };
2862
+ var supportsPolkadotXCM = function supportsPolkadotXCM(obj) {
2863
+ return _typeof(obj) === 'object' && obj !== null && 'transferPolkadotXCM' in obj;
2864
+ };
2865
+ var ParachainNode = /*#__PURE__*/function () {
2866
+ function ParachainNode(node, info, type, version) {
2867
+ _classCallCheck(this, ParachainNode);
2868
+ this._assetCheckEnabled = true;
2869
+ this._info = info;
2870
+ this._type = type;
2871
+ this._node = node;
2872
+ this._version = version;
3151
2873
  }
3152
2874
  return _createClass(ParachainNode, [{
3153
2875
  key: "info",
@@ -3456,17 +3178,17 @@ var ParachainNode = /*#__PURE__*/function () {
3456
3178
  return Builder(api.clone()).from('AssetHubPolkadot').to(destination).currency({
3457
3179
  symbol: 'DOT',
3458
3180
  amount: AH_EXECUTION_FEE_PADDED
3459
- }).address(address).dryRun(senderAddress);
3181
+ }).address(address).senderAddress(senderAddress).dryRun();
3460
3182
  case 12:
3461
3183
  dryRunResult = _context2.sent;
3462
- if (dryRunResult.success) {
3184
+ if (dryRunResult.origin.success) {
3463
3185
  _context2.next = 15;
3464
3186
  break;
3465
3187
  }
3466
- throw new DryRunFailedError(dryRunResult.failureReason);
3188
+ throw new DryRunFailedError(dryRunResult.origin.failureReason);
3467
3189
  case 15:
3468
3190
  // Pad fee by 50%
3469
- dryRunFeePadded = BigInt(dryRunResult.fee) * BigInt(3) / BigInt(2);
3191
+ dryRunFeePadded = BigInt(dryRunResult.origin.fee) * BigInt(3) / BigInt(2);
3470
3192
  destWithHeader = createVersionedDestination(scenario, version, destination, paraIdTo);
3471
3193
  _extractVersionFromHe = extractVersionFromHeader(destWithHeader), _extractVersionFromHe2 = _slicedToArray(_extractVersionFromHe, 2), _extractVersionFromHe2[0], dest = _extractVersionFromHe2[1];
3472
3194
  call = {
@@ -3957,6 +3679,12 @@ var AssetHubKusama = /*#__PURE__*/function (_ParachainNode) {
3957
3679
  }]);
3958
3680
  }(ParachainNode);
3959
3681
 
3682
+ var createVersionedBeneficiary = function createVersionedBeneficiary(options) {
3683
+ var version = options.version;
3684
+ var multiLocation = createBeneficiaryMultiLocation(options);
3685
+ return addXcmVersionHeader(multiLocation, version);
3686
+ };
3687
+
3960
3688
  var createExecuteXcm = function createExecuteXcm(input, weight, executionFee) {
3961
3689
  var api = input.api,
3962
3690
  _input$version = input.version,
@@ -4056,6 +3784,44 @@ var createExecuteXcm = function createExecuteXcm(input, weight, executionFee) {
4056
3784
  return api.callTxMethod(call);
4057
3785
  };
4058
3786
 
3787
+ var generateAddressMultiLocationV4 = function generateAddressMultiLocationV4(api, address) {
3788
+ var isMultiLocation = _typeof(address) === 'object';
3789
+ if (isMultiLocation) {
3790
+ return _defineProperty({}, Version.V4, address);
3791
+ }
3792
+ var isEthAddress = ethers.isAddress(address);
3793
+ return addXcmVersionHeader({
3794
+ parents: Parents.ZERO,
3795
+ interior: {
3796
+ X1: [isEthAddress ? {
3797
+ AccountKey20: {
3798
+ key: address
3799
+ }
3800
+ } : {
3801
+ AccountId32: {
3802
+ id: api.accountToHex(address),
3803
+ network: null
3804
+ }
3805
+ }]
3806
+ }
3807
+ }, Version.V4);
3808
+ };
3809
+
3810
+ var validateAddress = function validateAddress(address, node) {
3811
+ var isDestination = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
3812
+ var isEvm = isNodeEvm(node);
3813
+ var isEthereumAddress = ethers.isAddress(address);
3814
+ if (isEvm) {
3815
+ if (!isEthereumAddress) {
3816
+ throw new InvalidAddressError("".concat(isDestination ? 'Destination node' : 'Node', " is an EVM chain, but the address provided is not a valid Ethereum address."));
3817
+ }
3818
+ } else {
3819
+ if (isEthereumAddress) {
3820
+ throw new InvalidAddressError("EVM address provided but ".concat(isDestination ? 'destination ' : '', "node is not an EVM chain."));
3821
+ }
3822
+ }
3823
+ };
3824
+
4059
3825
  var createCustomXcmToBifrost = function createCustomXcmToBifrost(_ref, version) {
4060
3826
  var api = _ref.api,
4061
3827
  address = _ref.address,
@@ -6550,7 +6316,618 @@ var nodes = function nodes() {
6550
6316
  Peaq: new Peaq(),
6551
6317
  Polimec: new Polimec()
6552
6318
  };
6553
- };
6319
+ };
6320
+
6321
+ /**
6322
+ * Retrieves the parachain ID for a specified node.
6323
+ *
6324
+ * @param node - The node for which to get the paraId.
6325
+ * @returns The parachain ID of the node.
6326
+ */
6327
+ var getParaId = function getParaId(node) {
6328
+ if (node === 'Ethereum') {
6329
+ return ETH_PARA_ID;
6330
+ }
6331
+ return getNodeConfig(node).paraId;
6332
+ };
6333
+
6334
+ var shuffleArray = function shuffleArray(array) {
6335
+ var copy = _toConsumableArray(array);
6336
+ for (var i = copy.length - 1; i > 0; i--) {
6337
+ var j = Math.floor(Math.random() * (i + 1));
6338
+ var _ref = [copy[j], copy[i]];
6339
+ copy[i] = _ref[0];
6340
+ copy[j] = _ref[1];
6341
+ }
6342
+ return copy;
6343
+ };
6344
+
6345
+ var shuffleWsProviders = function shuffleWsProviders(node, wsProviders) {
6346
+ var ALLOWED_NODES = ['Hydration', 'Acala'];
6347
+ if (ALLOWED_NODES.includes(node)) {
6348
+ return shuffleArray(wsProviders);
6349
+ }
6350
+ return wsProviders;
6351
+ };
6352
+
6353
+ var createApiInstanceForNode = /*#__PURE__*/function () {
6354
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(api, node) {
6355
+ var wsUrl, resolvedWsUrl;
6356
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
6357
+ while (1) switch (_context.prev = _context.next) {
6358
+ case 0:
6359
+ wsUrl = getNodeProviders(node);
6360
+ resolvedWsUrl = Array.isArray(wsUrl) ? shuffleWsProviders(node, wsUrl) : wsUrl;
6361
+ return _context.abrupt("return", api.createApiInstance(resolvedWsUrl));
6362
+ case 3:
6363
+ case "end":
6364
+ return _context.stop();
6365
+ }
6366
+ }, _callee);
6367
+ }));
6368
+ return function createApiInstanceForNode(_x, _x2) {
6369
+ return _ref.apply(this, arguments);
6370
+ };
6371
+ }();
6372
+
6373
+ var getMultiLocationTokenId = function getMultiLocationTokenId(location, node) {
6374
+ if (location.interior.type === 'Here') {
6375
+ // native token
6376
+ return getNativeAssetSymbol(node);
6377
+ }
6378
+ var foreignAssets = getOtherAssets(node);
6379
+ if (location.interior.type === 'X2') {
6380
+ if (location.interior.value[0].type === 'PalletInstance' && location.interior.value[0].value === 50 && location.interior.value[1].type === 'GeneralIndex') {
6381
+ var _foreignAssets$find$a, _foreignAssets$find;
6382
+ var assetId = location.interior.value[1].value;
6383
+ return (_foreignAssets$find$a = (_foreignAssets$find = foreignAssets.find(function (asset) {
6384
+ return asset.assetId === String(assetId);
6385
+ })) === null || _foreignAssets$find === void 0 ? void 0 : _foreignAssets$find.assetId) !== null && _foreignAssets$find$a !== void 0 ? _foreignAssets$find$a : null;
6386
+ }
6387
+ }
6388
+ return null;
6389
+ };
6390
+
6391
+ var computeFeeFromDryRun = function computeFeeFromDryRun(dryRun, node, executionFee) {
6392
+ // Extract delivery fees from emitted events
6393
+ var deliveryFees = [];
6394
+ var _iterator = _createForOfIteratorHelper(dryRun.value.emitted_events),
6395
+ _step;
6396
+ try {
6397
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
6398
+ var e = _step.value;
6399
+ var isXcmEvent = e.type === 'XcmPallet' || e.type === 'PolkadotXcm' || e.type === 'CumulusXcm';
6400
+ var isFeesPaid = e.value.type === 'FeesPaid';
6401
+ if (isXcmEvent && isFeesPaid && e.value.value.fees) {
6402
+ var _iterator2 = _createForOfIteratorHelper(e.value.value.fees),
6403
+ _step2;
6404
+ try {
6405
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
6406
+ var feeItem = _step2.value;
6407
+ if (feeItem.fun.type === 'NonFungible') continue;
6408
+ var plancks = feeItem.fun.value;
6409
+ var tokenSymbol = getMultiLocationTokenId(feeItem.id, node);
6410
+ if (!tokenSymbol || !plancks) continue;
6411
+ deliveryFees.push({
6412
+ plancks: plancks,
6413
+ tokenSymbol: tokenSymbol
6414
+ });
6415
+ }
6416
+ } catch (err) {
6417
+ _iterator2.e(err);
6418
+ } finally {
6419
+ _iterator2.f();
6420
+ }
6421
+ }
6422
+ }
6423
+ } catch (err) {
6424
+ _iterator.e(err);
6425
+ } finally {
6426
+ _iterator.f();
6427
+ }
6428
+ var nativeAssetSymbol = getNativeAssetSymbol(node);
6429
+ // Sum the fees that match the feeToken
6430
+ var totalDeliveryFees = deliveryFees.filter(function (df) {
6431
+ return df.tokenSymbol === nativeAssetSymbol;
6432
+ }).reduce(function (acc, df) {
6433
+ return acc + df.plancks;
6434
+ }, 0n);
6435
+ return totalDeliveryFees + executionFee;
6436
+ };
6437
+
6438
+ var getMultiLocationTokenIdPjs = function getMultiLocationTokenIdPjs(location, node) {
6439
+ if (location.interior === 'Here') {
6440
+ // native token
6441
+ return getNativeAssetSymbol(node);
6442
+ }
6443
+ var foreignAssets = getOtherAssets(node);
6444
+ if (Object.keys(location.interior)[0] === 'X2') {
6445
+ var junctions = Object.values(location.interior)[0];
6446
+ if (Object.keys(junctions[0])[0] === 'PalletInstance' && junctions[0].PalletInstance === '50' && Object.keys(junctions[1])[0] === 'GeneralIndex') {
6447
+ var _foreignAssets$find$s, _foreignAssets$find;
6448
+ var assetId = junctions[1].GeneralIndex;
6449
+ return (_foreignAssets$find$s = (_foreignAssets$find = foreignAssets.find(function (asset) {
6450
+ return asset.assetId === String(assetId);
6451
+ })) === null || _foreignAssets$find === void 0 ? void 0 : _foreignAssets$find.symbol) !== null && _foreignAssets$find$s !== void 0 ? _foreignAssets$find$s : null;
6452
+ }
6453
+ }
6454
+ return null;
6455
+ };
6456
+
6457
+ var computeFeeFromDryRunPjs = function computeFeeFromDryRunPjs(dryRun, node, executionFee) {
6458
+ // Extract delivery fees from emitted events
6459
+ var deliveryFees = [];
6460
+ var _iterator = _createForOfIteratorHelper(dryRun.Ok.emittedEvents),
6461
+ _step;
6462
+ try {
6463
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
6464
+ var e = _step.value;
6465
+ var isXcmEvent = e.section === 'xcmPallet' || e.section === 'polkadotXcm' || e.section === 'cumulusXcm';
6466
+ var isFeesPaid = e.method === 'FeesPaid';
6467
+ if (isXcmEvent && isFeesPaid && e.data.fees) {
6468
+ var _iterator2 = _createForOfIteratorHelper(e.data.fees),
6469
+ _step2;
6470
+ try {
6471
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
6472
+ var feeItem = _step2.value;
6473
+ if (feeItem.fun.NonFungible) continue;
6474
+ var plancks = BigInt(feeItem.fun.Fungible.replace(/,/g, ''));
6475
+ var tokenSymbol = getMultiLocationTokenIdPjs(feeItem.id, node);
6476
+ if (!tokenSymbol || !plancks) continue;
6477
+ deliveryFees.push({
6478
+ plancks: plancks,
6479
+ tokenSymbol: tokenSymbol
6480
+ });
6481
+ }
6482
+ } catch (err) {
6483
+ _iterator2.e(err);
6484
+ } finally {
6485
+ _iterator2.f();
6486
+ }
6487
+ }
6488
+ }
6489
+ } catch (err) {
6490
+ _iterator.e(err);
6491
+ } finally {
6492
+ _iterator.f();
6493
+ }
6494
+ var nativeAssetSymbol = getNativeAssetSymbol(node);
6495
+ // Sum the fees that match the feeToken
6496
+ var totalDeliveryFees = deliveryFees.filter(function (df) {
6497
+ return df.tokenSymbol === nativeAssetSymbol;
6498
+ }).reduce(function (acc, df) {
6499
+ return acc + df.plancks;
6500
+ }, 0n);
6501
+ return totalDeliveryFees + executionFee;
6502
+ };
6503
+
6504
+ var resolveModuleError = function resolveModuleError(node, error) {
6505
+ var palletDetails = getSupportedPalletsDetails(node).find(function (p) {
6506
+ return p.index === Number(error.index);
6507
+ });
6508
+ if (!palletDetails) {
6509
+ throw new Error("Pallet with index ".concat(error.index, " not found"));
6510
+ }
6511
+ // Use only the first byte of the error to get the error index
6512
+ var errorIndex = Number(error.error.slice(0, 4));
6513
+ var name = palletDetails.name;
6514
+ if (name !== 'XTokens' && name !== 'PolkadotXcm' && name !== 'XcmPallet') {
6515
+ throw new Error("Pallet ".concat(name, " is not supported"));
6516
+ }
6517
+ var failureReason = name === 'XTokens' ? Object.values(XTokensError)[errorIndex] : Object.values(PolkadotXcmError)[errorIndex];
6518
+ if (!failureReason) {
6519
+ throw new Error("Error index ".concat(errorIndex, " not found in ").concat(name, " pallet"));
6520
+ }
6521
+ return failureReason;
6522
+ };
6523
+
6524
+ var getFees = function getFees(scenario) {
6525
+ if (scenario === 'ParaToRelay') {
6526
+ return 4600000000;
6527
+ } else if (scenario === 'ParaToPara') {
6528
+ return 399600000000;
6529
+ }
6530
+ throw new Error("Fees for scenario ".concat(scenario, " are not defined."));
6531
+ };
6532
+
6533
+ /**
6534
+ * Retrieves the node instance for a given node.
6535
+ *
6536
+ * @param node - The node identifier.
6537
+ * @returns The node instance
6538
+ */
6539
+ var getNode = function getNode(node) {
6540
+ var nodeMap = nodes();
6541
+ return nodeMap[node];
6542
+ };
6543
+
6544
+ // Contains important call creation utils (Selection of fees,formating of header and more.. )
6545
+ /**
6546
+ * Determines the relay chain for a given node.
6547
+ *
6548
+ * @param node - The node for which to determine the relay chain.
6549
+ * @returns 'Kusama' if the node's relay chain symbol is 'KSM'; otherwise, 'Polkadot'.
6550
+ */
6551
+ var determineRelayChain = function determineRelayChain(node) {
6552
+ return getRelayChainSymbol(node) === 'KSM' ? 'Kusama' : 'Polkadot';
6553
+ };
6554
+
6555
+ /**
6556
+ * Retrieves the node name corresponding to a specified parachain ID.
6557
+ *
6558
+ * @param paraId - The parachain ID.
6559
+ * @returns The node name if found; otherwise, null.
6560
+ */
6561
+ var getTNode = function getTNode(paraId, ecosystem) {
6562
+ var _NODE_NAMES_DOT_KSM$f;
6563
+ if (paraId === 0) {
6564
+ return ecosystem === 'polkadot' ? 'Polkadot' : 'Kusama';
6565
+ }
6566
+ if (paraId === 1) {
6567
+ return 'Ethereum';
6568
+ }
6569
+ return (_NODE_NAMES_DOT_KSM$f = NODE_NAMES_DOT_KSM.find(function (nodeName) {
6570
+ return getNode(nodeName).type === ecosystem && getParaId(nodeName) === paraId;
6571
+ })) !== null && _NODE_NAMES_DOT_KSM$f !== void 0 ? _NODE_NAMES_DOT_KSM$f : null;
6572
+ };
6573
+
6574
+ var isAssetHub = function isAssetHub(chain) {
6575
+ return chain === 'AssetHubPolkadot' || chain === 'AssetHubKusama';
6576
+ };
6577
+ var isBridgeHub = function isBridgeHub(chain) {
6578
+ return chain === 'BridgeHubPolkadot' || chain === 'BridgeHubKusama';
6579
+ };
6580
+ var isPeople = function isPeople(chain) {
6581
+ return chain === 'PeoplePolkadot' || chain === 'PeopleKusama';
6582
+ };
6583
+ var isSystemPara = function isSystemPara(chain) {
6584
+ return isAssetHub(chain) || isBridgeHub(chain) || isPeople(chain);
6585
+ };
6586
+ var mul = function mul(v, num) {
6587
+ var den = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1n;
6588
+ return v * num / den;
6589
+ };
6590
+ var padFee = function padFee(raw, origin, dest, side) {
6591
+ var relayOrigin = isRelayChain(origin);
6592
+ var relayDest = isRelayChain(dest);
6593
+ var sysParaOrigin = isSystemPara(origin);
6594
+ var sysParaDest = isSystemPara(dest);
6595
+ var relayToPara = relayOrigin && !relayDest;
6596
+ var sysParaToPara = sysParaOrigin && !sysParaDest;
6597
+ var paraToPara = !relayOrigin && !sysParaOrigin;
6598
+ if (sysParaToPara) return raw * 40n;
6599
+ if (relayToPara) return side === 'origin' ? mul(raw, 320n, 100n) : mul(raw, 3000n, 100n);
6600
+ if (paraToPara) return mul(raw, 130n, 100n);
6601
+ // apply default 30% padding
6602
+ return mul(raw, 130n, 100n);
6603
+ };
6604
+
6605
+ var createOriginLocation = function createOriginLocation(origin, destination) {
6606
+ if (isRelayChain(origin)) return DOT_MULTILOCATION;
6607
+ return {
6608
+ parents: isRelayChain(destination) ? Parents.ZERO : Parents.ONE,
6609
+ interior: {
6610
+ X1: [{
6611
+ Parachain: getParaId(origin)
6612
+ }]
6613
+ }
6614
+ };
6615
+ };
6616
+ var getFeeForDestNode = /*#__PURE__*/function () {
6617
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref) {
6618
+ var api, forwardedXcms, origin, destination, address, senderAddress, currency, disableFallback, calcPaymentInfoFee, dryRunResult, fee, newForwardedXcms, destParaId;
6619
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
6620
+ while (1) switch (_context2.prev = _context2.next) {
6621
+ case 0:
6622
+ api = _ref.api, forwardedXcms = _ref.forwardedXcms, origin = _ref.origin, destination = _ref.destination, address = _ref.address, senderAddress = _ref.senderAddress, currency = _ref.currency, disableFallback = _ref.disableFallback;
6623
+ calcPaymentInfoFee = /*#__PURE__*/function () {
6624
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
6625
+ var originAsset, currencyInput, tx, rawFee;
6626
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
6627
+ while (1) switch (_context.prev = _context.next) {
6628
+ case 0:
6629
+ if (!('multiasset' in currency)) {
6630
+ _context.next = 2;
6631
+ break;
6632
+ }
6633
+ throw new InvalidCurrencyError('Multi-assets are not yet supported for XCM fee calculation.');
6634
+ case 2:
6635
+ originAsset = findAsset(origin, currency, destination);
6636
+ if (originAsset) {
6637
+ _context.next = 5;
6638
+ break;
6639
+ }
6640
+ throw new InvalidCurrencyError("Currency ".concat(JSON.stringify(currency), " not found in ").concat(origin));
6641
+ case 5:
6642
+ currencyInput = originAsset.multiLocation ? {
6643
+ multilocation: originAsset.multiLocation
6644
+ } : {
6645
+ symbol: originAsset.symbol
6646
+ };
6647
+ _context.next = 8;
6648
+ return Builder(api).from(destination).to(origin).address(senderAddress).senderAddress(address).currency(_objectSpread2(_objectSpread2({}, currencyInput), {}, {
6649
+ amount: currency.amount
6650
+ })).build();
6651
+ case 8:
6652
+ tx = _context.sent;
6653
+ _context.next = 11;
6654
+ return api.calculateTransactionFee(tx, address);
6655
+ case 11:
6656
+ rawFee = _context.sent;
6657
+ return _context.abrupt("return", padFee(rawFee, origin, destination, 'destination'));
6658
+ case 13:
6659
+ case "end":
6660
+ return _context.stop();
6661
+ }
6662
+ }, _callee);
6663
+ }));
6664
+ return function calcPaymentInfoFee() {
6665
+ return _ref3.apply(this, arguments);
6666
+ };
6667
+ }();
6668
+ if (!(!hasDryRunSupport(destination) || !forwardedXcms)) {
6669
+ _context2.next = 7;
6670
+ break;
6671
+ }
6672
+ _context2.next = 5;
6673
+ return calcPaymentInfoFee();
6674
+ case 5:
6675
+ _context2.t0 = _context2.sent;
6676
+ return _context2.abrupt("return", {
6677
+ fee: _context2.t0,
6678
+ feeType: 'paymentInfo'
6679
+ });
6680
+ case 7:
6681
+ _context2.next = 9;
6682
+ return api.getDryRunXcm({
6683
+ originLocation: addXcmVersionHeader(createOriginLocation(origin, destination), Version.V4),
6684
+ xcm: forwardedXcms[1][0],
6685
+ node: destination,
6686
+ origin: origin
6687
+ });
6688
+ case 9:
6689
+ dryRunResult = _context2.sent;
6690
+ if (dryRunResult.success) {
6691
+ _context2.next = 18;
6692
+ break;
6693
+ }
6694
+ if (!disableFallback) {
6695
+ _context2.next = 13;
6696
+ break;
6697
+ }
6698
+ return _context2.abrupt("return", {
6699
+ dryRunError: dryRunResult.failureReason
6700
+ });
6701
+ case 13:
6702
+ _context2.next = 15;
6703
+ return calcPaymentInfoFee();
6704
+ case 15:
6705
+ _context2.t1 = _context2.sent;
6706
+ _context2.t2 = dryRunResult.failureReason;
6707
+ return _context2.abrupt("return", {
6708
+ fee: _context2.t1,
6709
+ feeType: 'paymentInfo',
6710
+ dryRunError: _context2.t2
6711
+ });
6712
+ case 18:
6713
+ fee = dryRunResult.fee, newForwardedXcms = dryRunResult.forwardedXcms, destParaId = dryRunResult.destParaId;
6714
+ return _context2.abrupt("return", {
6715
+ fee: fee,
6716
+ feeType: 'dryRun',
6717
+ forwardedXcms: newForwardedXcms,
6718
+ destParaId: destParaId
6719
+ });
6720
+ case 20:
6721
+ case "end":
6722
+ return _context2.stop();
6723
+ }
6724
+ }, _callee2);
6725
+ }));
6726
+ return function getFeeForDestNode(_x) {
6727
+ return _ref2.apply(this, arguments);
6728
+ };
6729
+ }();
6730
+
6731
+ var dryRunInternal = /*#__PURE__*/function () {
6732
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(options) {
6733
+ var _findAsset, _intermediateFees$ass, _intermediateFees$bri, _destinationDryRun;
6734
+ var origin, destination, currency, api, tx, senderAddress, asset, originDryRun, initialForwardedXcms, initialDestParaId, currentOrigin, forwardedXcms, nextParaId, intermediateFees, destinationDryRun, nextChain, hopApi, hopDryRun, newXcms, destParaId;
6735
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
6736
+ while (1) switch (_context.prev = _context.next) {
6737
+ case 0:
6738
+ origin = options.origin, destination = options.destination, currency = options.currency, api = options.api, tx = options.tx, senderAddress = options.senderAddress;
6739
+ asset = (_findAsset = findAsset(origin, currency, destination)) !== null && _findAsset !== void 0 ? _findAsset : origin === 'AssetHubPolkadot' ? findAsset('Ethereum', currency, null) : null;
6740
+ if (asset) {
6741
+ _context.next = 4;
6742
+ break;
6743
+ }
6744
+ throw new InvalidCurrencyError("Asset ".concat(JSON.stringify(currency), " not found on ").concat(origin));
6745
+ case 4:
6746
+ _context.next = 6;
6747
+ return api.getDryRunCall({
6748
+ tx: tx,
6749
+ node: origin,
6750
+ address: senderAddress
6751
+ });
6752
+ case 6:
6753
+ originDryRun = _context.sent;
6754
+ if (originDryRun.success) {
6755
+ _context.next = 9;
6756
+ break;
6757
+ }
6758
+ return _context.abrupt("return", {
6759
+ origin: originDryRun
6760
+ });
6761
+ case 9:
6762
+ initialForwardedXcms = originDryRun.forwardedXcms, initialDestParaId = originDryRun.destParaId;
6763
+ currentOrigin = origin;
6764
+ forwardedXcms = initialForwardedXcms;
6765
+ nextParaId = initialDestParaId;
6766
+ intermediateFees = {};
6767
+ case 14:
6768
+ if (!(Array.isArray(forwardedXcms) && forwardedXcms.length && forwardedXcms[1].length && ('disconnect' in api.getApi() ? Object.values(forwardedXcms[1][0]).length : forwardedXcms[1][0].value.length) > 0 && nextParaId !== undefined)) {
6769
+ _context.next = 41;
6770
+ break;
6771
+ }
6772
+ nextChain = getTNode(nextParaId, determineRelayChain(origin) === 'Polkadot' ? 'polkadot' : 'kusama');
6773
+ if (nextChain) {
6774
+ _context.next = 18;
6775
+ break;
6776
+ }
6777
+ throw new Error("Unable to find TNode for paraId ".concat(nextParaId));
6778
+ case 18:
6779
+ hopApi = api.clone();
6780
+ _context.prev = 19;
6781
+ if (hasDryRunSupport(nextChain)) {
6782
+ _context.next = 23;
6783
+ break;
6784
+ }
6785
+ if (nextChain === destination) {
6786
+ destinationDryRun = {
6787
+ success: false,
6788
+ failureReason: "DryRunApi is not available on node ".concat(nextChain)
6789
+ };
6790
+ }
6791
+ return _context.abrupt("break", 41);
6792
+ case 23:
6793
+ _context.next = 25;
6794
+ return hopApi.init(nextChain);
6795
+ case 25:
6796
+ _context.next = 27;
6797
+ return hopApi.getDryRunXcm({
6798
+ originLocation: addXcmVersionHeader(createOriginLocation(currentOrigin, nextChain), Version.V4),
6799
+ xcm: forwardedXcms[1][0],
6800
+ node: nextChain,
6801
+ origin: currentOrigin
6802
+ });
6803
+ case 27:
6804
+ hopDryRun = _context.sent;
6805
+ if (nextChain === destination || isRelayChain(nextChain) && !isRelayChain(destination)) {
6806
+ destinationDryRun = hopDryRun;
6807
+ } else if (nextChain === 'AssetHubPolkadot') {
6808
+ intermediateFees.assetHub = hopDryRun;
6809
+ } else if (nextChain === 'BridgeHubPolkadot') {
6810
+ intermediateFees.bridgeHub = hopDryRun;
6811
+ }
6812
+ if (hopDryRun.success) {
6813
+ _context.next = 31;
6814
+ break;
6815
+ }
6816
+ return _context.abrupt("break", 41);
6817
+ case 31:
6818
+ newXcms = hopDryRun.forwardedXcms, destParaId = hopDryRun.destParaId;
6819
+ forwardedXcms = newXcms;
6820
+ nextParaId = destParaId;
6821
+ currentOrigin = nextChain;
6822
+ case 35:
6823
+ _context.prev = 35;
6824
+ _context.next = 38;
6825
+ return hopApi.disconnect();
6826
+ case 38:
6827
+ return _context.finish(35);
6828
+ case 39:
6829
+ _context.next = 14;
6830
+ break;
6831
+ case 41:
6832
+ return _context.abrupt("return", {
6833
+ origin: originDryRun.success ? _objectSpread2(_objectSpread2({}, originDryRun), {}, {
6834
+ currency: getNativeAssetSymbol(origin)
6835
+ }) : originDryRun,
6836
+ assetHub: (_intermediateFees$ass = intermediateFees.assetHub) !== null && _intermediateFees$ass !== void 0 && _intermediateFees$ass.success ? _objectSpread2(_objectSpread2({}, intermediateFees.assetHub), {}, {
6837
+ currency: getNativeAssetSymbol('AssetHubPolkadot')
6838
+ }) : intermediateFees.assetHub,
6839
+ bridgeHub: (_intermediateFees$bri = intermediateFees.bridgeHub) !== null && _intermediateFees$bri !== void 0 && _intermediateFees$bri.success ? _objectSpread2(_objectSpread2({}, intermediateFees.bridgeHub), {}, {
6840
+ currency: getNativeAssetSymbol('BridgeHubPolkadot')
6841
+ }) : intermediateFees.bridgeHub,
6842
+ destination: (_destinationDryRun = destinationDryRun) !== null && _destinationDryRun !== void 0 && _destinationDryRun.success ? _objectSpread2(_objectSpread2({}, destinationDryRun), {}, {
6843
+ currency: asset.symbol
6844
+ }) : destinationDryRun
6845
+ });
6846
+ case 42:
6847
+ case "end":
6848
+ return _context.stop();
6849
+ }
6850
+ }, _callee, null, [[19,, 35, 39]]);
6851
+ }));
6852
+ return function dryRunInternal(_x) {
6853
+ return _ref.apply(this, arguments);
6854
+ };
6855
+ }();
6856
+
6857
+ var dryRun = /*#__PURE__*/function () {
6858
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(options) {
6859
+ var api, senderAddress, origin;
6860
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
6861
+ while (1) switch (_context.prev = _context.next) {
6862
+ case 0:
6863
+ api = options.api, senderAddress = options.senderAddress, origin = options.origin;
6864
+ validateAddress(senderAddress, origin, false);
6865
+ _context.next = 4;
6866
+ return api.init(origin);
6867
+ case 4:
6868
+ _context.prev = 4;
6869
+ _context.next = 7;
6870
+ return dryRunInternal(options);
6871
+ case 7:
6872
+ return _context.abrupt("return", _context.sent);
6873
+ case 8:
6874
+ _context.prev = 8;
6875
+ _context.next = 11;
6876
+ return api.disconnect();
6877
+ case 11:
6878
+ return _context.finish(8);
6879
+ case 12:
6880
+ case "end":
6881
+ return _context.stop();
6882
+ }
6883
+ }, _callee, null, [[4,, 8, 12]]);
6884
+ }));
6885
+ return function dryRun(_x) {
6886
+ return _ref.apply(this, arguments);
6887
+ };
6888
+ }();
6889
+
6890
+ var dryRunOrigin = /*#__PURE__*/function () {
6891
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(options) {
6892
+ var api, node, address, result;
6893
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
6894
+ while (1) switch (_context.prev = _context.next) {
6895
+ case 0:
6896
+ api = options.api, node = options.node, address = options.address;
6897
+ validateAddress(address, node, false);
6898
+ _context.next = 4;
6899
+ return api.init(node);
6900
+ case 4:
6901
+ _context.prev = 4;
6902
+ _context.next = 7;
6903
+ return api.getDryRunCall(options);
6904
+ case 7:
6905
+ result = _context.sent;
6906
+ if (!result.success) {
6907
+ _context.next = 12;
6908
+ break;
6909
+ }
6910
+ return _context.abrupt("return", _objectSpread2(_objectSpread2({}, result), {}, {
6911
+ currency: getNativeAssetSymbol(node)
6912
+ }));
6913
+ case 12:
6914
+ return _context.abrupt("return", result);
6915
+ case 13:
6916
+ _context.prev = 13;
6917
+ _context.next = 16;
6918
+ return api.disconnect();
6919
+ case 16:
6920
+ return _context.finish(13);
6921
+ case 17:
6922
+ case "end":
6923
+ return _context.stop();
6924
+ }
6925
+ }, _callee, null, [[4,, 13, 17]]);
6926
+ }));
6927
+ return function dryRunOrigin(_x) {
6928
+ return _ref.apply(this, arguments);
6929
+ };
6930
+ }();
6554
6931
 
6555
6932
  var getParaEthTransferFees = /*#__PURE__*/function () {
6556
6933
  var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(ahApi) {
@@ -6904,352 +7281,143 @@ var transferMoonbeamToEth = /*#__PURE__*/function () {
6904
7281
  _context.next = 5;
6905
7282
  return getBridgeStatus(api.clone());
6906
7283
  case 5:
6907
- bridgeStatus = _context.sent;
6908
- if (!(bridgeStatus !== 'Normal')) {
6909
- _context.next = 8;
6910
- break;
6911
- }
6912
- throw new BridgeHaltedError();
6913
- case 8:
6914
- if (!('multiasset' in currency)) {
6915
- _context.next = 10;
6916
- break;
6917
- }
6918
- throw new Error('Multiassets syntax is not supported for Evm transfers');
6919
- case 10:
6920
- if (!('multilocation' in currency && isOverrideMultiLocationSpecifier(currency.multilocation))) {
6921
- _context.next = 12;
6922
- break;
6923
- }
6924
- throw new Error('Override multilocation is not supported for Evm transfers');
6925
- case 12:
6926
- foundAsset = findAsset(from, currency, to);
6927
- if (!(foundAsset === null)) {
6928
- _context.next = 15;
6929
- break;
6930
- }
6931
- throw new InvalidCurrencyError("Origin node ".concat(from, " does not support currency ").concat(JSON.stringify(currency), "."));
6932
- case 15:
6933
- if (!(!isForeignAsset(foundAsset) || !foundAsset.multiLocation)) {
6934
- _context.next = 17;
6935
- break;
6936
- }
6937
- throw new InvalidCurrencyError('Currency must be a foreign asset with valid multi-location');
6938
- case 17:
6939
- ethAsset = findAssetByMultiLocation(getOtherAssets('Ethereum'), foundAsset.multiLocation);
6940
- if (!(!ethAsset || !ethAsset.assetId)) {
6941
- _context.next = 20;
6942
- break;
6943
- }
6944
- throw new InvalidCurrencyError("Could not obtain Ethereum asset address for ".concat(JSON.stringify(foundAsset)));
6945
- case 20:
6946
- contract = isEthersSigner(signer) ? new Contract(xcmInterfacePrecompile, abi, signer) : getContract({
6947
- abi: abi,
6948
- address: xcmInterfacePrecompile,
6949
- client: {
6950
- "public": createPublicClient({
6951
- chain: signer.chain,
6952
- transport: http()
6953
- }),
6954
- wallet: signer
6955
- }
6956
- });
6957
- if (!isEthersSigner(signer)) {
6958
- _context.next = 27;
6959
- break;
6960
- }
6961
- _context.next = 24;
6962
- return signer.getAddress();
6963
- case 24:
6964
- _context.t0 = _context.sent;
6965
- _context.next = 28;
6966
- break;
6967
- case 27:
6968
- _context.t0 = (_signer$account = signer.account) === null || _signer$account === void 0 ? void 0 : _signer$account.address;
6969
- case 28:
6970
- senderAddress = _context.t0;
6971
- if (senderAddress) {
6972
- _context.next = 31;
6973
- break;
6974
- }
6975
- throw new Error('Unable to get sender address');
6976
- case 31:
6977
- _context.next = 33;
6978
- return api.init(from);
6979
- case 33:
6980
- _context.next = 35;
6981
- return generateMessageId(api, senderAddress, getParaId(from), ethAsset.assetId, address, currency.amount);
6982
- case 35:
6983
- messageId = _context.sent;
6984
- customXcm = createCustomXcmOnDest({
6985
- api: api,
6986
- address: address,
6987
- scenario: 'ParaToPara',
6988
- senderAddress: senderAddress,
6989
- ahAddress: ahAddress,
6990
- asset: _objectSpread2(_objectSpread2({}, foundAsset), {}, {
6991
- amount: currency.amount
6992
- })}, from, Version.V4, messageId);
6993
- _context.next = 39;
6994
- return api.objectToHex(customXcm, 'XcmVersionedXcm');
6995
- case 39:
6996
- customXcmOnDest = _context.sent;
6997
- _context.next = 42;
6998
- return api.createApiForNode('AssetHubPolkadot');
6999
- case 42:
7000
- assetHubApi = _context.sent;
7001
- _context.next = 45;
7002
- return getParaEthTransferFees(assetHubApi);
7003
- case 45:
7004
- _yield$getParaEthTran = _context.sent;
7005
- _yield$getParaEthTran2 = _slicedToArray(_yield$getParaEthTran, 2);
7006
- bridgeFee = _yield$getParaEthTran2[0];
7007
- executionFee = _yield$getParaEthTran2[1];
7008
- transferFee = (bridgeFee + executionFee).toString(); // Partially inspired by Moonbeam XCM-SDK
7009
- // https://github.com/moonbeam-foundation/xcm-sdk/blob/ab835c15bf41612604b1c858d956a9f07705ed65/packages/sdk/src/contract/contracts/Xtokens/Xtokens.ts#L53
7010
- createTx = function createTx(func, args) {
7011
- if (isEthersContract(contract)) {
7012
- return contract[func].apply(contract, _toConsumableArray(args));
7013
- }
7014
- return contract.write[func](args);
7015
- };
7016
- numberToHex32 = function numberToHex32(num) {
7017
- return typeof num !== 'number' || isNaN(num) ? function () {
7018
- throw new Error('Input must be a valid number');
7019
- }() : "0x".concat((num >>> 0).toString(16).padStart(8, '0'));
7020
- }; // Execute the custom XCM message with the precompile
7021
- _context.next = 54;
7022
- return createTx(isEthersSigner(signer) ? 'transferAssetsUsingTypeAndThenAddress((uint8,bytes[]),(address,uint256)[],uint8,uint8,uint8,bytes)' : 'transferAssetsUsingTypeAndThenAddress', [
7023
- // This represents (1,X1(Parachain(1000)))
7024
- [1, ['0x00' + numberToHex32(getParaId('AssetHubPolkadot')).slice(2)]],
7025
- // Assets including fee and the ERC20 asset, with fee be the first
7026
- [[XCDOT, transferFee], [ethAsset.assetId, currency.amount.toString()]],
7027
- // The TransferType corresponding to asset being sent, 2 represents `DestinationReserve`
7028
- 2,
7029
- // index for the fee
7030
- 0,
7031
- // The TransferType corresponding to fee asset
7032
- 2, customXcmOnDest]);
7033
- case 54:
7034
- tx = _context.sent;
7035
- return _context.abrupt("return", _typeof(tx) === 'object' ? tx.hash : tx);
7036
- case 56:
7037
- case "end":
7038
- return _context.stop();
7039
- }
7040
- }, _callee);
7041
- }));
7042
- return function transferMoonbeamToEth(_x) {
7043
- return _ref2.apply(this, arguments);
7044
- };
7045
- }();
7046
-
7047
- /**
7048
- * Retrieves the node name corresponding to a specified parachain ID.
7049
- *
7050
- * @param paraId - The parachain ID.
7051
- * @returns The node name if found; otherwise, null.
7052
- */
7053
- var getTNode = function getTNode(paraId, ecosystem) {
7054
- var _NODE_NAMES_DOT_KSM$f;
7055
- if (paraId === 0) {
7056
- return ecosystem === 'polkadot' ? 'Polkadot' : 'Kusama';
7057
- }
7058
- if (paraId === 1) {
7059
- return 'Ethereum';
7060
- }
7061
- return (_NODE_NAMES_DOT_KSM$f = NODE_NAMES_DOT_KSM.find(function (nodeName) {
7062
- return getNode(nodeName).type === ecosystem && getParaId(nodeName) === paraId;
7063
- })) !== null && _NODE_NAMES_DOT_KSM$f !== void 0 ? _NODE_NAMES_DOT_KSM$f : null;
7064
- };
7065
-
7066
- var isAssetHub = function isAssetHub(chain) {
7067
- return chain === 'AssetHubPolkadot' || chain === 'AssetHubKusama';
7068
- };
7069
- var isBridgeHub = function isBridgeHub(chain) {
7070
- return chain === 'BridgeHubPolkadot' || chain === 'BridgeHubKusama';
7071
- };
7072
- var isPeople = function isPeople(chain) {
7073
- return chain === 'PeoplePolkadot' || chain === 'PeopleKusama';
7074
- };
7075
- var isSystemPara = function isSystemPara(chain) {
7076
- return isAssetHub(chain) || isBridgeHub(chain) || isPeople(chain);
7077
- };
7078
- var mul = function mul(v, num) {
7079
- var den = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1n;
7080
- return v * num / den;
7081
- };
7082
- var padFee = function padFee(raw, origin, dest, side) {
7083
- var relayOrigin = isRelayChain(origin);
7084
- var relayDest = isRelayChain(dest);
7085
- var sysParaOrigin = isSystemPara(origin);
7086
- var sysParaDest = isSystemPara(dest);
7087
- var relayToPara = relayOrigin && !relayDest;
7088
- var sysParaToPara = sysParaOrigin && !sysParaDest;
7089
- var paraToPara = !relayOrigin && !sysParaOrigin;
7090
- if (sysParaToPara) return raw * 40n;
7091
- if (relayToPara) return side === 'origin' ? mul(raw, 320n, 100n) : mul(raw, 3000n, 100n);
7092
- if (paraToPara) return mul(raw, 130n, 100n);
7093
- // apply default 30% padding
7094
- return mul(raw, 130n, 100n);
7095
- };
7096
-
7097
- var createOriginLocation = function createOriginLocation(origin, destination) {
7098
- if (isRelayChain(origin)) return DOT_MULTILOCATION;
7099
- return {
7100
- parents: isRelayChain(destination) ? Parents.ZERO : Parents.ONE,
7101
- interior: {
7102
- X1: [{
7103
- Parachain: getParaId(origin)
7104
- }]
7105
- }
7106
- };
7107
- };
7108
- var getFeeForDestNode = /*#__PURE__*/function () {
7109
- var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref) {
7110
- var api, forwardedXcms, origin, destination, address, senderAddress, currency, disableFallback, calcPaymentInfoFee, dryRunResult, fee, newForwardedXcms, destParaId;
7111
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
7112
- while (1) switch (_context2.prev = _context2.next) {
7113
- case 0:
7114
- api = _ref.api, forwardedXcms = _ref.forwardedXcms, origin = _ref.origin, destination = _ref.destination, address = _ref.address, senderAddress = _ref.senderAddress, currency = _ref.currency, disableFallback = _ref.disableFallback;
7115
- calcPaymentInfoFee = /*#__PURE__*/function () {
7116
- var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
7117
- var originAsset, currencyInput, tx, rawFee;
7118
- return _regeneratorRuntime().wrap(function _callee$(_context) {
7119
- while (1) switch (_context.prev = _context.next) {
7120
- case 0:
7121
- if (!('multiasset' in currency)) {
7122
- _context.next = 2;
7123
- break;
7124
- }
7125
- throw new InvalidCurrencyError('Multi-assets are not yet supported for XCM fee calculation.');
7126
- case 2:
7127
- originAsset = findAsset(origin, currency, destination);
7128
- if (originAsset) {
7129
- _context.next = 5;
7130
- break;
7131
- }
7132
- throw new InvalidCurrencyError("Currency ".concat(JSON.stringify(currency), " not found in ").concat(origin));
7133
- case 5:
7134
- currencyInput = originAsset.multiLocation ? {
7135
- multilocation: originAsset.multiLocation
7136
- } : {
7137
- symbol: originAsset.symbol
7138
- };
7139
- _context.next = 8;
7140
- return Builder(api).from(destination).to(origin).address(senderAddress, address).currency(_objectSpread2(_objectSpread2({}, currencyInput), {}, {
7141
- amount: currency.amount
7142
- })).build();
7143
- case 8:
7144
- tx = _context.sent;
7145
- _context.next = 11;
7146
- return api.calculateTransactionFee(tx, address);
7147
- case 11:
7148
- rawFee = _context.sent;
7149
- return _context.abrupt("return", padFee(rawFee, origin, destination, 'destination'));
7150
- case 13:
7151
- case "end":
7152
- return _context.stop();
7153
- }
7154
- }, _callee);
7155
- }));
7156
- return function calcPaymentInfoFee() {
7157
- return _ref3.apply(this, arguments);
7158
- };
7159
- }();
7160
- if (!(!hasDryRunSupport(destination) || !forwardedXcms)) {
7161
- _context2.next = 7;
7284
+ bridgeStatus = _context.sent;
7285
+ if (!(bridgeStatus !== 'Normal')) {
7286
+ _context.next = 8;
7162
7287
  break;
7163
7288
  }
7164
- _context2.next = 5;
7165
- return calcPaymentInfoFee();
7166
- case 5:
7167
- _context2.t0 = _context2.sent;
7168
- return _context2.abrupt("return", {
7169
- fee: _context2.t0,
7170
- feeType: 'paymentInfo'
7171
- });
7172
- case 7:
7173
- _context2.next = 9;
7174
- return api.getDryRunXcm({
7175
- originLocation: addXcmVersionHeader(createOriginLocation(origin, destination), Version.V4),
7176
- xcm: forwardedXcms[1][0],
7177
- node: destination,
7178
- origin: origin
7179
- });
7180
- case 9:
7181
- dryRunResult = _context2.sent;
7182
- if (dryRunResult.success) {
7183
- _context2.next = 18;
7289
+ throw new BridgeHaltedError();
7290
+ case 8:
7291
+ if (!('multiasset' in currency)) {
7292
+ _context.next = 10;
7184
7293
  break;
7185
7294
  }
7186
- if (!disableFallback) {
7187
- _context2.next = 13;
7295
+ throw new Error('Multiassets syntax is not supported for Evm transfers');
7296
+ case 10:
7297
+ if (!('multilocation' in currency && isOverrideMultiLocationSpecifier(currency.multilocation))) {
7298
+ _context.next = 12;
7188
7299
  break;
7189
7300
  }
7190
- return _context2.abrupt("return", {
7191
- dryRunError: dryRunResult.failureReason
7192
- });
7193
- case 13:
7194
- _context2.next = 15;
7195
- return calcPaymentInfoFee();
7301
+ throw new Error('Override multilocation is not supported for Evm transfers');
7302
+ case 12:
7303
+ foundAsset = findAsset(from, currency, to);
7304
+ if (!(foundAsset === null)) {
7305
+ _context.next = 15;
7306
+ break;
7307
+ }
7308
+ throw new InvalidCurrencyError("Origin node ".concat(from, " does not support currency ").concat(JSON.stringify(currency), "."));
7196
7309
  case 15:
7197
- _context2.t1 = _context2.sent;
7198
- _context2.t2 = dryRunResult.failureReason;
7199
- return _context2.abrupt("return", {
7200
- fee: _context2.t1,
7201
- feeType: 'paymentInfo',
7202
- dryRunError: _context2.t2
7203
- });
7204
- case 18:
7205
- fee = dryRunResult.fee, newForwardedXcms = dryRunResult.forwardedXcms, destParaId = dryRunResult.destParaId;
7206
- return _context2.abrupt("return", {
7207
- fee: fee,
7208
- feeType: 'dryRun',
7209
- forwardedXcms: newForwardedXcms,
7210
- destParaId: destParaId
7211
- });
7310
+ if (!(!isForeignAsset(foundAsset) || !foundAsset.multiLocation)) {
7311
+ _context.next = 17;
7312
+ break;
7313
+ }
7314
+ throw new InvalidCurrencyError('Currency must be a foreign asset with valid multi-location');
7315
+ case 17:
7316
+ ethAsset = findAssetByMultiLocation(getOtherAssets('Ethereum'), foundAsset.multiLocation);
7317
+ if (!(!ethAsset || !ethAsset.assetId)) {
7318
+ _context.next = 20;
7319
+ break;
7320
+ }
7321
+ throw new InvalidCurrencyError("Could not obtain Ethereum asset address for ".concat(JSON.stringify(foundAsset)));
7212
7322
  case 20:
7213
- case "end":
7214
- return _context2.stop();
7215
- }
7216
- }, _callee2);
7217
- }));
7218
- return function getFeeForDestNode(_x) {
7219
- return _ref2.apply(this, arguments);
7220
- };
7221
- }();
7222
-
7223
- var getDryRun = /*#__PURE__*/function () {
7224
- var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(options) {
7225
- var api, node, address;
7226
- return _regeneratorRuntime().wrap(function _callee$(_context) {
7227
- while (1) switch (_context.prev = _context.next) {
7228
- case 0:
7229
- api = options.api, node = options.node, address = options.address;
7230
- validateAddress(address, node, false);
7231
- _context.next = 4;
7232
- return api.init(node);
7233
- case 4:
7234
- _context.prev = 4;
7235
- _context.next = 7;
7236
- return api.getDryRunCall(options);
7237
- case 7:
7238
- return _context.abrupt("return", _context.sent);
7239
- case 8:
7240
- _context.prev = 8;
7241
- _context.next = 11;
7242
- return api.disconnect();
7243
- case 11:
7244
- return _context.finish(8);
7245
- case 12:
7323
+ contract = isEthersSigner(signer) ? new Contract(xcmInterfacePrecompile, abi, signer) : getContract({
7324
+ abi: abi,
7325
+ address: xcmInterfacePrecompile,
7326
+ client: {
7327
+ "public": createPublicClient({
7328
+ chain: signer.chain,
7329
+ transport: http()
7330
+ }),
7331
+ wallet: signer
7332
+ }
7333
+ });
7334
+ if (!isEthersSigner(signer)) {
7335
+ _context.next = 27;
7336
+ break;
7337
+ }
7338
+ _context.next = 24;
7339
+ return signer.getAddress();
7340
+ case 24:
7341
+ _context.t0 = _context.sent;
7342
+ _context.next = 28;
7343
+ break;
7344
+ case 27:
7345
+ _context.t0 = (_signer$account = signer.account) === null || _signer$account === void 0 ? void 0 : _signer$account.address;
7346
+ case 28:
7347
+ senderAddress = _context.t0;
7348
+ if (senderAddress) {
7349
+ _context.next = 31;
7350
+ break;
7351
+ }
7352
+ throw new Error('Unable to get sender address');
7353
+ case 31:
7354
+ _context.next = 33;
7355
+ return api.init(from);
7356
+ case 33:
7357
+ _context.next = 35;
7358
+ return generateMessageId(api, senderAddress, getParaId(from), ethAsset.assetId, address, currency.amount);
7359
+ case 35:
7360
+ messageId = _context.sent;
7361
+ customXcm = createCustomXcmOnDest({
7362
+ api: api,
7363
+ address: address,
7364
+ scenario: 'ParaToPara',
7365
+ senderAddress: senderAddress,
7366
+ ahAddress: ahAddress,
7367
+ asset: _objectSpread2(_objectSpread2({}, foundAsset), {}, {
7368
+ amount: currency.amount
7369
+ })}, from, Version.V4, messageId);
7370
+ _context.next = 39;
7371
+ return api.objectToHex(customXcm, 'XcmVersionedXcm');
7372
+ case 39:
7373
+ customXcmOnDest = _context.sent;
7374
+ _context.next = 42;
7375
+ return api.createApiForNode('AssetHubPolkadot');
7376
+ case 42:
7377
+ assetHubApi = _context.sent;
7378
+ _context.next = 45;
7379
+ return getParaEthTransferFees(assetHubApi);
7380
+ case 45:
7381
+ _yield$getParaEthTran = _context.sent;
7382
+ _yield$getParaEthTran2 = _slicedToArray(_yield$getParaEthTran, 2);
7383
+ bridgeFee = _yield$getParaEthTran2[0];
7384
+ executionFee = _yield$getParaEthTran2[1];
7385
+ transferFee = (bridgeFee + executionFee).toString(); // Partially inspired by Moonbeam XCM-SDK
7386
+ // https://github.com/moonbeam-foundation/xcm-sdk/blob/ab835c15bf41612604b1c858d956a9f07705ed65/packages/sdk/src/contract/contracts/Xtokens/Xtokens.ts#L53
7387
+ createTx = function createTx(func, args) {
7388
+ if (isEthersContract(contract)) {
7389
+ return contract[func].apply(contract, _toConsumableArray(args));
7390
+ }
7391
+ return contract.write[func](args);
7392
+ };
7393
+ numberToHex32 = function numberToHex32(num) {
7394
+ return typeof num !== 'number' || isNaN(num) ? function () {
7395
+ throw new Error('Input must be a valid number');
7396
+ }() : "0x".concat((num >>> 0).toString(16).padStart(8, '0'));
7397
+ }; // Execute the custom XCM message with the precompile
7398
+ _context.next = 54;
7399
+ return createTx(isEthersSigner(signer) ? 'transferAssetsUsingTypeAndThenAddress((uint8,bytes[]),(address,uint256)[],uint8,uint8,uint8,bytes)' : 'transferAssetsUsingTypeAndThenAddress', [
7400
+ // This represents (1,X1(Parachain(1000)))
7401
+ [1, ['0x00' + numberToHex32(getParaId('AssetHubPolkadot')).slice(2)]],
7402
+ // Assets including fee and the ERC20 asset, with fee be the first
7403
+ [[XCDOT, transferFee], [ethAsset.assetId, currency.amount.toString()]],
7404
+ // The TransferType corresponding to asset being sent, 2 represents `DestinationReserve`
7405
+ 2,
7406
+ // index for the fee
7407
+ 0,
7408
+ // The TransferType corresponding to fee asset
7409
+ 2, customXcmOnDest]);
7410
+ case 54:
7411
+ tx = _context.sent;
7412
+ return _context.abrupt("return", _typeof(tx) === 'object' ? tx.hash : tx);
7413
+ case 56:
7246
7414
  case "end":
7247
7415
  return _context.stop();
7248
7416
  }
7249
- }, _callee, null, [[4,, 8, 12]]);
7417
+ }, _callee);
7250
7418
  }));
7251
- return function getDryRun(_x) {
7252
- return _ref.apply(this, arguments);
7419
+ return function transferMoonbeamToEth(_x) {
7420
+ return _ref2.apply(this, arguments);
7253
7421
  };
7254
7422
  }();
7255
7423
 
@@ -7274,8 +7442,7 @@ var getFeeForOriginNode = /*#__PURE__*/function () {
7274
7442
  });
7275
7443
  case 6:
7276
7444
  _context.next = 8;
7277
- return getDryRun({
7278
- api: api,
7445
+ return api.getDryRunCall({
7279
7446
  tx: tx,
7280
7447
  node: origin,
7281
7448
  address: senderAddress
@@ -7414,7 +7581,7 @@ var getXcmFee = /*#__PURE__*/function () {
7414
7581
  destinationFeeType = 'paymentInfo';
7415
7582
  case 36:
7416
7583
  if (!(Array.isArray(forwardedXcms) && forwardedXcms.length > 0 && forwardedXcms[1].length > 0 && ('disconnect' in api.getApi() ? Object.values(forwardedXcms[1][0]).length : forwardedXcms[1][0].value.length) > 0 && nextParaId !== undefined)) {
7417
- _context.next = 69;
7584
+ _context.next = 68;
7418
7585
  break;
7419
7586
  }
7420
7587
  nextChain = getTNode(nextParaId, determineRelayChain(origin) === 'Polkadot' ? 'polkadot' : 'kusama');
@@ -7485,7 +7652,7 @@ var getXcmFee = /*#__PURE__*/function () {
7485
7652
  destinationFee = destFallback.fee;
7486
7653
  destinationFeeType = destFallback.feeType; // paymentInfo
7487
7654
  case 57:
7488
- return _context.abrupt("break", 69);
7655
+ return _context.abrupt("break", 68);
7489
7656
  case 58:
7490
7657
  if (nextChain === destination || isRelayChain(nextChain) && !isRelayChain(destination)) {
7491
7658
  destinationFee = hopResult.fee;
@@ -7508,15 +7675,14 @@ var getXcmFee = /*#__PURE__*/function () {
7508
7675
  currentOrigin = nextChain;
7509
7676
  case 62:
7510
7677
  _context.prev = 62;
7511
- hopApi.setDisconnectAllowed(true);
7512
- _context.next = 66;
7678
+ _context.next = 65;
7513
7679
  return hopApi.disconnect();
7514
- case 66:
7680
+ case 65:
7515
7681
  return _context.finish(62);
7516
- case 67:
7682
+ case 66:
7517
7683
  _context.next = 36;
7518
7684
  break;
7519
- case 69:
7685
+ case 68:
7520
7686
  return _context.abrupt("return", _objectSpread2(_objectSpread2({
7521
7687
  origin: _objectSpread2(_objectSpread2(_objectSpread2({}, originFee && {
7522
7688
  fee: originFee
@@ -7538,11 +7704,11 @@ var getXcmFee = /*#__PURE__*/function () {
7538
7704
  dryRunError: destinationDryRunError
7539
7705
  })
7540
7706
  }));
7541
- case 70:
7707
+ case 69:
7542
7708
  case "end":
7543
7709
  return _context.stop();
7544
7710
  }
7545
- }, _callee, null, [[17,, 25, 30], [41,, 62, 67]]);
7711
+ }, _callee, null, [[17,, 25, 30], [41,, 62, 66]]);
7546
7712
  }));
7547
7713
  return function getXcmFee(_x) {
7548
7714
  return _ref2.apply(this, arguments);
@@ -7616,7 +7782,7 @@ var getXcmFeeEstimate = /*#__PURE__*/function () {
7616
7782
  symbol: originAsset.symbol
7617
7783
  };
7618
7784
  _context.next = 20;
7619
- return Builder(destApi).from(destination).to(origin).address(senderAddress, address).currency(_objectSpread2(_objectSpread2({}, currencyInput), {}, {
7785
+ return Builder(destApi).from(destination).to(origin).address(senderAddress).senderAddress(address).currency(_objectSpread2(_objectSpread2({}, currencyInput), {}, {
7620
7786
  amount: currency.amount
7621
7787
  })).build();
7622
7788
  case 20:
@@ -8100,14 +8266,31 @@ var GeneralBuilder = /*#__PURE__*/function () {
8100
8266
  currency: _currency
8101
8267
  }));
8102
8268
  }
8269
+ /**
8270
+ * Sets the recipient address.
8271
+ *
8272
+ * @param address - The destination address.
8273
+ * @returns An instance of Builder
8274
+ */
8103
8275
  }, {
8104
8276
  key: "address",
8105
- value: function address(_address, senderAddress) {
8277
+ value: function address(_address) {
8106
8278
  return new GeneralBuilder(this.api, this.batchManager, _objectSpread2(_objectSpread2({}, this._options), {}, {
8107
8279
  address: _address
8108
- }, senderAddress ? {
8109
- senderAddress: senderAddress
8110
- } : {}));
8280
+ }));
8281
+ }
8282
+ /**
8283
+ * Sets the sender address.
8284
+ *
8285
+ * @param address - The sender address.
8286
+ * @returns
8287
+ */
8288
+ }, {
8289
+ key: "senderAddress",
8290
+ value: function senderAddress(address) {
8291
+ return new GeneralBuilder(this.api, this.batchManager, _objectSpread2(_objectSpread2({}, this._options), {}, {
8292
+ senderAddress: address
8293
+ }));
8111
8294
  }
8112
8295
  /**
8113
8296
  * Sets the asset hub address. This is used for transfers that go through the Asset Hub and originate from an EVM chain.
@@ -8246,33 +8429,53 @@ var GeneralBuilder = /*#__PURE__*/function () {
8246
8429
  }, {
8247
8430
  key: "dryRun",
8248
8431
  value: function () {
8249
- var _dryRun = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(senderAddress) {
8250
- var tx;
8432
+ var _dryRun2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
8433
+ var _this$_options2, to, address, senderAddress, tx;
8251
8434
  return _regeneratorRuntime().wrap(function _callee3$(_context3) {
8252
8435
  while (1) switch (_context3.prev = _context3.next) {
8253
8436
  case 0:
8254
- this.api.setDisconnectAllowed(false);
8437
+ _this$_options2 = this._options, to = _this$_options2.to, address = _this$_options2.address, senderAddress = _this$_options2.senderAddress;
8255
8438
  _context3.next = 3;
8256
8439
  return this.build();
8257
8440
  case 3:
8258
8441
  tx = _context3.sent;
8259
- this.api.setDisconnectAllowed(true);
8260
- return _context3.abrupt("return", getDryRun({
8442
+ if (!isTMultiLocation(to)) {
8443
+ _context3.next = 6;
8444
+ break;
8445
+ }
8446
+ throw new InvalidParameterError('Multi-Location destination is not supported for XCM fee calculation.');
8447
+ case 6:
8448
+ if (!isTMultiLocation(address)) {
8449
+ _context3.next = 8;
8450
+ break;
8451
+ }
8452
+ throw new InvalidParameterError('Multi-Location address is not supported for XCM fee calculation.');
8453
+ case 8:
8454
+ if (!(to === 'Ethereum')) {
8455
+ _context3.next = 10;
8456
+ break;
8457
+ }
8458
+ throw new InvalidParameterError('Ethereum destination is not yet supported for XCM fee calculation.');
8459
+ case 10:
8460
+ return _context3.abrupt("return", dryRun({
8261
8461
  api: this.api,
8262
8462
  tx: tx,
8263
8463
  address: senderAddress,
8264
- node: this._options.from
8464
+ origin: this._options.from,
8465
+ destination: to,
8466
+ currency: this._options.currency,
8467
+ senderAddress: this._options.senderAddress
8265
8468
  }));
8266
- case 6:
8469
+ case 11:
8267
8470
  case "end":
8268
8471
  return _context3.stop();
8269
8472
  }
8270
8473
  }, _callee3, this);
8271
8474
  }));
8272
- function dryRun(_x2) {
8273
- return _dryRun.apply(this, arguments);
8475
+ function dryRun$1() {
8476
+ return _dryRun2.apply(this, arguments);
8274
8477
  }
8275
- return dryRun;
8478
+ return dryRun$1;
8276
8479
  }()
8277
8480
  /**
8278
8481
  * Estimates the XCM fee for the transfer using paymentInfo function.
@@ -8283,11 +8486,11 @@ var GeneralBuilder = /*#__PURE__*/function () {
8283
8486
  key: "getXcmFeeEstimate",
8284
8487
  value: (function () {
8285
8488
  var _getXcmFeeEstimate2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
8286
- var _this$_options2, from, to, address, senderAddress, tx;
8489
+ var _this$_options3, from, to, address, senderAddress, tx;
8287
8490
  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
8288
8491
  while (1) switch (_context4.prev = _context4.next) {
8289
8492
  case 0:
8290
- _this$_options2 = this._options, from = _this$_options2.from, to = _this$_options2.to, address = _this$_options2.address, senderAddress = _this$_options2.senderAddress;
8493
+ _this$_options3 = this._options, from = _this$_options3.from, to = _this$_options3.to, address = _this$_options3.address, senderAddress = _this$_options3.senderAddress;
8291
8494
  if (!isTMultiLocation(to)) {
8292
8495
  _context4.next = 3;
8293
8496
  break;
@@ -8312,7 +8515,9 @@ var GeneralBuilder = /*#__PURE__*/function () {
8312
8515
  case 10:
8313
8516
  tx = _context4.sent;
8314
8517
  this.api.setDisconnectAllowed(true);
8315
- return _context4.abrupt("return", getXcmFeeEstimate({
8518
+ _context4.prev = 12;
8519
+ _context4.next = 15;
8520
+ return getXcmFeeEstimate({
8316
8521
  api: this.api,
8317
8522
  tx: tx,
8318
8523
  origin: from,
@@ -8320,12 +8525,20 @@ var GeneralBuilder = /*#__PURE__*/function () {
8320
8525
  address: address,
8321
8526
  senderAddress: senderAddress,
8322
8527
  currency: this._options.currency
8323
- }));
8324
- case 13:
8528
+ });
8529
+ case 15:
8530
+ return _context4.abrupt("return", _context4.sent);
8531
+ case 16:
8532
+ _context4.prev = 16;
8533
+ _context4.next = 19;
8534
+ return this.api.disconnect();
8535
+ case 19:
8536
+ return _context4.finish(16);
8537
+ case 20:
8325
8538
  case "end":
8326
8539
  return _context4.stop();
8327
8540
  }
8328
- }, _callee4, this);
8541
+ }, _callee4, this, [[12,, 16, 20]]);
8329
8542
  }));
8330
8543
  function getXcmFeeEstimate$1() {
8331
8544
  return _getXcmFeeEstimate2.apply(this, arguments);
@@ -8344,7 +8557,7 @@ var GeneralBuilder = /*#__PURE__*/function () {
8344
8557
  var _getXcmFee2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
8345
8558
  var _ref,
8346
8559
  disableFallback,
8347
- _this$_options3,
8560
+ _this$_options4,
8348
8561
  from,
8349
8562
  to,
8350
8563
  address,
@@ -8357,7 +8570,7 @@ var GeneralBuilder = /*#__PURE__*/function () {
8357
8570
  _ref = _args5.length > 0 && _args5[0] !== undefined ? _args5[0] : {
8358
8571
  disableFallback: false
8359
8572
  }, disableFallback = _ref.disableFallback;
8360
- _this$_options3 = this._options, from = _this$_options3.from, to = _this$_options3.to, address = _this$_options3.address, senderAddress = _this$_options3.senderAddress;
8573
+ _this$_options4 = this._options, from = _this$_options4.from, to = _this$_options4.to, address = _this$_options4.address, senderAddress = _this$_options4.senderAddress;
8361
8574
  if (!isTMultiLocation(to)) {
8362
8575
  _context5.next = 4;
8363
8576
  break;
@@ -8380,8 +8593,9 @@ var GeneralBuilder = /*#__PURE__*/function () {
8380
8593
  return this.build();
8381
8594
  case 10:
8382
8595
  tx = _context5.sent;
8383
- this.api.setDisconnectAllowed(false);
8384
- return _context5.abrupt("return", getXcmFee({
8596
+ _context5.prev = 11;
8597
+ _context5.next = 14;
8598
+ return getXcmFee({
8385
8599
  api: this.api,
8386
8600
  tx: tx,
8387
8601
  origin: from,
@@ -8390,12 +8604,20 @@ var GeneralBuilder = /*#__PURE__*/function () {
8390
8604
  address: address,
8391
8605
  currency: this._options.currency,
8392
8606
  disableFallback: disableFallback
8393
- }));
8394
- case 13:
8607
+ });
8608
+ case 14:
8609
+ return _context5.abrupt("return", _context5.sent);
8610
+ case 15:
8611
+ _context5.prev = 15;
8612
+ _context5.next = 18;
8613
+ return this.api.disconnect();
8614
+ case 18:
8615
+ return _context5.finish(15);
8616
+ case 19:
8395
8617
  case "end":
8396
8618
  return _context5.stop();
8397
8619
  }
8398
- }, _callee5, this);
8620
+ }, _callee5, this, [[11,, 15, 19]]);
8399
8621
  }));
8400
8622
  function getXcmFee$1() {
8401
8623
  return _getXcmFee2.apply(this, arguments);
@@ -8796,7 +9018,7 @@ var getOriginFeeDetailsInternal = /*#__PURE__*/function () {
8796
9018
  return api.init(origin);
8797
9019
  case 3:
8798
9020
  _context.next = 5;
8799
- return Builder(api).from(origin).to(destination).currency(currency).address(accountDestination, account).build();
9021
+ return Builder(api).from(origin).to(destination).currency(currency).address(accountDestination).senderAddress(account).build();
8800
9022
  case 5:
8801
9023
  tx = _context.sent;
8802
9024
  _context.next = 8;
@@ -9191,4 +9413,4 @@ var verifyEdOnDestination = /*#__PURE__*/function () {
9191
9413
  };
9192
9414
  }();
9193
9415
 
9194
- export { AssetClaimBuilder, BatchMode, BridgeHaltedError, Builder, DryRunFailedError, ETHEREUM_JUNCTION, ETH_CHAIN_ID, GeneralBuilder, IncompatibleNodesError, InvalidAddressError, InvalidParameterError, NoXCMSupportImplementedError, NodeNotSupportedError, PolkadotXcmError, ScenarioNotSupportedError, Version, XTokensError, claimAssets, computeFeeFromDryRun, computeFeeFromDryRunPjs, createApiInstanceForNode, createBeneficiaryMultiLocation, createVersionedBeneficiary, createX1Payload, determineRelayChain, generateAddressMultiLocationV4, getAssetBalance, getAssetBalanceInternal, getBalanceForeign, getBalanceForeignInternal, getBalanceNative, getBalanceNativeInternal, getBridgeStatus, getDryRun, getFees, getMaxForeignTransferableAmount, getMaxNativeTransferableAmount, getNode, getNodeConfig, getNodeProviders, getOriginFeeDetails, getOriginFeeDetailsInternal, getParaEthTransferFees, getParaId, getTNode, getTransferInfo, getTransferableAmount, getXcmFee, getXcmFeeEstimate, isEthersContract, isEthersSigner, resolveModuleError, resolveParaId, send, transferMoonbeamEvm, transferMoonbeamToEth, transferRelayToPara, transformMultiLocation, validateAddress, verifyEdOnDestination };
9416
+ export { AssetClaimBuilder, BatchMode, BridgeHaltedError, Builder, DryRunFailedError, ETHEREUM_JUNCTION, ETH_CHAIN_ID, GeneralBuilder, IncompatibleNodesError, InvalidAddressError, InvalidParameterError, NoXCMSupportImplementedError, NodeNotSupportedError, PolkadotXcmError, ScenarioNotSupportedError, Version, XTokensError, claimAssets, computeFeeFromDryRun, computeFeeFromDryRunPjs, createApiInstanceForNode, createBeneficiaryMultiLocation, createVersionedBeneficiary, createX1Payload, determineRelayChain, dryRun, dryRunOrigin, generateAddressMultiLocationV4, getAssetBalance, getAssetBalanceInternal, getBalanceForeign, getBalanceForeignInternal, getBalanceNative, getBalanceNativeInternal, getBridgeStatus, getFees, getMaxForeignTransferableAmount, getMaxNativeTransferableAmount, getNode, getNodeConfig, getNodeProviders, getOriginFeeDetails, getOriginFeeDetailsInternal, getParaEthTransferFees, getParaId, getTNode, getTransferInfo, getTransferableAmount, getXcmFee, getXcmFeeEstimate, isEthersContract, isEthersSigner, resolveModuleError, resolveParaId, send, transferMoonbeamEvm, transferMoonbeamToEth, transferRelayToPara, transformMultiLocation, validateAddress, verifyEdOnDestination };