@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.
@@ -1,13 +1,13 @@
1
1
  import { createConsola, LogLevels } from 'consola';
2
2
  import { flatten, zip, capitalize, maxBy, isNil } from 'lodash-es';
3
- 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';
3
+ 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';
4
4
  import mergeRace from '@async-generator/merge-race';
5
5
  import { baseSepolia, optimismSepolia, arbitrumSepolia, soneium, gnosis, optimism, polygonAmoy, unichain, polygon, base, arbitrum, bsc, mainnet, sepolia, gnosisChiado, bscTestnet, tron } from 'viem/chains';
6
6
  import { TronWeb } from 'tronweb';
7
7
  import { match } from 'ts-pattern';
8
8
  import { WsProvider, ApiPromise, Keyring } from '@polkadot/api';
9
- import { Struct, Vector, u8, Bytes, Tuple, Enum, _void, u64, u32, Option, bool, u128 } from 'scale-ts';
10
- import { keccakAsU8a, decodeAddress, keccakAsHex, xxhashAsU8a } from '@polkadot/util-crypto';
9
+ import { Struct, Vector, u8, Bytes, Enum, Tuple, _void, u64, u32, Option, bool, u128 } from 'scale-ts';
10
+ import { keccakAsU8a, decodeAddress, keccakAsHex, xxhashAsU8a, blake2AsU8a } from '@polkadot/util-crypto';
11
11
  import { hexToU8a, u8aToHex, u8aConcat } from '@polkadot/util';
12
12
  import { hasWindow, isNode, env } from 'std-env';
13
13
  import { GraphQLClient } from 'graphql-request';
@@ -4368,6 +4368,8 @@ var getConfigByStateMachineId = (id) => configsByStateMachineId[id];
4368
4368
  var getChainId = (stateMachineId) => configsByStateMachineId[stateMachineId]?.chainId;
4369
4369
  var getViemChain = (chainId) => chainConfigs[chainId]?.viemChain;
4370
4370
  var hyperbridgeAddress = "";
