@hyperbridge/sdk 1.8.3 → 1.8.5

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.
@@ -3,14 +3,14 @@ import { join } from 'path';
3
3
  import { TextDecoder as TextDecoder$1, TextEncoder as TextEncoder$1 } from 'util';
4
4
  import { createConsola, LogLevels } from 'consola';
5
5
  import { flatten, zip, capitalize, maxBy, isNil } from 'lodash-es';
6
- import { defineChain, keccak256, toHex, createPublicClient, http, hexToBytes, bytesToHex, encodeFunctionData, erc20Abi, bytesToBigInt, pad, toBytes, numberToBytes, encodePacked, encodeAbiParameters, maxUint256, parseAbiParameters, parseAbiItem, isHex, hexToString as hexToString$1, parseEventLogs, parseUnits, concatHex, concat, decodeFunctionData, decodeAbiParameters, formatUnits } from 'viem';
6
+ import { defineChain, keccak256, toHex, createPublicClient, http, hexToBytes, bytesToHex, encodeFunctionData, erc20Abi, bytesToBigInt, pad, toBytes, numberToBytes, getAddress, encodePacked, encodeAbiParameters, maxUint256, parseAbiParameters, parseAbiItem, isHex, hexToString as hexToString$1, parseEventLogs, parseUnits, concatHex, concat, decodeFunctionData, decodeAbiParameters, formatUnits } from 'viem';
7
7
  import mergeRace from '@async-generator/merge-race';
8
8
  import { baseSepolia, optimismSepolia, arbitrumSepolia, soneium, gnosis, optimism, polygonAmoy, unichain, polygon, base, arbitrum, bsc, mainnet, sepolia, gnosisChiado, bscTestnet, tron } from 'viem/chains';
9
9
  import { TronWeb } from 'tronweb';
10
10
  import { match } from 'ts-pattern';
11
11
  import { WsProvider, ApiPromise, Keyring } from '@polkadot/api';
12
- import { Struct, Vector, u8, Bytes, Tuple, Enum, _void, u64, u32, Option, bool, u128 } from 'scale-ts';
13
- import { keccakAsU8a, decodeAddress, keccakAsHex, xxhashAsU8a } from '@polkadot/util-crypto';
12
+ import { Struct, Vector, u8, Bytes, Enum, Tuple, _void, u64, u32, Option, bool, u128 } from 'scale-ts';
13
+ import { keccakAsU8a, decodeAddress, keccakAsHex, xxhashAsU8a, blake2AsU8a } from '@polkadot/util-crypto';
14
14
  import { hexToU8a, u8aToHex, u8aConcat } from '@polkadot/util';
15
15
  import { hasWindow, isNode, env } from 'std-env';
16
16
  import { GraphQLClient } from 'graphql-request';
@@ -4318,6 +4318,8 @@ var getConfigByStateMachineId = (id) => configsByStateMachineId[id];
4318
4318
  var getChainId = (stateMachineId) => configsByStateMachineId[stateMachineId]?.chainId;
4319
4319
  var getViemChain = (chainId) => chainConfigs[chainId]?.viemChain;
4320
4320
  var hyperbridgeAddress = "";
