@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.
@@ -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";
@@ -18662,9 +18927,9 @@ async function fetchLocalAssetId(params) {
18662
18927
  const palletPrefix = xxhashAsU8a("TokenGateway", 128);
18663
18928
  const storagePrefix = xxhashAsU8a("LocalAssets", 128);
18664
18929
  const full_key = new Uint8Array([...palletPrefix, ...storagePrefix, ...assetId]);
18665
- const hexKey = bytesToHex(full_key);
18930
+ const hexKey2 = bytesToHex(full_key);
18666
18931
  const storage_value = await api.rpc.state.getStorage(
18667
- hexKey
18932
+ hexKey2
18668
18933
  );
18669
18934
  if (storage_value.isSome) {
18670
18935
  const assetId2 = storage_value.value.toU8a();
@@ -18937,6 +19202,6 @@ async function teleportDot(param_) {
18937
19202
  return stream;
18938
19203
  }
18939
19204
 
18940
- 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 };
18941
19206
  //# sourceMappingURL=index.js.map
18942
19207
  //# sourceMappingURL=index.js.map