4371
+
4372
+ // src/configs/ChainConfigService.ts
4371
4373
  var ChainConfigService = class {
4372
4374
  rpcUrls = {};
4373
4375
  constructor(env2 = process.env) {
@@ -4436,7 +4438,8 @@ var ChainConfigService = class {
4436
4438
  }
4437
4439
  getConsensusStateId(chain) {
4438
4440
  const id = this.getConfig(chain)?.consensusStateId;
4439
- return id ? toHex(id) : "0x";
4441
+ if (!id) throw new Error(`No consensusStateId configured for chain: ${chain}`);
4442
+ return id;
4440
4443
  }
4441
4444
  getHyperbridgeChainId() {
4442
4445
  return chainConfigs[4009]?.chainId ?? 4009;
@@ -5530,8 +5533,10 @@ var EvmChain = class _EvmChain {
5530
5533
  // Gnosis
5531
5534
  10200: "GNO0",
5532
5535
  // Gnosis Chiado
5533
- 420420417: "PAS0"
5536
+ 420420417: "PAS0",
5534
5537
  // Polkadot Asset Hub (Paseo)
5538
+ 420420419: "DOT0"
5539
+ // Polkadot Asset Hub (Polkadot)
5535
5540
  };
5536
5541
  if (!params.consensusStateId) {
5537
5542
  params.consensusStateId = defaultConsensusStateIds[params.chainId];
@@ -7110,143 +7115,20 @@ var TronChain = class _TronChain {
7110
7115
  return this.evm.estimateGas(request);
7111
7116
  }
7112
7117
  };
7113
- function getPeakPosByHeight(height) {
7114
- return (1n << BigInt(height + 1)) - 2n;
7115
- }
7116
- function leftPeakHeightPos(mmrSize) {
7117
- let height = 1;
7118
- let prevPos = 0n;
7119
- let pos = getPeakPosByHeight(height);
7120
- while (pos < mmrSize) {
7121
- height += 1;
7122
- prevPos = pos;
7123
- pos = getPeakPosByHeight(height);
7124
- }
7125
- return [height - 1, prevPos];
7126
- }
7127
- function getRightPeak(initialHeight, initialPos, mmrSize) {
7128
- let height = initialHeight;
7129
- let pos = initialPos;
7130
- pos += siblingOffset(height);
7131
- while (pos > mmrSize - 1n) {
7132
- if (height === 0) {
7133
- return null;
7134
- }
7135
- pos -= parentOffset(height - 1);
7136
- height -= 1;
7137
- }
7138
- return [height, pos];
7139
- }
7140
- function getPeaks(mmrSize) {
7141
- const positions = [];
7142
- let [height, pos] = leftPeakHeightPos(mmrSize);
7143
- positions.push(pos);
7144
- while (height > 0) {
7145
- const peak = getRightPeak(height, pos, mmrSize);
7146
- if (!peak) break;
7147
- [height, pos] = peak;
7148
- positions.push(pos);
7149
- }
7150
- return positions;
7151
- }
7152
- function allOnes(num) {
7153
- if (num === 0n) return false;
7154
- return num.toString(2).split("").every((bit) => bit === "1");
7155
- }
7156
- function jumpLeft(pos) {
7157
- const bitLength = pos.toString(2).length;
7158
- const mostSignificantBits = 1n << BigInt(bitLength - 1);
7159
- return pos - (mostSignificantBits - 1n);
7160
- }
7161
- function posHeightInTree(initialPos) {
7162
- let pos = initialPos + 1n;
7163
- while (!allOnes(pos)) {
7164
- pos = jumpLeft(pos);
7165
- }
7166
- return pos.toString(2).length - 1;
7167
- }
7168
- function parentOffset(height) {
7169
- return 2n << BigInt(height);
7170
- }
7171
- function siblingOffset(height) {
7172
- return (2n << BigInt(height)) - 1n;
7173
- }
7174
- function takeWhileVec(v, p) {
7175
- const index = v.findIndex((item) => !p(item));
7176
- if (index === -1) {
7177
- const result = [...v];
7178
- v.length = 0;
7179
- return result;
7180
- }
7181
- return v.splice(0, index);
7182
- }
7183
- function mmrPositionToKIndex(initialLeaves, mmrSize) {
7184
- const leaves = [...initialLeaves];
7185
- const peaks = getPeaks(mmrSize);
7186
- const leavesWithKIndices = [];
7187
- for (const peak of peaks) {
7188
- const peakLeaves = takeWhileVec(leaves, (pos) => pos <= peak);
7189
- if (peakLeaves.length > 0) {
7190
- for (const pos of peakLeaves) {
7191
- const height = posHeightInTree(peak);
7192
- let index = 0n;
7193
- let parentPos = peak;
7194
- for (let h = height; h >= 1; h--) {
7195
- const leftChild = parentPos - parentOffset(h - 1);
7196
- const rightChild = leftChild + siblingOffset(h - 1);
7197
- index *= 2n;
7198
- if (leftChild >= pos) {
7199
- parentPos = leftChild;
7200
- } else {
7201
- parentPos = rightChild;
7202
- index += 1n;
7203
- }
7204
- }
7205
- leavesWithKIndices.push([pos, index]);
7206
- }
7207
- }
7208
- }
7209
- return leavesWithKIndices;
7210
- }
7211
- function calculateMMRSize(numberOfLeaves) {
7212
- const numberOfPeaks = numberOfLeaves.toString(2).split("1").length - 1;
7213
- return 2n * numberOfLeaves - BigInt(numberOfPeaks);
7214
- }
7215
- async function generateRootWithProof(postRequest, treeSize) {
7216
- const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7217
- const { commitment: hash, encodePacked: encodePacked4 } = postRequestCommitment(postRequest);
7218
- const result = JSON.parse(generate_root_with_proof2(hexToBytes(encodePacked4), treeSize));
7219
- const { root, proof, mmr_size, leaf_positions, keccak_hash_calldata } = result;
7220
- if (keccak_hash_calldata !== hash) {
7221
- console.log("keccak_hash", keccak_hash_calldata);
7222
- console.log("hash", hash);
7223
- throw new Error("Abi keccak hash mismatch");
7224
- }
7225
- const [[, kIndex]] = mmrPositionToKIndex(leaf_positions, BigInt(mmr_size));
7226
- return {
7227
- root,
7228
- proof,
7229
- index: treeSize - 1n,
7230
- kIndex,
7231
- treeSize,
7232
- mmrSize: mmr_size
7233
- };
7234
- }
7235
- async function load_ckb_mmr() {
7236
- if (hasWindow) {
7237
- const wasm2 = await Promise.resolve().then(() => (init_web(), web_exports));
7238
- await wasm2.default();
7239
- return wasm2;
7240
- }
7241
- if (isNode) {
7242
- const wasm2 = await Promise.resolve().then(() => (init_web(), web_exports));
7243
- return wasm2;
7244
- }
7245
- throw new Error(`SDK not setup for ${env}`);
7246
- }
7247
- async function __test() {
7248
- const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7249
- return generate_root_with_proof2(new Uint8Array(), 120n);
7118
+ var ReviveContractInfo = Struct({
7119
+ trie_id: Vector(u8)
7120
+ });
7121
+ var ReviveAccountType = Enum({
7122
+ Contract: ReviveContractInfo
7123
+ });
7124
+ var ReviveAccountInfo = Struct({
7125
+ account_type: ReviveAccountType
7126
+ });
7127
+ function decodeReviveContractTrieId(accountData) {
7128
+ const {
7129
+ account_type: { value }
7130
+ } = ReviveAccountInfo.dec(accountData);
7131
+ return value.trie_id;
7250
7132
  }
7251
7133
  var H256 = Vector(u8, 32);
7252
7134
  var EvmStateProof = Struct({
@@ -7259,6 +7141,16 @@ var EvmStateProof = Struct({
7259
7141
  */
7260
7142
  storageProof: Vector(Tuple(Vector(u8), Vector(Vector(u8))))
7261
7143
  });
7144
+ var SubstrateEvmProof = Struct({
7145
+ main_proof: Vector(Vector(u8)),
7146
+ storage_proof: Vector(Tuple(Vector(u8), Vector(Vector(u8))))
7147
+ });
7148
+ function encodeSubstrateEvmProofBytes(params) {
7149
+ return SubstrateEvmProof.enc({
7150
+ main_proof: params.mainProof,
7151
+ storage_proof: Array.from(params.storageProof.entries())
7152
+ });
7153
+ }
7262
7154
  var SubstrateHashing = Enum({
7263
7155
  /* For chains that use keccak as their hashing algo */
7264
7156
  Keccak: _void,
@@ -7630,6 +7522,379 @@ var Message = Enum({
7630
7522
  TimeoutMessage
7631
7523
  });
7632
7524
 
7525
+ // src/chains/polkadotHub.ts
7526
+ var DEFAULT_CHILD_STORAGE_PREFIX = new TextEncoder().encode(":child_storage:default:");
7527
+ var SubstrateHttpRpc = class {
7528
+ constructor(url) {
7529
+ this.url = url;
7530
+ }
7531
+ async call(method, params = []) {
7532
+ const body = JSON.stringify({
7533
+ jsonrpc: "2.0",
7534
+ id: Date.now(),
7535
+ method,
7536
+ params
7537
+ });
7538
+ const response = await fetch(this.url, {
7539
+ method: "POST",
7540
+ headers: { "Content-Type": "application/json" },
7541
+ body
7542
+ });
7543
+ if (!response.ok) {
7544
+ throw new Error(`Substrate RPC HTTP error: ${response.status}`);
7545
+ }
7546
+ const json = await response.json();
7547
+ if (json.error) {
7548
+ throw new Error(`Substrate RPC error: ${json.error.message}`);
7549
+ }
7550
+ return json.result;
7551
+ }
7552
+ };
7553
+ function contractInfoKey(address20) {
7554
+ const key = new Uint8Array(16 + 16 + 20);
7555
+ key.set(xxhashAsU8a("Revive", 128), 0);
7556
+ key.set(xxhashAsU8a("AccountInfoOf", 128), 16);
7557
+ key.set(address20, 32);
7558
+ return key;
7559
+ }
7560
+ function childPrefixedStorageKey(trieId) {
7561
+ return u8aConcat(DEFAULT_CHILD_STORAGE_PREFIX, trieId);
7562
+ }
7563
+ function storageKeyForSlot(slot32) {
7564
+ return blake2AsU8a(slot32, 256);
7565
+ }
7566
+ function hexKey(k) {
7567
+ return bytesToHex(k);
7568
+ }
7569
+ var PolkadotHubChain = class _PolkadotHubChain {
7570
+ constructor(params, evm) {
7571
+ this.params = params;
7572
+ this.evm = evm;
7573
+ this.substrateRpc = new SubstrateHttpRpc(replaceWebsocketWithHttp(params.substrateRpcUrl));
7574
+ }
7575
+ evm;
7576
+ substrateRpc;
7577
+ static fromParams(params) {
7578
+ const { substrateRpcUrl, ...evmParams } = params;
7579
+ const evm = EvmChain.fromParams(evmParams);
7580
+ return new _PolkadotHubChain(params, evm);
7581
+ }
7582
+ /**
7583
+ * Creates a `PolkadotHubChain` by auto-detecting the EVM chain ID and `IsmpHost` address via
7584
+ * {@link EvmChain.create}, plus a Substrate RPC URL for Revive child-trie proofs.
7585
+ *
7586
+ * @param evmRpcUrl - HTTP(S) JSON-RPC URL of the EVM (Revive) node
7587
+ * @param substrateRpcUrl - Substrate node RPC (HTTP or WebSocket) for proof queries
7588
+ * @param bundlerUrl - Optional ERC-4337 bundler URL (forwarded to `EvmChain.create`)
7589
+ */
7590
+ static async create(evmRpcUrl, substrateRpcUrl, bundlerUrl) {
7591
+ const evm = await EvmChain.create(evmRpcUrl, bundlerUrl);
7592
+ const chainId = Number.parseInt(evm.config.stateMachineId.replace(/^EVM-/, ""), 10);
7593
+ if (!Number.isFinite(chainId)) {
7594
+ throw new Error(`Unexpected EVM stateMachineId: ${evm.config.stateMachineId}`);
7595
+ }
7596
+ const params = {
7597
+ chainId,
7598
+ rpcUrl: evm.config.rpcUrl,
7599
+ host: evm.config.host,
7600
+ consensusStateId: evm.config.consensusStateId,
7601
+ bundlerUrl: evm.bundlerUrl,
7602
+ substrateRpcUrl
7603
+ };
7604
+ return new _PolkadotHubChain(params, evm);
7605
+ }
7606
+ get client() {
7607
+ return this.evm.client;
7608
+ }
7609
+ get host() {
7610
+ return this.evm.host;
7611
+ }
7612
+ get bundlerUrl() {
7613
+ return this.evm.bundlerUrl;
7614
+ }
7615
+ get configService() {
7616
+ return this.evm.configService;
7617
+ }
7618
+ get config() {
7619
+ return {
7620
+ ...this.evm.config,
7621
+ substrateRpcUrl: this.params.substrateRpcUrl
7622
+ };
7623
+ }
7624
+ hostAddress20() {
7625
+ return hexToBytes(getAddress(this.evm.host));
7626
+ }
7627
+ async fetchCombinedProof(at, queries) {
7628
+ const height = Number(at);
7629
+ if (!Number.isSafeInteger(height) || height < 0) {
7630
+ throw new Error("Block height must be a non-negative safe integer for Substrate RPC");
7631
+ }
7632
+ const blockHash = await this.substrateRpc.call("chain_getBlockHash", [height]);
7633
+ if (!blockHash) {
7634
+ throw new Error(`Block hash not found for height ${height}`);
7635
+ }
7636
+ const mainKeys = [];
7637
+ const childInfoByAddr = /* @__PURE__ */ new Map();
7638
+ const contractEntries = [...queries.entries()];
7639
+ for (const [addr20] of contractEntries) {
7640
+ const infoKey = contractInfoKey(addr20);
7641
+ const storageHex = await this.substrateRpc.call("state_getStorage", [hexKey(infoKey), blockHash]);
7642
+ if (!storageHex) {
7643
+ throw new Error(`Revive AccountInfo not found for contract ${hexKey(addr20)}`);
7644
+ }
7645
+ const trieId = decodeReviveContractTrieId(hexToBytes(storageHex));
7646
+ const prefixed = childPrefixedStorageKey(trieId);
7647
+ mainKeys.push(hexKey(infoKey));
7648
+ mainKeys.push(hexKey(prefixed));
7649
+ childInfoByAddr.set(hexKey(addr20), { trieId, prefixed });
7650
+ }
7651
+ const mainRead = await this.substrateRpc.call("state_getReadProof", [mainKeys, blockHash]);
7652
+ const mainProofBytes = mainRead.proof.map((p) => hexToBytes(p));
7653
+ const storageProofEncoded = /* @__PURE__ */ new Map();
7654
+ for (const [addr20, innerKeys] of contractEntries) {
7655
+ const addrHex = hexKey(addr20);
7656
+ const info = childInfoByAddr.get(addrHex);
7657
+ if (!info) {
7658
+ throw new Error("Internal error: missing child info for contract");
7659
+ }
7660
+ const childKeysHex = innerKeys.map((k) => hexKey(k));
7661
+ const childRead = await this.substrateRpc.call("state_getChildReadProof", [
7662
+ hexKey(info.prefixed),
7663
+ childKeysHex,
7664
+ blockHash
7665
+ ]);
7666
+ storageProofEncoded.set(
7667
+ addr20,
7668
+ childRead.proof.map((p) => hexToBytes(p))
7669
+ );
7670
+ }
7671
+ const encoded = encodeSubstrateEvmProofBytes({
7672
+ mainProof: mainProofBytes,
7673
+ storageProof: storageProofEncoded
7674
+ });
7675
+ return bytesToHex(encoded);
7676
+ }
7677
+ timestamp() {
7678
+ return this.evm.timestamp();
7679
+ }
7680
+ requestReceiptKey(commitment) {
7681
+ return this.evm.requestReceiptKey(commitment);
7682
+ }
7683
+ queryRequestReceipt(commitment) {
7684
+ return this.evm.queryRequestReceipt(commitment);
7685
+ }
7686
+ async queryProof(message, _counterparty, at) {
7687
+ if (at === void 0) {
7688
+ throw new Error("PolkadotHubChain.queryProof requires an explicit block height `at`");
7689
+ }
7690
+ const host = this.hostAddress20();
7691
+ const storageKeys = "Requests" in message ? message.Requests.map((c) => storageKeyForSlot(hexToBytes(requestCommitmentKey(c).slot1))) : message.Responses.map((c) => storageKeyForSlot(hexToBytes(responseCommitmentKey(c))));
7692
+ const q = /* @__PURE__ */ new Map();
7693
+ q.set(host, storageKeys);
7694
+ return this.fetchCombinedProof(at, q);
7695
+ }
7696
+ async queryStateProof(at, keys, _address) {
7697
+ const keyBytes = keys.map((k) => hexToBytes(k));
7698
+ const host = this.hostAddress20();
7699
+ if (keyBytes.every((k) => k.length === 32)) {
7700
+ const storageKeys = keyBytes.map((slot) => storageKeyForSlot(slot));
7701
+ const q = /* @__PURE__ */ new Map();
7702
+ q.set(host, storageKeys);
7703
+ return this.fetchCombinedProof(at, q);
7704
+ }
7705
+ if (keyBytes.every((k) => k.length === 52)) {
7706
+ const groups = /* @__PURE__ */ new Map();
7707
+ for (const full of keyBytes) {
7708
+ const addr = full.subarray(0, 20);
7709
+ const slot = full.subarray(20, 52);
7710
+ const h = hexKey(addr);
7711
+ const arr = groups.get(h) ?? [];
7712
+ arr.push(storageKeyForSlot(slot));
7713
+ groups.set(h, arr);
7714
+ }
7715
+ const q = /* @__PURE__ */ new Map();
7716
+ for (const [addrHex, sks] of groups) {
7717
+ q.set(hexToBytes(addrHex), sks);
7718
+ }
7719
+ return this.fetchCombinedProof(at, q);
7720
+ }
7721
+ throw new Error(
7722
+ "PolkadotHubChain.queryStateProof: keys must be either all 32-byte ISMP slots or all 52-byte (20-byte address + 32-byte slot) entries"
7723
+ );
7724
+ }
7725
+ encode(message) {
7726
+ return this.evm.encode(message);
7727
+ }
7728
+ latestStateMachineHeight(stateMachineId) {
7729
+ return this.evm.latestStateMachineHeight(stateMachineId);
7730
+ }
7731
+ challengePeriod(stateMachineId) {
7732
+ return this.evm.challengePeriod(stateMachineId);
7733
+ }
7734
+ stateMachineUpdateTime(stateMachineHeight) {
7735
+ return this.evm.stateMachineUpdateTime(stateMachineHeight);
7736
+ }
7737
+ getHostNonce() {
7738
+ return this.evm.getHostNonce();
7739
+ }
7740
+ quoteNative(request, fee) {
7741
+ return this.evm.quoteNative(request, fee);
7742
+ }
7743
+ getFeeTokenWithDecimals() {
7744
+ return this.evm.getFeeTokenWithDecimals();
7745
+ }
7746
+ getPlaceOrderCalldata(txHash, intentGatewayAddress) {
7747
+ return this.evm.getPlaceOrderCalldata(txHash, intentGatewayAddress);
7748
+ }
7749
+ estimateGas(request) {
7750
+ return this.evm.estimateGas(request);
7751
+ }
7752
+ broadcastTransaction(signedTransaction) {
7753
+ return this.evm.broadcastTransaction(signedTransaction);
7754
+ }
7755
+ getTransactionReceipt(hash) {
7756
+ return this.evm.getTransactionReceipt(hash);
7757
+ }
7758
+ };
7759
+ function getPeakPosByHeight(height) {
7760
+ return (1n << BigInt(height + 1)) - 2n;
7761
+ }
7762
+ function leftPeakHeightPos(mmrSize) {
7763
+ let height = 1;
7764
+ let prevPos = 0n;
7765
+ let pos = getPeakPosByHeight(height);
7766
+ while (pos < mmrSize) {
7767
+ height += 1;
7768
+ prevPos = pos;
7769
+ pos = getPeakPosByHeight(height);
7770
+ }
7771
+ return [height - 1, prevPos];
7772
+ }
7773
+ function getRightPeak(initialHeight, initialPos, mmrSize) {
7774
+ let height = initialHeight;
7775
+ let pos = initialPos;
7776
+ pos += siblingOffset(height);
7777
+ while (pos > mmrSize - 1n) {
7778
+ if (height === 0) {
7779
+ return null;
7780
+ }
7781
+ pos -= parentOffset(height - 1);
7782
+ height -= 1;
7783
+ }
7784
+ return [height, pos];
7785
+ }
7786
+ function getPeaks(mmrSize) {
7787
+ const positions = [];
7788
+ let [height, pos] = leftPeakHeightPos(mmrSize);
7789
+ positions.push(pos);
7790
+ while (height > 0) {
7791
+ const peak = getRightPeak(height, pos, mmrSize);
7792
+ if (!peak) break;
7793
+ [height, pos] = peak;
7794
+ positions.push(pos);
7795
+ }
7796
+ return positions;
7797
+ }
7798
+ function allOnes(num) {
7799
+ if (num === 0n) return false;
7800
+ return num.toString(2).split("").every((bit) => bit === "1");
7801
+ }
7802
+ function jumpLeft(pos) {
7803
+ const bitLength = pos.toString(2).length;
7804
+ const mostSignificantBits = 1n << BigInt(bitLength - 1);
7805
+ return pos - (mostSignificantBits - 1n);
7806
+ }
7807
+ function posHeightInTree(initialPos) {
7808
+ let pos = initialPos + 1n;
7809
+ while (!allOnes(pos)) {
7810
+ pos = jumpLeft(pos);
7811
+ }
7812
+ return pos.toString(2).length - 1;
7813
+ }
7814
+ function parentOffset(height) {
7815
+ return 2n << BigInt(height);
7816
+ }
7817
+ function siblingOffset(height) {
7818
+ return (2n << BigInt(height)) - 1n;
7819
+ }
7820
+ function takeWhileVec(v, p) {
7821
+ const index = v.findIndex((item) => !p(item));
7822
+ if (index === -1) {
7823
+ const result = [...v];
7824
+ v.length = 0;
7825
+ return result;
7826
+ }
7827
+ return v.splice(0, index);
7828
+ }
7829
+ function mmrPositionToKIndex(initialLeaves, mmrSize) {
7830
+ const leaves = [...initialLeaves];
7831
+ const peaks = getPeaks(mmrSize);
7832
+ const leavesWithKIndices = [];
7833
+ for (const peak of peaks) {
7834
+ const peakLeaves = takeWhileVec(leaves, (pos) => pos <= peak);
7835
+ if (peakLeaves.length > 0) {
7836
+ for (const pos of peakLeaves) {
7837
+ const height = posHeightInTree(peak);
7838
+ let index = 0n;
7839
+ let parentPos = peak;
7840
+ for (let h = height; h >= 1; h--) {
7841
+ const leftChild = parentPos - parentOffset(h - 1);
7842
+ const rightChild = leftChild + siblingOffset(h - 1);
7843
+ index *= 2n;
7844
+ if (leftChild >= pos) {
7845
+ parentPos = leftChild;
7846
+ } else {
7847
+ parentPos = rightChild;
7848
+ index += 1n;
7849
+ }
7850
+ }
7851
+ leavesWithKIndices.push([pos, index]);
7852
+ }
7853
+ }
7854
+ }
7855
+ return leavesWithKIndices;
7856
+ }
7857
+ function calculateMMRSize(numberOfLeaves) {
7858
+ const numberOfPeaks = numberOfLeaves.toString(2).split("1").length - 1;
7859
+ return 2n * numberOfLeaves - BigInt(numberOfPeaks);
7860
+ }
7861
+ async function generateRootWithProof(postRequest, treeSize) {
7862
+ const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7863
+ const { commitment: hash, encodePacked: encodePacked4 } = postRequestCommitment(postRequest);
7864
+ const result = JSON.parse(generate_root_with_proof2(hexToBytes(encodePacked4), treeSize));
7865
+ const { root, proof, mmr_size, leaf_positions, keccak_hash_calldata } = result;
7866
+ if (keccak_hash_calldata !== hash) {
7867
+ console.log("keccak_hash", keccak_hash_calldata);
7868
+ console.log("hash", hash);
7869
+ throw new Error("Abi keccak hash mismatch");
7870
+ }
7871
+ const [[, kIndex]] = mmrPositionToKIndex(leaf_positions, BigInt(mmr_size));
7872
+ return {
7873
+ root,
7874
+ proof,
7875
+ index: treeSize - 1n,
7876
+ kIndex,
7877
+ treeSize,
7878
+ mmrSize: mmr_size
7879
+ };
7880
+ }
7881
+ async function load_ckb_mmr() {
7882
+ if (hasWindow) {
7883
+ const wasm2 = await Promise.resolve().then(() => (init_web(), web_exports));
7884
+ await wasm2.default();
7885
+ return wasm2;
7886
+ }
7887
+ if (isNode) {
7888
+ const wasm2 = await Promise.resolve().then(() => (init_web(), web_exports));
7889
+ return wasm2;
7890
+ }
7891
+ throw new Error(`SDK not setup for ${env}`);
7892
+ }
7893
+ async function __test() {
7894
+ const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7895
+ return generate_root_with_proof2(new Uint8Array(), 120n);
7896
+ }
7897
+
7633
7898
  // src/utils.ts
7634
7899
  var DEFAULT_POLL_INTERVAL = 5e3;
7635
7900
  var ADDRESS_ZERO2 = "0x0000000000000000000000000000000000000000";
@@ -14886,6 +15151,34 @@ async function convertGasToFeeToken(ctx, gasEstimate, gasEstimateIn, evmChainID,
14886
15151
  return parseUnits(gasCostInFeeToken.toFixed(feeToken.decimals), feeToken.decimals);
14887
15152
  }
14888
15153
  }
15154
+ async function convertFeeTokenToWei(ctx, feeTokenAmount, feeTokenIn, evmChainID) {
15155
+ const chain = ctx[feeTokenIn];
15156
+ const client = chain.client;
15157
+ const wethAddr = chain.configService.getWrappedNativeAssetWithDecimals(evmChainID).asset;
15158
+ const feeToken = await getFeeToken(ctx, evmChainID, chain);
15159
+ try {
15160
+ const { amountOut } = await ctx.swap.findBestProtocolWithAmountIn(
15161
+ client,
15162
+ feeToken.address,
15163
+ wethAddr,
15164
+ feeTokenAmount,
15165
+ evmChainID,
15166
+ { selectedProtocol: "v2" }
15167
+ );
15168
+ if (amountOut === 0n) {
15169
+ throw new Error();
15170
+ }
15171
+ return amountOut;
15172
+ } catch {
15173
+ const nativeCurrency = client.chain?.nativeCurrency;
15174
+ const chainId = Number.parseInt(evmChainID.split("-")[1]);
15175
+ const feeTokenAmountInToken = new Decimal2(formatUnits(feeTokenAmount, feeToken.decimals));
15176
+ const nativeTokenPriceUsd = await fetchPrice(nativeCurrency?.symbol, chainId);
15177
+ const feeTokenAmountUsd = feeTokenAmountInToken.times(new Decimal2(1));
15178
+ const nativeAmount = feeTokenAmountUsd.dividedBy(nativeTokenPriceUsd);
15179
+ return parseUnits(nativeAmount.toFixed(nativeCurrency?.decimals ?? 18), nativeCurrency?.decimals ?? 18);
15180
+ }
15181
+ }
14889
15182
 
14890
15183
  // src/protocols/intents/OrderPlacer.ts
14891
15184
  var OrderPlacer = class {
@@ -15217,21 +15510,20 @@ var OrderCanceller = class {
15217
15510
  this.ctx = ctx;
15218
15511
  }
15219
15512
  /**
15220
- * Quotes the native token cost of cancelling an order from the given chain.
15221
- *
15222
- * For same-chain orders the cost is zero. For cross-chain orders, the
15223
- * quote covers the ISMP GET/POST dispatch fee.
15513
+ * Returns both the native token cost and the relayer fee for cancelling an
15514
+ * order. Frontends can use `relayerFee` to approve the ERC-20 spend before
15515
+ * submitting the cancel transaction.
15224
15516
  *
15225
- * @param order - The order to quote a cancellation for.
15226
- * @param fromDest - If `true`, quotes the destination-initiated cancellation fee.
15227
- * Defaults to `false` (source-side cancellation).
15228
- * @returns The native token amount required to submit the cancel transaction.
15517
+ * @param order - The order to quote.
15518
+ * @param fromDest - If `true`, quotes the destination-initiated path.
15519
+ * @returns `{ nativeValue }` — native token amount (wei) to send as `value`;
15520
+ * `{ relayerFee }` relayer incentive denominated in the chain's fee token.
15229
15521
  */
15230
- async quoteCancelNative(order, fromDest = false) {
15522
+ async quoteCancelOrder(order, fromDest = false) {
15231
15523
  if (fromDest) {
15232
- return this.quoteCancelNativeFromDest(order);
15524
+ return this.quoteCancelFromDest(order);
15233
15525
  }
15234
- return this.quoteCancelNativeFromSource(order);
15526
+ return this.quoteCancelFromSource(order);
15235
15527
  }
15236
15528
  /**
15237
15529
  * Quotes the native token cost of a source-initiated cross-chain cancellation.
@@ -15243,8 +15535,9 @@ var OrderCanceller = class {
15243
15535
  * @param order - The order to quote.
15244
15536
  * @returns The native token dispatch fee in wei.
15245
15537
  */
15246
- async quoteCancelNativeFromSource(order) {
15247
- if (order.source === order.destination) return 0n;
15538
+ async quoteCancelFromSource(order) {
15539
+ if (order.source === order.destination) return { nativeValue: 0n, relayerFee: 0n };
15540
+ const sourceStateMachine = order.source.startsWith("0x") ? hexToString(order.source) : order.source;
15248
15541
  const height = order.deadline + 1n;
15249
15542
  const destIntentGateway = this.ctx.dest.configService.getIntentGatewayV2Address(
15250
15543
  hexToString(order.destination)
@@ -15258,7 +15551,7 @@ var OrderCanceller = class {
15258
15551
  const key = concatHex([destIntentGateway, slotHash]);
15259
15552
  const context = encodeWithdrawalRequest(order, order.user);
15260
15553
  const getRequest = {
15261
- source: order.source.startsWith("0x") ? hexToString(order.source) : order.source,
15554
+ source: sourceStateMachine,
15262
15555
  dest: order.destination.startsWith("0x") ? hexToString(order.destination) : order.destination,
15263
15556
  from: this.ctx.source.configService.getIntentGatewayV2Address(hexToString(order.destination)),
15264
15557
  nonce: await this.ctx.source.getHostNonce(),
@@ -15267,7 +15560,10 @@ var OrderCanceller = class {
15267
15560
  timeoutTimestamp: 0n,
15268
15561
  context
15269
15562
  };
15270
- return await this.ctx.source.quoteNative(getRequest, 0n);
15563
+ const feeInSourceFeeToken = await convertGasToFeeToken(this.ctx, 400000n, "source", sourceStateMachine);
15564
+ const relayerFee = feeInSourceFeeToken * 1005n / 1000n;
15565
+ const nativeValue = await this.ctx.source.quoteNative(getRequest, relayerFee);
15566
+ return { nativeValue, relayerFee };
15271
15567
  }
15272
15568
  /**
15273
15569
  * Async generator that cancels an order and streams status events until
@@ -15362,17 +15658,17 @@ var OrderCanceller = class {
15362
15658
  STORAGE_KEYS.getRequest(orderId)
15363
15659
  );
15364
15660
  if (!getRequest) {
15365
- const value = await this.quoteCancelNativeFromSource(order);
15661
+ const quote = await this.quoteCancelFromSource(order);
15366
15662
  const data = encodeFunctionData({
15367
15663
  abi: ABI7,
15368
15664
  functionName: "cancelOrder",
15369
- args: [transformOrderForContract(order), { relayerFee: 0n, height: destIProof.height }]
15665
+ args: [transformOrderForContract(order), { relayerFee: quote.relayerFee, height: destIProof.height }]
15370
15666
  });
15371
15667
  const signedTransaction = yield {
15372
15668
  status: "AWAITING_CANCEL_TRANSACTION",
15373
15669
  data,
15374
15670
  to: intentGatewayAddress,
15375
- value
15671
+ value: quote.nativeValue
15376
15672
  };
15377
15673
  const receipt = signedTransaction.length === 66 ? await this.ctx.source.getTransactionReceipt(signedTransaction) : await this.ctx.source.broadcastTransaction(signedTransaction);
15378
15674
  const events = parseEventLogs({ abi: evmHost_default.ABI, logs: receipt.logs });
@@ -15457,8 +15753,8 @@ var OrderCanceller = class {
15457
15753
  * @param order - The order to quote.
15458
15754
  * @returns The native token dispatch fee in wei.
15459
15755
  */
15460
- async quoteCancelNativeFromDest(order) {
15461
- if (order.source === order.destination) return 0n;
15756
+ async quoteCancelFromDest(order) {
15757
+ if (order.source === order.destination) return { nativeValue: 0n, relayerFee: 0n };
15462
15758
  const destStateMachine = order.destination.startsWith("0x") ? hexToString(order.destination) : order.destination;
15463
15759
  const sourceStateMachine = order.source.startsWith("0x") ? hexToString(order.source) : order.source;
15464
15760
  const destIntentGateway = this.ctx.dest.configService.getIntentGatewayV2Address(destStateMachine);
@@ -15474,7 +15770,8 @@ var OrderCanceller = class {
15474
15770
  body,
15475
15771
  timeoutTimestamp: 0n
15476
15772
  };
15477
- return await this.ctx.dest.quoteNative(postRequest, relayerFee);
15773
+ const nativeValue = await this.ctx.dest.quoteNative(postRequest, relayerFee);
15774
+ return { nativeValue, relayerFee };
15478
15775
  }
15479
15776
  /**
15480
15777
  * Async generator that cancels an order by initiating from the destination
@@ -15507,17 +15804,17 @@ var OrderCanceller = class {
15507
15804
  STORAGE_KEYS.postCommitment(orderId)
15508
15805
  );
15509
15806
  if (!commitment) {
15510
- const value = await this.quoteCancelNativeFromDest(order);
15807
+ const quote = await this.quoteCancelFromDest(order);
15511
15808
  const data = encodeFunctionData({
15512
15809
  abi: ABI7,
15513
15810
  functionName: "cancelOrder",
15514
- args: [transformOrderForContract(order), { relayerFee: 0n, height: 0n }]
15811
+ args: [transformOrderForContract(order), { relayerFee: quote.relayerFee, height: 0n }]
15515
15812
  });
15516
15813
  const signedTransaction = yield {
15517
15814
  status: "AWAITING_CANCEL_TRANSACTION",
15518
15815
  data,
15519
15816
  to: intentGatewayAddress,
15520
- value
15817
+ value: quote.nativeValue
15521
15818
  };
15522
15819
  const receipt = signedTransaction.length === 66 ? await this.ctx.dest.getTransactionReceipt(signedTransaction) : await this.ctx.dest.broadcastTransaction(signedTransaction);
15523
15820
  yield {
@@ -17947,7 +18244,7 @@ var GasEstimator = class {
17947
18244
  }
17948
18245
  }
17949
18246
  const totalGas = callGasLimit + verificationGasLimit + preVerificationGas;
17950
- const totalGasCostWei = totalGas * maxFeePerGas;
18247
+ const rawTotalGasCostWei = totalGas * maxFeePerGas;
17951
18248
  const totalGasInDestFeeToken = await convertGasToFeeToken(
17952
18249
  this.ctx,
17953
18250
  totalGas,
@@ -17955,11 +18252,8 @@ var GasEstimator = class {
17955
18252
  destStateMachineId,
17956
18253
  gasPrice
17957
18254
  );
17958
- const totalGasInSourceFeeToken = adjustDecimals(
17959
- totalGasInDestFeeToken,
17960
- destFeeToken.decimals,
17961
- sourceFeeToken.decimals
17962
- );
18255
+ const totalGasInSourceFeeToken = isSameChain ? totalGasInDestFeeToken : adjustDecimals(totalGasInDestFeeToken, destFeeToken.decimals, sourceFeeToken.decimals);
18256
+ const totalGasCostWei = isSameChain ? rawTotalGasCostWei : await convertFeeTokenToWei(this.ctx, totalGasInSourceFeeToken, "source", souceStateMachineId);
17963
18257
  return {
17964
18258
  callGasLimit,
17965
18259
  verificationGasLimit,
@@ -18400,17 +18694,18 @@ var IntentGateway = class _IntentGateway {
18400
18694
  return;
18401
18695
  }
18402
18696
  /**
18403
- * Quotes the native token cost for cancelling an order.
18697
+ * Returns both the native token cost and the relayer fee for cancelling an
18698
+ * order. Use `relayerFee` to approve the ERC-20 spend before submitting.
18404
18699
  *
18405
- * Delegates to {@link OrderCanceller.quoteCancelNative}.
18700
+ * Delegates to {@link OrderCanceller.quoteCancelOrder}.
18406
18701
  *
18407
18702
  * @param order - The order to quote cancellation for.
18408
18703
  * @param fromDest - If `true`, quotes the destination-initiated cancellation fee.
18409
- * Defaults to `false` (source-side cancellation).
18410
- * @returns The native token amount required to submit the cancel transaction.
18704
+ * @returns `{ nativeValue }` — native token amount (wei) to send as `value`;
18705
+ * `{ relayerFee }` relayer incentive denominated in the chain's fee token.
18411
18706
  */
18412
- async quoteCancelNative(order, fromDest = false) {
18413
- return this.orderCanceller.quoteCancelNative(order, fromDest);
18707
+ async quoteCancelOrder(order, fromDest = false) {
18708
+ return this.orderCanceller.quoteCancelOrder(order, fromDest);
18414
18709
  }
18415
18710
  /**
18416
18711
  * Async generator that cancels an order and streams status events until
@@ -18692,9 +18987,9 @@ async function fetchLocalAssetId(params) {
18692
18987
  const palletPrefix = xxhashAsU8a("TokenGateway", 128);
18693
18988
  const storagePrefix = xxhashAsU8a("LocalAssets", 128);
18694
18989
  const full_key = new Uint8Array([...palletPrefix, ...storagePrefix, ...assetId]);
18695
- const hexKey = bytesToHex(full_key);
18990
+ const hexKey2 = bytesToHex(full_key);
18696
18991
  const storage_value = await api.rpc.state.getStorage(
18697
- hexKey
18992
+ hexKey2
18698
18993
  );
18699
18994
  if (storage_value.isSome) {
18700
18995
  const assetId2 = storage_value.value.toU8a();
@@ -18967,6 +19262,6 @@ async function teleportDot(param_) {
18967
19262
  return stream;
18968
19263
  }
18969
19264
 
18970
- 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 };
19265
+ 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 };
18971
19266
  //# sourceMappingURL=index.js.map
18972
19267
  //# sourceMappingURL=index.js.map