4321
+
4322
+ // src/configs/ChainConfigService.ts
4321
4323
  var ChainConfigService = class {
4322
4324
  rpcUrls = {};
4323
4325
  constructor(env2 = process.env) {
@@ -4386,7 +4388,8 @@ var ChainConfigService = class {
4386
4388
  }
4387
4389
  getConsensusStateId(chain) {
4388
4390
  const id = this.getConfig(chain)?.consensusStateId;
4389
- return id ? toHex(id) : "0x";
4391
+ if (!id) throw new Error(`No consensusStateId configured for chain: ${chain}`);
4392
+ return id;
4390
4393
  }
4391
4394
  getHyperbridgeChainId() {
4392
4395
  return chainConfigs[4009]?.chainId ?? 4009;
@@ -5480,8 +5483,10 @@ var EvmChain = class _EvmChain {
5480
5483
  // Gnosis
5481
5484
  10200: "GNO0",
5482
5485
  // Gnosis Chiado
5483
- 420420417: "PAS0"
5486
+ 420420417: "PAS0",
5484
5487
  // Polkadot Asset Hub (Paseo)
5488
+ 420420419: "DOT0"
5489
+ // Polkadot Asset Hub (Polkadot)
5485
5490
  };
5486
5491
  if (!params.consensusStateId) {
5487
5492
  params.consensusStateId = defaultConsensusStateIds[params.chainId];
@@ -7060,143 +7065,20 @@ var TronChain = class _TronChain {
7060
7065
  return this.evm.estimateGas(request);
7061
7066
  }
7062
7067
  };
7063
- function getPeakPosByHeight(height) {
7064
- return (1n << BigInt(height + 1)) - 2n;
7065
- }
7066
- function leftPeakHeightPos(mmrSize) {
7067
- let height = 1;
7068
- let prevPos = 0n;
7069
- let pos = getPeakPosByHeight(height);
7070
- while (pos < mmrSize) {
7071
- height += 1;
7072
- prevPos = pos;
7073
- pos = getPeakPosByHeight(height);
7074
- }
7075
- return [height - 1, prevPos];
7076
- }
7077
- function getRightPeak(initialHeight, initialPos, mmrSize) {
7078
- let height = initialHeight;
7079
- let pos = initialPos;
7080
- pos += siblingOffset(height);
7081
- while (pos > mmrSize - 1n) {
7082
- if (height === 0) {
7083
- return null;
7084
- }
7085
- pos -= parentOffset(height - 1);
7086
- height -= 1;
7087
- }
7088
- return [height, pos];
7089
- }
7090
- function getPeaks(mmrSize) {
7091
- const positions = [];
7092
- let [height, pos] = leftPeakHeightPos(mmrSize);
7093
- positions.push(pos);
7094
- while (height > 0) {
7095
- const peak = getRightPeak(height, pos, mmrSize);
7096
- if (!peak) break;
7097
- [height, pos] = peak;
7098
- positions.push(pos);
7099
- }
7100
- return positions;
7101
- }
7102
- function allOnes(num) {
7103
- if (num === 0n) return false;
7104
- return num.toString(2).split("").every((bit) => bit === "1");
7105
- }
7106
- function jumpLeft(pos) {
7107
- const bitLength = pos.toString(2).length;
7108
- const mostSignificantBits = 1n << BigInt(bitLength - 1);
7109
- return pos - (mostSignificantBits - 1n);
7110
- }
7111
- function posHeightInTree(initialPos) {
7112
- let pos = initialPos + 1n;
7113
- while (!allOnes(pos)) {
7114
- pos = jumpLeft(pos);
7115
- }
7116
- return pos.toString(2).length - 1;
7117
- }
7118
- function parentOffset(height) {
7119
- return 2n << BigInt(height);
7120
- }
7121
- function siblingOffset(height) {
7122
- return (2n << BigInt(height)) - 1n;
7123
- }
7124
- function takeWhileVec(v, p) {
7125
- const index = v.findIndex((item) => !p(item));
7126
- if (index === -1) {
7127
- const result = [...v];
7128
- v.length = 0;
7129
- return result;
7130
- }
7131
- return v.splice(0, index);
7132
- }
7133
- function mmrPositionToKIndex(initialLeaves, mmrSize) {
7134
- const leaves = [...initialLeaves];
7135
- const peaks = getPeaks(mmrSize);
7136
- const leavesWithKIndices = [];
7137
- for (const peak of peaks) {
7138
- const peakLeaves = takeWhileVec(leaves, (pos) => pos <= peak);
7139
- if (peakLeaves.length > 0) {
7140
- for (const pos of peakLeaves) {
7141
- const height = posHeightInTree(peak);
7142
- let index = 0n;
7143
- let parentPos = peak;
7144
- for (let h = height; h >= 1; h--) {
7145
- const leftChild = parentPos - parentOffset(h - 1);
7146
- const rightChild = leftChild + siblingOffset(h - 1);
7147
- index *= 2n;
7148
- if (leftChild >= pos) {
7149
- parentPos = leftChild;
7150
- } else {
7151
- parentPos = rightChild;
7152
- index += 1n;
7153
- }
7154
- }
7155
- leavesWithKIndices.push([pos, index]);
7156
- }
7157
- }
7158
- }
7159
- return leavesWithKIndices;
7160
- }
7161
- function calculateMMRSize(numberOfLeaves) {
7162
- const numberOfPeaks = numberOfLeaves.toString(2).split("1").length - 1;
7163
- return 2n * numberOfLeaves - BigInt(numberOfPeaks);
7164
- }
7165
- async function generateRootWithProof(postRequest, treeSize) {
7166
- const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7167
- const { commitment: hash, encodePacked: encodePacked4 } = postRequestCommitment(postRequest);
7168
- const result = JSON.parse(generate_root_with_proof2(hexToBytes(encodePacked4), treeSize));
7169
- const { root, proof, mmr_size, leaf_positions, keccak_hash_calldata } = result;
7170
- if (keccak_hash_calldata !== hash) {
7171
- console.log("keccak_hash", keccak_hash_calldata);
7172
- console.log("hash", hash);
7173
- throw new Error("Abi keccak hash mismatch");
7174
- }
7175
- const [[, kIndex]] = mmrPositionToKIndex(leaf_positions, BigInt(mmr_size));
7176
- return {
7177
- root,
7178
- proof,
7179
- index: treeSize - 1n,
7180
- kIndex,
7181
- treeSize,
7182
- mmrSize: mmr_size
7183
- };
7184
- }
7185
- async function load_ckb_mmr() {
7186
- if (hasWindow) {
7187
- const wasm2 = await Promise.resolve().then(() => (init_node(), node_exports));
7188
- await wasm2.default();
7189
- return wasm2;
7190
- }
7191
- if (isNode) {
7192
- const wasm2 = await Promise.resolve().then(() => (init_node(), node_exports));
7193
- return wasm2;
7194
- }
7195
- throw new Error(`SDK not setup for ${env}`);
7196
- }
7197
- async function __test() {
7198
- const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7199
- return generate_root_with_proof2(new Uint8Array(), 120n);
7068
+ var ReviveContractInfo = Struct({
7069
+ trie_id: Vector(u8)
7070
+ });
7071
+ var ReviveAccountType = Enum({
7072
+ Contract: ReviveContractInfo
7073
+ });
7074
+ var ReviveAccountInfo = Struct({
7075
+ account_type: ReviveAccountType
7076
+ });
7077
+ function decodeReviveContractTrieId(accountData) {
7078
+ const {
7079
+ account_type: { value }
7080
+ } = ReviveAccountInfo.dec(accountData);
7081
+ return value.trie_id;
7200
7082
  }
7201
7083
  var H256 = Vector(u8, 32);
7202
7084
  var EvmStateProof = Struct({
@@ -7209,6 +7091,16 @@ var EvmStateProof = Struct({
7209
7091
  */
7210
7092
  storageProof: Vector(Tuple(Vector(u8), Vector(Vector(u8))))
7211
7093
  });
7094
+ var SubstrateEvmProof = Struct({
7095
+ main_proof: Vector(Vector(u8)),
7096
+ storage_proof: Vector(Tuple(Vector(u8), Vector(Vector(u8))))
7097
+ });
7098
+ function encodeSubstrateEvmProofBytes(params) {
7099
+ return SubstrateEvmProof.enc({
7100
+ main_proof: params.mainProof,
7101
+ storage_proof: Array.from(params.storageProof.entries())
7102
+ });
7103
+ }
7212
7104
  var SubstrateHashing = Enum({
7213
7105
  /* For chains that use keccak as their hashing algo */
7214
7106
  Keccak: _void,
@@ -7580,6 +7472,379 @@ var Message = Enum({
7580
7472
  TimeoutMessage
7581
7473
  });
7582
7474
 
7475
+ // src/chains/polkadotHub.ts
7476
+ var DEFAULT_CHILD_STORAGE_PREFIX = new TextEncoder().encode(":child_storage:default:");
7477
+ var SubstrateHttpRpc = class {
7478
+ constructor(url) {
7479
+ this.url = url;
7480
+ }
7481
+ async call(method, params = []) {
7482
+ const body = JSON.stringify({
7483
+ jsonrpc: "2.0",
7484
+ id: Date.now(),
7485
+ method,
7486
+ params
7487
+ });
7488
+ const response = await fetch(this.url, {
7489
+ method: "POST",
7490
+ headers: { "Content-Type": "application/json" },
7491
+ body
7492
+ });
7493
+ if (!response.ok) {
7494
+ throw new Error(`Substrate RPC HTTP error: ${response.status}`);
7495
+ }
7496
+ const json = await response.json();
7497
+ if (json.error) {
7498
+ throw new Error(`Substrate RPC error: ${json.error.message}`);
7499
+ }
7500
+ return json.result;
7501
+ }
7502
+ };
7503
+ function contractInfoKey(address20) {
7504
+ const key = new Uint8Array(16 + 16 + 20);
7505
+ key.set(xxhashAsU8a("Revive", 128), 0);
7506
+ key.set(xxhashAsU8a("AccountInfoOf", 128), 16);
7507
+ key.set(address20, 32);
7508
+ return key;
7509
+ }
7510
+ function childPrefixedStorageKey(trieId) {
7511
+ return u8aConcat(DEFAULT_CHILD_STORAGE_PREFIX, trieId);
7512
+ }
7513
+ function storageKeyForSlot(slot32) {
7514
+ return blake2AsU8a(slot32, 256);
7515
+ }
7516
+ function hexKey(k) {
7517
+ return bytesToHex(k);
7518
+ }
7519
+ var PolkadotHubChain = class _PolkadotHubChain {
7520
+ constructor(params, evm) {
7521
+ this.params = params;
7522
+ this.evm = evm;
7523
+ this.substrateRpc = new SubstrateHttpRpc(replaceWebsocketWithHttp(params.substrateRpcUrl));
7524
+ }
7525
+ evm;
7526
+ substrateRpc;
7527
+ static fromParams(params) {
7528
+ const { substrateRpcUrl, ...evmParams } = params;
7529
+ const evm = EvmChain.fromParams(evmParams);
7530
+ return new _PolkadotHubChain(params, evm);
7531
+ }
7532
+ /**
7533
+ * Creates a `PolkadotHubChain` by auto-detecting the EVM chain ID and `IsmpHost` address via
7534
+ * {@link EvmChain.create}, plus a Substrate RPC URL for Revive child-trie proofs.
7535
+ *
7536
+ * @param evmRpcUrl - HTTP(S) JSON-RPC URL of the EVM (Revive) node
7537
+ * @param substrateRpcUrl - Substrate node RPC (HTTP or WebSocket) for proof queries
7538
+ * @param bundlerUrl - Optional ERC-4337 bundler URL (forwarded to `EvmChain.create`)
7539
+ */
7540
+ static async create(evmRpcUrl, substrateRpcUrl, bundlerUrl) {
7541
+ const evm = await EvmChain.create(evmRpcUrl, bundlerUrl);
7542
+ const chainId = Number.parseInt(evm.config.stateMachineId.replace(/^EVM-/, ""), 10);
7543
+ if (!Number.isFinite(chainId)) {
7544
+ throw new Error(`Unexpected EVM stateMachineId: ${evm.config.stateMachineId}`);
7545
+ }
7546
+ const params = {
7547
+ chainId,
7548
+ rpcUrl: evm.config.rpcUrl,
7549
+ host: evm.config.host,
7550
+ consensusStateId: evm.config.consensusStateId,
7551
+ bundlerUrl: evm.bundlerUrl,
7552
+ substrateRpcUrl
7553
+ };
7554
+ return new _PolkadotHubChain(params, evm);
7555
+ }
7556
+ get client() {
7557
+ return this.evm.client;
7558
+ }
7559
+ get host() {
7560
+ return this.evm.host;
7561
+ }
7562
+ get bundlerUrl() {
7563
+ return this.evm.bundlerUrl;
7564
+ }
7565
+ get configService() {
7566
+ return this.evm.configService;
7567
+ }
7568
+ get config() {
7569
+ return {
7570
+ ...this.evm.config,
7571
+ substrateRpcUrl: this.params.substrateRpcUrl
7572
+ };
7573
+ }
7574
+ hostAddress20() {
7575
+ return hexToBytes(getAddress(this.evm.host));
7576
+ }
7577
+ async fetchCombinedProof(at, queries) {
7578
+ const height = Number(at);
7579
+ if (!Number.isSafeInteger(height) || height < 0) {
7580
+ throw new Error("Block height must be a non-negative safe integer for Substrate RPC");
7581
+ }
7582
+ const blockHash = await this.substrateRpc.call("chain_getBlockHash", [height]);
7583
+ if (!blockHash) {
7584
+ throw new Error(`Block hash not found for height ${height}`);
7585
+ }
7586
+ const mainKeys = [];
7587
+ const childInfoByAddr = /* @__PURE__ */ new Map();
7588
+ const contractEntries = [...queries.entries()];
7589
+ for (const [addr20] of contractEntries) {
7590
+ const infoKey = contractInfoKey(addr20);
7591
+ const storageHex = await this.substrateRpc.call("state_getStorage", [hexKey(infoKey), blockHash]);
7592
+ if (!storageHex) {
7593
+ throw new Error(`Revive AccountInfo not found for contract ${hexKey(addr20)}`);
7594
+ }
7595
+ const trieId = decodeReviveContractTrieId(hexToBytes(storageHex));
7596
+ const prefixed = childPrefixedStorageKey(trieId);
7597
+ mainKeys.push(hexKey(infoKey));
7598
+ mainKeys.push(hexKey(prefixed));
7599
+ childInfoByAddr.set(hexKey(addr20), { trieId, prefixed });
7600
+ }
7601
+ const mainRead = await this.substrateRpc.call("state_getReadProof", [mainKeys, blockHash]);
7602
+ const mainProofBytes = mainRead.proof.map((p) => hexToBytes(p));
7603
+ const storageProofEncoded = /* @__PURE__ */ new Map();
7604
+ for (const [addr20, innerKeys] of contractEntries) {
7605
+ const addrHex = hexKey(addr20);
7606
+ const info = childInfoByAddr.get(addrHex);
7607
+ if (!info) {
7608
+ throw new Error("Internal error: missing child info for contract");
7609
+ }
7610
+ const childKeysHex = innerKeys.map((k) => hexKey(k));
7611
+ const childRead = await this.substrateRpc.call("state_getChildReadProof", [
7612
+ hexKey(info.prefixed),
7613
+ childKeysHex,
7614
+ blockHash
7615
+ ]);
7616
+ storageProofEncoded.set(
7617
+ addr20,
7618
+ childRead.proof.map((p) => hexToBytes(p))
7619
+ );
7620
+ }
7621
+ const encoded = encodeSubstrateEvmProofBytes({
7622
+ mainProof: mainProofBytes,
7623
+ storageProof: storageProofEncoded
7624
+ });
7625
+ return bytesToHex(encoded);
7626
+ }
7627
+ timestamp() {
7628
+ return this.evm.timestamp();
7629
+ }
7630
+ requestReceiptKey(commitment) {
7631
+ return this.evm.requestReceiptKey(commitment);
7632
+ }
7633
+ queryRequestReceipt(commitment) {
7634
+ return this.evm.queryRequestReceipt(commitment);
7635
+ }
7636
+ async queryProof(message, _counterparty, at) {
7637
+ if (at === void 0) {
7638
+ throw new Error("PolkadotHubChain.queryProof requires an explicit block height `at`");
7639
+ }
7640
+ const host = this.hostAddress20();
7641
+ const storageKeys = "Requests" in message ? message.Requests.map((c) => storageKeyForSlot(hexToBytes(requestCommitmentKey(c).slot1))) : message.Responses.map((c) => storageKeyForSlot(hexToBytes(responseCommitmentKey(c))));
7642
+ const q = /* @__PURE__ */ new Map();
7643
+ q.set(host, storageKeys);
7644
+ return this.fetchCombinedProof(at, q);
7645
+ }
7646
+ async queryStateProof(at, keys, _address) {
7647
+ const keyBytes = keys.map((k) => hexToBytes(k));
7648
+ const host = this.hostAddress20();
7649
+ if (keyBytes.every((k) => k.length === 32)) {
7650
+ const storageKeys = keyBytes.map((slot) => storageKeyForSlot(slot));
7651
+ const q = /* @__PURE__ */ new Map();
7652
+ q.set(host, storageKeys);
7653
+ return this.fetchCombinedProof(at, q);
7654
+ }
7655
+ if (keyBytes.every((k) => k.length === 52)) {
7656
+ const groups = /* @__PURE__ */ new Map();
7657
+ for (const full of keyBytes) {
7658
+ const addr = full.subarray(0, 20);
7659
+ const slot = full.subarray(20, 52);
7660
+ const h = hexKey(addr);
7661
+ const arr = groups.get(h) ?? [];
7662
+ arr.push(storageKeyForSlot(slot));
7663
+ groups.set(h, arr);
7664
+ }
7665
+ const q = /* @__PURE__ */ new Map();
7666
+ for (const [addrHex, sks] of groups) {
7667
+ q.set(hexToBytes(addrHex), sks);
7668
+ }
7669
+ return this.fetchCombinedProof(at, q);
7670
+ }
7671
+ throw new Error(
7672
+ "PolkadotHubChain.queryStateProof: keys must be either all 32-byte ISMP slots or all 52-byte (20-byte address + 32-byte slot) entries"
7673
+ );
7674
+ }
7675
+ encode(message) {
7676
+ return this.evm.encode(message);
7677
+ }
7678
+ latestStateMachineHeight(stateMachineId) {
7679
+ return this.evm.latestStateMachineHeight(stateMachineId);
7680
+ }
7681
+ challengePeriod(stateMachineId) {
7682
+ return this.evm.challengePeriod(stateMachineId);
7683
+ }
7684
+ stateMachineUpdateTime(stateMachineHeight) {
7685
+ return this.evm.stateMachineUpdateTime(stateMachineHeight);
7686
+ }
7687
+ getHostNonce() {
7688
+ return this.evm.getHostNonce();
7689
+ }
7690
+ quoteNative(request, fee) {
7691
+ return this.evm.quoteNative(request, fee);
7692
+ }
7693
+ getFeeTokenWithDecimals() {
7694
+ return this.evm.getFeeTokenWithDecimals();
7695
+ }
7696
+ getPlaceOrderCalldata(txHash, intentGatewayAddress) {
7697
+ return this.evm.getPlaceOrderCalldata(txHash, intentGatewayAddress);
7698
+ }
7699
+ estimateGas(request) {
7700
+ return this.evm.estimateGas(request);
7701
+ }
7702
+ broadcastTransaction(signedTransaction) {
7703
+ return this.evm.broadcastTransaction(signedTransaction);
7704
+ }
7705
+ getTransactionReceipt(hash) {
7706
+ return this.evm.getTransactionReceipt(hash);
7707
+ }
7708
+ };
7709
+ function getPeakPosByHeight(height) {
7710
+ return (1n << BigInt(height + 1)) - 2n;
7711
+ }
7712
+ function leftPeakHeightPos(mmrSize) {
7713
+ let height = 1;
7714
+ let prevPos = 0n;
7715
+ let pos = getPeakPosByHeight(height);
7716
+ while (pos < mmrSize) {
7717
+ height += 1;
7718
+ prevPos = pos;
7719
+ pos = getPeakPosByHeight(height);
7720
+ }
7721
+ return [height - 1, prevPos];
7722
+ }
7723
+ function getRightPeak(initialHeight, initialPos, mmrSize) {
7724
+ let height = initialHeight;
7725
+ let pos = initialPos;
7726
+ pos += siblingOffset(height);
7727
+ while (pos > mmrSize - 1n) {
7728
+ if (height === 0) {
7729
+ return null;
7730
+ }
7731
+ pos -= parentOffset(height - 1);
7732
+ height -= 1;
7733
+ }
7734
+ return [height, pos];
7735
+ }
7736
+ function getPeaks(mmrSize) {
7737
+ const positions = [];
7738
+ let [height, pos] = leftPeakHeightPos(mmrSize);
7739
+ positions.push(pos);
7740
+ while (height > 0) {
7741
+ const peak = getRightPeak(height, pos, mmrSize);
7742
+ if (!peak) break;
7743
+ [height, pos] = peak;
7744
+ positions.push(pos);
7745
+ }
7746
+ return positions;
7747
+ }
7748
+ function allOnes(num) {
7749
+ if (num === 0n) return false;
7750
+ return num.toString(2).split("").every((bit) => bit === "1");
7751
+ }
7752
+ function jumpLeft(pos) {
7753
+ const bitLength = pos.toString(2).length;
7754
+ const mostSignificantBits = 1n << BigInt(bitLength - 1);
7755
+ return pos - (mostSignificantBits - 1n);
7756
+ }
7757
+ function posHeightInTree(initialPos) {
7758
+ let pos = initialPos + 1n;
7759
+ while (!allOnes(pos)) {
7760
+ pos = jumpLeft(pos);
7761
+ }
7762
+ return pos.toString(2).length - 1;
7763
+ }
7764
+ function parentOffset(height) {
7765
+ return 2n << BigInt(height);
7766
+ }
7767
+ function siblingOffset(height) {
7768
+ return (2n << BigInt(height)) - 1n;
7769
+ }
7770
+ function takeWhileVec(v, p) {
7771
+ const index = v.findIndex((item) => !p(item));
7772
+ if (index === -1) {
7773
+ const result = [...v];
7774
+ v.length = 0;
7775
+ return result;
7776
+ }
7777
+ return v.splice(0, index);
7778
+ }
7779
+ function mmrPositionToKIndex(initialLeaves, mmrSize) {
7780
+ const leaves = [...initialLeaves];
7781
+ const peaks = getPeaks(mmrSize);
7782
+ const leavesWithKIndices = [];
7783
+ for (const peak of peaks) {
7784
+ const peakLeaves = takeWhileVec(leaves, (pos) => pos <= peak);
7785
+ if (peakLeaves.length > 0) {
7786
+ for (const pos of peakLeaves) {
7787
+ const height = posHeightInTree(peak);
7788
+ let index = 0n;
7789
+ let parentPos = peak;
7790
+ for (let h = height; h >= 1; h--) {
7791
+ const leftChild = parentPos - parentOffset(h - 1);
7792
+ const rightChild = leftChild + siblingOffset(h - 1);
7793
+ index *= 2n;
7794
+ if (leftChild >= pos) {
7795
+ parentPos = leftChild;
7796
+ } else {
7797
+ parentPos = rightChild;
7798
+ index += 1n;
7799
+ }
7800
+ }
7801
+ leavesWithKIndices.push([pos, index]);
7802
+ }
7803
+ }
7804
+ }
7805
+ return leavesWithKIndices;
7806
+ }
7807
+ function calculateMMRSize(numberOfLeaves) {
7808
+ const numberOfPeaks = numberOfLeaves.toString(2).split("1").length - 1;
7809
+ return 2n * numberOfLeaves - BigInt(numberOfPeaks);
7810
+ }
7811
+ async function generateRootWithProof(postRequest, treeSize) {
7812
+ const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7813
+ const { commitment: hash, encodePacked: encodePacked4 } = postRequestCommitment(postRequest);
7814
+ const result = JSON.parse(generate_root_with_proof2(hexToBytes(encodePacked4), treeSize));
7815
+ const { root, proof, mmr_size, leaf_positions, keccak_hash_calldata } = result;
7816
+ if (keccak_hash_calldata !== hash) {
7817
+ console.log("keccak_hash", keccak_hash_calldata);
7818
+ console.log("hash", hash);
7819
+ throw new Error("Abi keccak hash mismatch");
7820
+ }
7821
+ const [[, kIndex]] = mmrPositionToKIndex(leaf_positions, BigInt(mmr_size));
7822
+ return {
7823
+ root,
7824
+ proof,
7825
+ index: treeSize - 1n,
7826
+ kIndex,
7827
+ treeSize,
7828
+ mmrSize: mmr_size
7829
+ };
7830
+ }
7831
+ async function load_ckb_mmr() {
7832
+ if (hasWindow) {
7833
+ const wasm2 = await Promise.resolve().then(() => (init_node(), node_exports));
7834
+ await wasm2.default();
7835
+ return wasm2;
7836
+ }
7837
+ if (isNode) {
7838
+ const wasm2 = await Promise.resolve().then(() => (init_node(), node_exports));
7839
+ return wasm2;
7840
+ }
7841
+ throw new Error(`SDK not setup for ${env}`);
7842
+ }
7843
+ async function __test() {
7844
+ const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7845
+ return generate_root_with_proof2(new Uint8Array(), 120n);
7846
+ }
7847
+
7583
7848
  // src/utils.ts
7584
7849
  var DEFAULT_POLL_INTERVAL = 5e3;
7585
7850
  var ADDRESS_ZERO2 = "0x0000000000000000000000000000000000000000";
@@ -14826,6 +15091,34 @@ async function convertGasToFeeToken(ctx, gasEstimate, gasEstimateIn, evmChainID,
14826
15091
  return parseUnits(gasCostInFeeToken.toFixed(feeToken.decimals), feeToken.decimals);
14827
15092
  }
14828
15093
  }
15094
+ async function convertFeeTokenToWei(ctx, feeTokenAmount, feeTokenIn, evmChainID) {
15095
+ const chain = ctx[feeTokenIn];
15096
+ const client = chain.client;
15097
+ const wethAddr = chain.configService.getWrappedNativeAssetWithDecimals(evmChainID).asset;
15098
+ const feeToken = await getFeeToken(ctx, evmChainID, chain);
15099
+ try {
15100
+ const { amountOut } = await ctx.swap.findBestProtocolWithAmountIn(
15101
+ client,
15102
+ feeToken.address,
15103
+ wethAddr,
15104
+ feeTokenAmount,
15105
+ evmChainID,
15106
+ { selectedProtocol: "v2" }
15107
+ );
15108
+ if (amountOut === 0n) {
15109
+ throw new Error();
15110
+ }
15111
+ return amountOut;
15112
+ } catch {
15113
+ const nativeCurrency = client.chain?.nativeCurrency;
15114
+ const chainId = Number.parseInt(evmChainID.split("-")[1]);
15115
+ const feeTokenAmountInToken = new Decimal2(formatUnits(feeTokenAmount, feeToken.decimals));
15116
+ const nativeTokenPriceUsd = await fetchPrice(nativeCurrency?.symbol, chainId);
15117
+ const feeTokenAmountUsd = feeTokenAmountInToken.times(new Decimal2(1));
15118
+ const nativeAmount = feeTokenAmountUsd.dividedBy(nativeTokenPriceUsd);
15119
+ return parseUnits(nativeAmount.toFixed(nativeCurrency?.decimals ?? 18), nativeCurrency?.decimals ?? 18);
15120
+ }
15121
+ }
14829
15122
 
14830
15123
  // src/protocols/intents/OrderPlacer.ts
14831
15124
  var OrderPlacer = class {
@@ -15157,21 +15450,20 @@ var OrderCanceller = class {
15157
15450
  this.ctx = ctx;
15158
15451
  }
15159
15452
  /**
15160
- * Quotes the native token cost of cancelling an order from the given chain.
15161
- *
15162
- * For same-chain orders the cost is zero. For cross-chain orders, the
15163
- * quote covers the ISMP GET/POST dispatch fee.
15453
+ * Returns both the native token cost and the relayer fee for cancelling an
15454
+ * order. Frontends can use `relayerFee` to approve the ERC-20 spend before
15455
+ * submitting the cancel transaction.
15164
15456
  *
15165
- * @param order - The order to quote a cancellation for.
15166
- * @param fromDest - If `true`, quotes the destination-initiated cancellation fee.
15167
- * Defaults to `false` (source-side cancellation).
15168
- * @returns The native token amount required to submit the cancel transaction.
15457
+ * @param order - The order to quote.
15458
+ * @param fromDest - If `true`, quotes the destination-initiated path.
15459
+ * @returns `{ nativeValue }` — native token amount (wei) to send as `value`;
15460
+ * `{ relayerFee }` relayer incentive denominated in the chain's fee token.
15169
15461
  */
15170
- async quoteCancelNative(order, fromDest = false) {
15462
+ async quoteCancelOrder(order, fromDest = false) {
15171
15463
  if (fromDest) {
15172
- return this.quoteCancelNativeFromDest(order);
15464
+ return this.quoteCancelFromDest(order);
15173
15465
  }
15174
- return this.quoteCancelNativeFromSource(order);
15466
+ return this.quoteCancelFromSource(order);
15175
15467
  }
15176
15468
  /**
15177
15469
  * Quotes the native token cost of a source-initiated cross-chain cancellation.
@@ -15183,8 +15475,9 @@ var OrderCanceller = class {
15183
15475
  * @param order - The order to quote.
15184
15476
  * @returns The native token dispatch fee in wei.
15185
15477
  */
15186
- async quoteCancelNativeFromSource(order) {
15187
- if (order.source === order.destination) return 0n;
15478
+ async quoteCancelFromSource(order) {
15479
+ if (order.source === order.destination) return { nativeValue: 0n, relayerFee: 0n };
15480
+ const sourceStateMachine = order.source.startsWith("0x") ? hexToString(order.source) : order.source;
15188
15481
  const height = order.deadline + 1n;
15189
15482
  const destIntentGateway = this.ctx.dest.configService.getIntentGatewayV2Address(
15190
15483
  hexToString(order.destination)
@@ -15198,7 +15491,7 @@ var OrderCanceller = class {
15198
15491
  const key = concatHex([destIntentGateway, slotHash]);
15199
15492
  const context = encodeWithdrawalRequest(order, order.user);
15200
15493
  const getRequest = {
15201
- source: order.source.startsWith("0x") ? hexToString(order.source) : order.source,
15494
+ source: sourceStateMachine,
15202
15495
  dest: order.destination.startsWith("0x") ? hexToString(order.destination) : order.destination,
15203
15496
  from: this.ctx.source.configService.getIntentGatewayV2Address(hexToString(order.destination)),
15204
15497
  nonce: await this.ctx.source.getHostNonce(),
@@ -15207,7 +15500,10 @@ var OrderCanceller = class {
15207
15500
  timeoutTimestamp: 0n,
15208
15501
  context
15209
15502
  };
15210
- return await this.ctx.source.quoteNative(getRequest, 0n);
15503
+ const feeInSourceFeeToken = await convertGasToFeeToken(this.ctx, 400000n, "source", sourceStateMachine);
15504
+ const relayerFee = feeInSourceFeeToken * 1005n / 1000n;
15505
+ const nativeValue = await this.ctx.source.quoteNative(getRequest, relayerFee);
15506
+ return { nativeValue, relayerFee };
15211
15507
  }
15212
15508
  /**
15213
15509
  * Async generator that cancels an order and streams status events until
@@ -15302,17 +15598,17 @@ var OrderCanceller = class {
15302
15598
  STORAGE_KEYS.getRequest(orderId)
15303
15599
  );
15304
15600
  if (!getRequest) {
15305
- const value = await this.quoteCancelNativeFromSource(order);
15601
+ const quote = await this.quoteCancelFromSource(order);
15306
15602
  const data = encodeFunctionData({
15307
15603
  abi: ABI7,
15308
15604
  functionName: "cancelOrder",
15309
- args: [transformOrderForContract(order), { relayerFee: 0n, height: destIProof.height }]
15605
+ args: [transformOrderForContract(order), { relayerFee: quote.relayerFee, height: destIProof.height }]
15310
15606
  });
15311
15607
  const signedTransaction = yield {
15312
15608
  status: "AWAITING_CANCEL_TRANSACTION",
15313
15609
  data,
15314
15610
  to: intentGatewayAddress,
15315
- value
15611
+ value: quote.nativeValue
15316
15612
  };
15317
15613
  const receipt = signedTransaction.length === 66 ? await this.ctx.source.getTransactionReceipt(signedTransaction) : await this.ctx.source.broadcastTransaction(signedTransaction);
15318
15614
  const events = parseEventLogs({ abi: evmHost_default.ABI, logs: receipt.logs });
@@ -15397,8 +15693,8 @@ var OrderCanceller = class {
15397
15693
  * @param order - The order to quote.
15398
15694
  * @returns The native token dispatch fee in wei.
15399
15695
  */
15400
- async quoteCancelNativeFromDest(order) {
15401
- if (order.source === order.destination) return 0n;
15696
+ async quoteCancelFromDest(order) {
15697
+ if (order.source === order.destination) return { nativeValue: 0n, relayerFee: 0n };
15402
15698
  const destStateMachine = order.destination.startsWith("0x") ? hexToString(order.destination) : order.destination;
15403
15699
  const sourceStateMachine = order.source.startsWith("0x") ? hexToString(order.source) : order.source;
15404
15700
  const destIntentGateway = this.ctx.dest.configService.getIntentGatewayV2Address(destStateMachine);
@@ -15414,7 +15710,8 @@ var OrderCanceller = class {
15414
15710
  body,
15415
15711
  timeoutTimestamp: 0n
15416
15712
  };
15417
- return await this.ctx.dest.quoteNative(postRequest, relayerFee);
15713
+ const nativeValue = await this.ctx.dest.quoteNative(postRequest, relayerFee);
15714
+ return { nativeValue, relayerFee };
15418
15715
  }
15419
15716
  /**
15420
15717
  * Async generator that cancels an order by initiating from the destination
@@ -15447,17 +15744,17 @@ var OrderCanceller = class {
15447
15744
  STORAGE_KEYS.postCommitment(orderId)
15448
15745
  );
15449
15746
  if (!commitment) {
15450
- const value = await this.quoteCancelNativeFromDest(order);
15747
+ const quote = await this.quoteCancelFromDest(order);
15451
15748
  const data = encodeFunctionData({
15452
15749
  abi: ABI7,
15453
15750
  functionName: "cancelOrder",
15454
- args: [transformOrderForContract(order), { relayerFee: 0n, height: 0n }]
15751
+ args: [transformOrderForContract(order), { relayerFee: quote.relayerFee, height: 0n }]
15455
15752
  });
15456
15753
  const signedTransaction = yield {
15457
15754
  status: "AWAITING_CANCEL_TRANSACTION",
15458
15755
  data,
15459
15756
  to: intentGatewayAddress,
15460
- value
15757
+ value: quote.nativeValue
15461
15758
  };
15462
15759
  const receipt = signedTransaction.length === 66 ? await this.ctx.dest.getTransactionReceipt(signedTransaction) : await this.ctx.dest.broadcastTransaction(signedTransaction);
15463
15760
  yield {
@@ -17887,7 +18184,7 @@ var GasEstimator = class {
17887
18184
  }
17888
18185
  }
17889
18186
  const totalGas = callGasLimit + verificationGasLimit + preVerificationGas;
17890
- const totalGasCostWei = totalGas * maxFeePerGas;
18187
+ const rawTotalGasCostWei = totalGas * maxFeePerGas;
17891
18188
  const totalGasInDestFeeToken = await convertGasToFeeToken(
17892
18189
  this.ctx,
17893
18190
  totalGas,
@@ -17895,11 +18192,8 @@ var GasEstimator = class {
17895
18192
  destStateMachineId,
17896
18193
  gasPrice
17897
18194
  );
17898
- const totalGasInSourceFeeToken = adjustDecimals(
17899
- totalGasInDestFeeToken,
17900
- destFeeToken.decimals,
17901
- sourceFeeToken.decimals
17902
- );
18195
+ const totalGasInSourceFeeToken = isSameChain ? totalGasInDestFeeToken : adjustDecimals(totalGasInDestFeeToken, destFeeToken.decimals, sourceFeeToken.decimals);
18196
+ const totalGasCostWei = isSameChain ? rawTotalGasCostWei : await convertFeeTokenToWei(this.ctx, totalGasInSourceFeeToken, "source", souceStateMachineId);
17903
18197
  return {
17904
18198
  callGasLimit,
17905
18199
  verificationGasLimit,
@@ -18340,17 +18634,18 @@ var IntentGateway = class _IntentGateway {
18340
18634
  return;
18341
18635
  }
18342
18636
  /**
18343
- * Quotes the native token cost for cancelling an order.
18637
+ * Returns both the native token cost and the relayer fee for cancelling an
18638
+ * order. Use `relayerFee` to approve the ERC-20 spend before submitting.
18344
18639
  *
18345
- * Delegates to {@link OrderCanceller.quoteCancelNative}.
18640
+ * Delegates to {@link OrderCanceller.quoteCancelOrder}.
18346
18641
  *
18347
18642
  * @param order - The order to quote cancellation for.
18348
18643
  * @param fromDest - If `true`, quotes the destination-initiated cancellation fee.
18349
- * Defaults to `false` (source-side cancellation).
18350
- * @returns The native token amount required to submit the cancel transaction.
18644
+ * @returns `{ nativeValue }` — native token amount (wei) to send as `value`;
18645
+ * `{ relayerFee }` relayer incentive denominated in the chain's fee token.
18351
18646
  */
18352
- async quoteCancelNative(order, fromDest = false) {
18353
- return this.orderCanceller.quoteCancelNative(order, fromDest);
18647
+ async quoteCancelOrder(order, fromDest = false) {
18648
+ return this.orderCanceller.quoteCancelOrder(order, fromDest);
18354
18649
  }
18355
18650
  /**
18356
18651
  * Async generator that cancels an order and streams status events until
@@ -18632,9 +18927,9 @@ async function fetchLocalAssetId(params) {
18632
18927
  const palletPrefix = xxhashAsU8a("TokenGateway", 128);
18633
18928
  const storagePrefix = xxhashAsU8a("LocalAssets", 128);
18634
18929
  const full_key = new Uint8Array([...palletPrefix, ...storagePrefix, ...assetId]);
18635
- const hexKey = bytesToHex(full_key);
18930
+ const hexKey2 = bytesToHex(full_key);
18636
18931
  const storage_value = await api.rpc.state.getStorage(
18637
- hexKey
18932
+ hexKey2
18638
18933
  );
18639
18934
  if (storage_value.isSome) {
18640
18935
  const assetId2 = storage_value.value.toU8a();
@@ -18907,6 +19202,6 @@ async function teleportDot(param_) {
18907
19202
  return stream;
18908
19203
  }
18909
19204
 
18910
- export { ADDRESS_ZERO2 as ADDRESS_ZERO, BundlerMethod, ChainConfigService, Chains, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DOMAIN_TYPEHASH, DUMMY_PRIVATE_KEY, ERC20Method, ERC7821_BATCH_MODE, EvmChain, ABI as EvmHostABI, EvmLanguage, HyperClientStatus, IndexerClient, IntentGateway, ABI7 as IntentGatewayV2ABI, IntentOrderStatus, IntentsCoprocessor, MOCK_ADDRESS, ORDER_V2_PARAM_TYPE, OrderStatus, OrderStatusChecker, PACKED_USEROP_TYPEHASH, PLACE_ORDER_SELECTOR, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, RequestKind, RequestStatus, SELECT_SOLVER_TYPEHASH, STATE_COMMITMENTS_SLOT, SubstrateChain, Swap, TESTNET_CHAINS, TeleportStatus, TimeoutStatus, TokenGateway, TronChain, USE_ETHERSCAN_CHAINS, __test, adjustDecimals, bytes20ToBytes32, bytes32ToBytes20, calculateAllowanceMappingLocation, calculateBalanceMappingLocation, chainConfigs, constructRedeemEscrowRequestBody, constructRefundEscrowRequestBody, convertCodecToIGetRequest, convertCodecToIProof, convertIGetRequestToCodec, convertIProofToCodec, convertStateIdToStateMachineId, convertStateMachineEnumToString, convertStateMachineIdToEnum, createEvmChain, createQueryClient, decodeUserOpScale, encodeERC7821ExecuteBatch, encodeISMPMessage, encodeUserOpScale, encodeWithdrawalRequest, estimateGasForPost, fetchPrice, fetchSourceProof, generateRootWithProof, getChainId, getConfigByStateMachineId, getContractCallInput, getGasPriceFromEtherscan, getOrFetchStorageSlot, getOrderPlacedFromTx, getPostRequestEventFromTx, getPostResponseEventFromTx, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, getViemChain, hexToString, hyperbridgeAddress, maxBigInt, orderCommitment, parseStateMachineId, polkadotAssetHubPaseo, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, requestCommitmentKey, retryPromise, teleport, teleportDot, transformOrderForContract, tronChainIds, tronNile };
19205
+ export { ADDRESS_ZERO2 as ADDRESS_ZERO, BundlerMethod, ChainConfigService, Chains, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DOMAIN_TYPEHASH, DUMMY_PRIVATE_KEY, ERC20Method, ERC7821_BATCH_MODE, EvmChain, ABI as EvmHostABI, EvmLanguage, HyperClientStatus, IndexerClient, IntentGateway, ABI7 as IntentGatewayV2ABI, IntentOrderStatus, IntentsCoprocessor, MOCK_ADDRESS, ORDER_V2_PARAM_TYPE, OrderStatus, OrderStatusChecker, PACKED_USEROP_TYPEHASH, PLACE_ORDER_SELECTOR, PolkadotHubChain, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, RequestKind, RequestStatus, SELECT_SOLVER_TYPEHASH, STATE_COMMITMENTS_SLOT, SubstrateChain, Swap, TESTNET_CHAINS, TeleportStatus, TimeoutStatus, TokenGateway, TronChain, USE_ETHERSCAN_CHAINS, __test, adjustDecimals, bytes20ToBytes32, bytes32ToBytes20, calculateAllowanceMappingLocation, calculateBalanceMappingLocation, chainConfigs, constructRedeemEscrowRequestBody, constructRefundEscrowRequestBody, convertCodecToIGetRequest, convertCodecToIProof, convertIGetRequestToCodec, convertIProofToCodec, convertStateIdToStateMachineId, convertStateMachineEnumToString, convertStateMachineIdToEnum, createEvmChain, createQueryClient, decodeUserOpScale, encodeERC7821ExecuteBatch, encodeISMPMessage, encodeUserOpScale, encodeWithdrawalRequest, estimateGasForPost, fetchPrice, fetchSourceProof, generateRootWithProof, getChainId, getConfigByStateMachineId, getContractCallInput, getGasPriceFromEtherscan, getOrFetchStorageSlot, getOrderPlacedFromTx, getPostRequestEventFromTx, getPostResponseEventFromTx, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, getViemChain, hexToString, hyperbridgeAddress, maxBigInt, orderCommitment, parseStateMachineId, polkadotAssetHubPaseo, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, requestCommitmentKey, responseCommitmentKey, retryPromise, teleport, teleportDot, transformOrderForContract, tronChainIds, tronNile };
18911
19206
  //# sourceMappingURL=index.js.map
18912
19207
  //# sourceMappingURL=index.js.map