@hyperbridge/sdk 1.8.4 → 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";
@@ -18722,9 +18987,9 @@ async function fetchLocalAssetId(params) {
18722
18987
  const palletPrefix = xxhashAsU8a("TokenGateway", 128);
18723
18988
  const storagePrefix = xxhashAsU8a("LocalAssets", 128);
18724
18989
  const full_key = new Uint8Array([...palletPrefix, ...storagePrefix, ...assetId]);
18725
- const hexKey = bytesToHex(full_key);
18990
+ const hexKey2 = bytesToHex(full_key);
18726
18991
  const storage_value = await api.rpc.state.getStorage(
18727
- hexKey
18992
+ hexKey2
18728
18993
  );
18729
18994
  if (storage_value.isSome) {
18730
18995
  const assetId2 = storage_value.value.toU8a();
@@ -18997,6 +19262,6 @@ async function teleportDot(param_) {
18997
19262
  return stream;
18998
19263
  }
18999
19264
 
19000
- 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 };
19001
19266
  //# sourceMappingURL=index.js.map
19002
19267
  //# sourceMappingURL=index.js.map