@hyperbridge/sdk 1.8.4 → 1.8.6-rc.1

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,148 +7065,26 @@ 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({
7203
7085
  /**
7204
- * Proof of the contract state.
7086
+ * Proof of the contract state (EVM account trie) or, for Revive / Substrate EVM, the main state trie proof
7087
+ * (`AccountInfo` + child root) — same SCALE shape as `SubstrateEvmProof::main_proof` on the Rust side.
7205
7088
  */
7206
7089
  contractProof: Vector(Vector(u8)),
7207
7090
  /**
@@ -7580,6 +7463,379 @@ var Message = Enum({
7580
7463
  TimeoutMessage
7581
7464
  });
7582
7465
 
7466
+ // src/chains/polkadotHub.ts
7467
+ var DEFAULT_CHILD_STORAGE_PREFIX = new TextEncoder().encode(":child_storage:default:");
7468
+ var SubstrateHttpRpc = class {
7469
+ constructor(url) {
7470
+ this.url = url;
7471
+ }
7472
+ async call(method, params = []) {
7473
+ const body = JSON.stringify({
7474
+ jsonrpc: "2.0",
7475
+ id: Date.now(),
7476
+ method,
7477
+ params
7478
+ });
7479
+ const response = await fetch(this.url, {
7480
+ method: "POST",
7481
+ headers: { "Content-Type": "application/json" },
7482
+ body
7483
+ });
7484
+ if (!response.ok) {
7485
+ throw new Error(`Substrate RPC HTTP error: ${response.status}`);
7486
+ }
7487
+ const json = await response.json();
7488
+ if (json.error) {
7489
+ throw new Error(`Substrate RPC error: ${json.error.message}`);
7490
+ }
7491
+ return json.result;
7492
+ }
7493
+ };
7494
+ function contractInfoKey(address20) {
7495
+ const key = new Uint8Array(16 + 16 + 20);
7496
+ key.set(xxhashAsU8a("Revive", 128), 0);
7497
+ key.set(xxhashAsU8a("AccountInfoOf", 128), 16);
7498
+ key.set(address20, 32);
7499
+ return key;
7500
+ }
7501
+ function childPrefixedStorageKey(trieId) {
7502
+ return u8aConcat(DEFAULT_CHILD_STORAGE_PREFIX, trieId);
7503
+ }
7504
+ function storageKeyForSlot(slot32) {
7505
+ return blake2AsU8a(slot32, 256);
7506
+ }
7507
+ function hexKey(k) {
7508
+ return bytesToHex(k);
7509
+ }
7510
+ var PolkadotHubChain = class _PolkadotHubChain {
7511
+ constructor(params, evm) {
7512
+ this.params = params;
7513
+ this.evm = evm;
7514
+ this.substrateRpc = new SubstrateHttpRpc(replaceWebsocketWithHttp(params.substrateRpcUrl));
7515
+ }
7516
+ evm;
7517
+ substrateRpc;
7518
+ static fromParams(params) {
7519
+ const { substrateRpcUrl, ...evmParams } = params;
7520
+ const evm = EvmChain.fromParams(evmParams);
7521
+ return new _PolkadotHubChain(params, evm);
7522
+ }
7523
+ /**
7524
+ * Creates a `PolkadotHubChain` by auto-detecting the EVM chain ID and `IsmpHost` address via
7525
+ * {@link EvmChain.create}, plus a Substrate RPC URL for Revive child-trie proofs.
7526
+ *
7527
+ * @param evmRpcUrl - HTTP(S) JSON-RPC URL of the EVM (Revive) node
7528
+ * @param substrateRpcUrl - Substrate node RPC (HTTP or WebSocket) for proof queries
7529
+ * @param bundlerUrl - Optional ERC-4337 bundler URL (forwarded to `EvmChain.create`)
7530
+ */
7531
+ static async create(evmRpcUrl, substrateRpcUrl, bundlerUrl) {
7532
+ const evm = await EvmChain.create(evmRpcUrl, bundlerUrl);
7533
+ const chainId = Number.parseInt(evm.config.stateMachineId.replace(/^EVM-/, ""), 10);
7534
+ if (!Number.isFinite(chainId)) {
7535
+ throw new Error(`Unexpected EVM stateMachineId: ${evm.config.stateMachineId}`);
7536
+ }
7537
+ const params = {
7538
+ chainId,
7539
+ rpcUrl: evm.config.rpcUrl,
7540
+ host: evm.config.host,
7541
+ consensusStateId: evm.config.consensusStateId,
7542
+ bundlerUrl: evm.bundlerUrl,
7543
+ substrateRpcUrl
7544
+ };
7545
+ return new _PolkadotHubChain(params, evm);
7546
+ }
7547
+ get client() {
7548
+ return this.evm.client;
7549
+ }
7550
+ get host() {
7551
+ return this.evm.host;
7552
+ }
7553
+ get bundlerUrl() {
7554
+ return this.evm.bundlerUrl;
7555
+ }
7556
+ get configService() {
7557
+ return this.evm.configService;
7558
+ }
7559
+ get config() {
7560
+ return {
7561
+ ...this.evm.config,
7562
+ substrateRpcUrl: this.params.substrateRpcUrl
7563
+ };
7564
+ }
7565
+ hostAddress20() {
7566
+ return hexToBytes(getAddress(this.evm.host));
7567
+ }
7568
+ async fetchCombinedProof(at, queries) {
7569
+ const height = Number(at);
7570
+ if (!Number.isSafeInteger(height) || height < 0) {
7571
+ throw new Error("Block height must be a non-negative safe integer for Substrate RPC");
7572
+ }
7573
+ const blockHash = await this.substrateRpc.call("chain_getBlockHash", [height]);
7574
+ if (!blockHash) {
7575
+ throw new Error(`Block hash not found for height ${height}`);
7576
+ }
7577
+ const mainKeys = [];
7578
+ const childInfoByAddr = /* @__PURE__ */ new Map();
7579
+ const contractEntries = [...queries.entries()];
7580
+ for (const [addr20] of contractEntries) {
7581
+ const infoKey = contractInfoKey(addr20);
7582
+ const storageHex = await this.substrateRpc.call("state_getStorage", [hexKey(infoKey), blockHash]);
7583
+ if (!storageHex) {
7584
+ throw new Error(`Revive AccountInfo not found for contract ${hexKey(addr20)}`);
7585
+ }
7586
+ const trieId = decodeReviveContractTrieId(hexToBytes(storageHex));
7587
+ const prefixed = childPrefixedStorageKey(trieId);
7588
+ mainKeys.push(hexKey(infoKey));
7589
+ mainKeys.push(hexKey(prefixed));
7590
+ childInfoByAddr.set(hexKey(addr20), { trieId, prefixed });
7591
+ }
7592
+ const mainRead = await this.substrateRpc.call("state_getReadProof", [mainKeys, blockHash]);
7593
+ const mainProofBytes = mainRead.proof.map((p) => hexToBytes(p));
7594
+ const storageProofEncoded = /* @__PURE__ */ new Map();
7595
+ for (const [addr20, innerKeys] of contractEntries) {
7596
+ const addrHex = hexKey(addr20);
7597
+ const info = childInfoByAddr.get(addrHex);
7598
+ if (!info) {
7599
+ throw new Error("Internal error: missing child info for contract");
7600
+ }
7601
+ const childKeysHex = innerKeys.map((k) => hexKey(k));
7602
+ const childRead = await this.substrateRpc.call("state_getChildReadProof", [
7603
+ hexKey(info.prefixed),
7604
+ childKeysHex,
7605
+ blockHash
7606
+ ]);
7607
+ storageProofEncoded.set(
7608
+ addr20,
7609
+ childRead.proof.map((p) => hexToBytes(p))
7610
+ );
7611
+ }
7612
+ const encoded = EvmStateProof.enc({
7613
+ contractProof: mainProofBytes,
7614
+ storageProof: Array.from(storageProofEncoded.entries())
7615
+ });
7616
+ return bytesToHex(encoded);
7617
+ }
7618
+ timestamp() {
7619
+ return this.evm.timestamp();
7620
+ }
7621
+ requestReceiptKey(commitment) {
7622
+ return this.evm.requestReceiptKey(commitment);
7623
+ }
7624
+ queryRequestReceipt(commitment) {
7625
+ return this.evm.queryRequestReceipt(commitment);
7626
+ }
7627
+ async queryProof(message, _counterparty, at) {
7628
+ if (at === void 0) {
7629
+ throw new Error("PolkadotHubChain.queryProof requires an explicit block height `at`");
7630
+ }
7631
+ const host = this.hostAddress20();
7632
+ const storageKeys = "Requests" in message ? message.Requests.map((c) => storageKeyForSlot(hexToBytes(requestCommitmentKey(c).slot1))) : message.Responses.map((c) => storageKeyForSlot(hexToBytes(responseCommitmentKey(c))));
7633
+ const q = /* @__PURE__ */ new Map();
7634
+ q.set(host, storageKeys);
7635
+ return this.fetchCombinedProof(at, q);
7636
+ }
7637
+ async queryStateProof(at, keys, _address) {
7638
+ const keyBytes = keys.map((k) => hexToBytes(k));
7639
+ const host = this.hostAddress20();
7640
+ if (keyBytes.every((k) => k.length === 32)) {
7641
+ const storageKeys = keyBytes.map((slot) => storageKeyForSlot(slot));
7642
+ const q = /* @__PURE__ */ new Map();
7643
+ q.set(host, storageKeys);
7644
+ return this.fetchCombinedProof(at, q);
7645
+ }
7646
+ if (keyBytes.every((k) => k.length === 52)) {
7647
+ const groups = /* @__PURE__ */ new Map();
7648
+ for (const full of keyBytes) {
7649
+ const addr = full.subarray(0, 20);
7650
+ const slot = full.subarray(20, 52);
7651
+ const h = hexKey(addr);
7652
+ const arr = groups.get(h) ?? [];
7653
+ arr.push(storageKeyForSlot(slot));
7654
+ groups.set(h, arr);
7655
+ }
7656
+ const q = /* @__PURE__ */ new Map();
7657
+ for (const [addrHex, sks] of groups) {
7658
+ q.set(hexToBytes(addrHex), sks);
7659
+ }
7660
+ return this.fetchCombinedProof(at, q);
7661
+ }
7662
+ throw new Error(
7663
+ "PolkadotHubChain.queryStateProof: keys must be either all 32-byte ISMP slots or all 52-byte (20-byte address + 32-byte slot) entries"
7664
+ );
7665
+ }
7666
+ encode(message) {
7667
+ return this.evm.encode(message);
7668
+ }
7669
+ latestStateMachineHeight(stateMachineId) {
7670
+ return this.evm.latestStateMachineHeight(stateMachineId);
7671
+ }
7672
+ challengePeriod(stateMachineId) {
7673
+ return this.evm.challengePeriod(stateMachineId);
7674
+ }
7675
+ stateMachineUpdateTime(stateMachineHeight) {
7676
+ return this.evm.stateMachineUpdateTime(stateMachineHeight);
7677
+ }
7678
+ getHostNonce() {
7679
+ return this.evm.getHostNonce();
7680
+ }
7681
+ quoteNative(request, fee) {
7682
+ return this.evm.quoteNative(request, fee);
7683
+ }
7684
+ getFeeTokenWithDecimals() {
7685
+ return this.evm.getFeeTokenWithDecimals();
7686
+ }
7687
+ getPlaceOrderCalldata(txHash, intentGatewayAddress) {
7688
+ return this.evm.getPlaceOrderCalldata(txHash, intentGatewayAddress);
7689
+ }
7690
+ estimateGas(request) {
7691
+ return this.evm.estimateGas(request);
7692
+ }
7693
+ broadcastTransaction(signedTransaction) {
7694
+ return this.evm.broadcastTransaction(signedTransaction);
7695
+ }
7696
+ getTransactionReceipt(hash) {
7697
+ return this.evm.getTransactionReceipt(hash);
7698
+ }
7699
+ };
7700
+ function getPeakPosByHeight(height) {
7701
+ return (1n << BigInt(height + 1)) - 2n;
7702
+ }
7703
+ function leftPeakHeightPos(mmrSize) {
7704
+ let height = 1;
7705
+ let prevPos = 0n;
7706
+ let pos = getPeakPosByHeight(height);
7707
+ while (pos < mmrSize) {
7708
+ height += 1;
7709
+ prevPos = pos;
7710
+ pos = getPeakPosByHeight(height);
7711
+ }
7712
+ return [height - 1, prevPos];
7713
+ }
7714
+ function getRightPeak(initialHeight, initialPos, mmrSize) {
7715
+ let height = initialHeight;
7716
+ let pos = initialPos;
7717
+ pos += siblingOffset(height);
7718
+ while (pos > mmrSize - 1n) {
7719
+ if (height === 0) {
7720
+ return null;
7721
+ }
7722
+ pos -= parentOffset(height - 1);
7723
+ height -= 1;
7724
+ }
7725
+ return [height, pos];
7726
+ }
7727
+ function getPeaks(mmrSize) {
7728
+ const positions = [];
7729
+ let [height, pos] = leftPeakHeightPos(mmrSize);
7730
+ positions.push(pos);
7731
+ while (height > 0) {
7732
+ const peak = getRightPeak(height, pos, mmrSize);
7733
+ if (!peak) break;
7734
+ [height, pos] = peak;
7735
+ positions.push(pos);
7736
+ }
7737
+ return positions;
7738
+ }
7739
+ function allOnes(num) {
7740
+ if (num === 0n) return false;
7741
+ return num.toString(2).split("").every((bit) => bit === "1");
7742
+ }
7743
+ function jumpLeft(pos) {
7744
+ const bitLength = pos.toString(2).length;
7745
+ const mostSignificantBits = 1n << BigInt(bitLength - 1);
7746
+ return pos - (mostSignificantBits - 1n);
7747
+ }
7748
+ function posHeightInTree(initialPos) {
7749
+ let pos = initialPos + 1n;
7750
+ while (!allOnes(pos)) {
7751
+ pos = jumpLeft(pos);
7752
+ }
7753
+ return pos.toString(2).length - 1;
7754
+ }
7755
+ function parentOffset(height) {
7756
+ return 2n << BigInt(height);
7757
+ }
7758
+ function siblingOffset(height) {
7759
+ return (2n << BigInt(height)) - 1n;
7760
+ }
7761
+ function takeWhileVec(v, p) {
7762
+ const index = v.findIndex((item) => !p(item));
7763
+ if (index === -1) {
7764
+ const result = [...v];
7765
+ v.length = 0;
7766
+ return result;
7767
+ }
7768
+ return v.splice(0, index);
7769
+ }
7770
+ function mmrPositionToKIndex(initialLeaves, mmrSize) {
7771
+ const leaves = [...initialLeaves];
7772
+ const peaks = getPeaks(mmrSize);
7773
+ const leavesWithKIndices = [];
7774
+ for (const peak of peaks) {
7775
+ const peakLeaves = takeWhileVec(leaves, (pos) => pos <= peak);
7776
+ if (peakLeaves.length > 0) {
7777
+ for (const pos of peakLeaves) {
7778
+ const height = posHeightInTree(peak);
7779
+ let index = 0n;
7780
+ let parentPos = peak;
7781
+ for (let h = height; h >= 1; h--) {
7782
+ const leftChild = parentPos - parentOffset(h - 1);
7783
+ const rightChild = leftChild + siblingOffset(h - 1);
7784
+ index *= 2n;
7785
+ if (leftChild >= pos) {
7786
+ parentPos = leftChild;
7787
+ } else {
7788
+ parentPos = rightChild;
7789
+ index += 1n;
7790
+ }
7791
+ }
7792
+ leavesWithKIndices.push([pos, index]);
7793
+ }
7794
+ }
7795
+ }
7796
+ return leavesWithKIndices;
7797
+ }
7798
+ function calculateMMRSize(numberOfLeaves) {
7799
+ const numberOfPeaks = numberOfLeaves.toString(2).split("1").length - 1;
7800
+ return 2n * numberOfLeaves - BigInt(numberOfPeaks);
7801
+ }
7802
+ async function generateRootWithProof(postRequest, treeSize) {
7803
+ const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7804
+ const { commitment: hash, encodePacked: encodePacked4 } = postRequestCommitment(postRequest);
7805
+ const result = JSON.parse(generate_root_with_proof2(hexToBytes(encodePacked4), treeSize));
7806
+ const { root, proof, mmr_size, leaf_positions, keccak_hash_calldata } = result;
7807
+ if (keccak_hash_calldata !== hash) {
7808
+ console.log("keccak_hash", keccak_hash_calldata);
7809
+ console.log("hash", hash);
7810
+ throw new Error("Abi keccak hash mismatch");
7811
+ }
7812
+ const [[, kIndex]] = mmrPositionToKIndex(leaf_positions, BigInt(mmr_size));
7813
+ return {
7814
+ root,
7815
+ proof,
7816
+ index: treeSize - 1n,
7817
+ kIndex,
7818
+ treeSize,
7819
+ mmrSize: mmr_size
7820
+ };
7821
+ }
7822
+ async function load_ckb_mmr() {
7823
+ if (hasWindow) {
7824
+ const wasm2 = await Promise.resolve().then(() => (init_node(), node_exports));
7825
+ await wasm2.default();
7826
+ return wasm2;
7827
+ }
7828
+ if (isNode) {
7829
+ const wasm2 = await Promise.resolve().then(() => (init_node(), node_exports));
7830
+ return wasm2;
7831
+ }
7832
+ throw new Error(`SDK not setup for ${env}`);
7833
+ }
7834
+ async function __test() {
7835
+ const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7836
+ return generate_root_with_proof2(new Uint8Array(), 120n);
7837
+ }
7838
+
7583
7839
  // src/utils.ts
7584
7840
  var DEFAULT_POLL_INTERVAL = 5e3;
7585
7841
  var ADDRESS_ZERO2 = "0x0000000000000000000000000000000000000000";
@@ -15670,7 +15926,7 @@ var BidManager = class {
15670
15926
  const {
15671
15927
  order,
15672
15928
  solverAccount,
15673
- solverPrivateKey,
15929
+ solverSigner,
15674
15930
  nonce,
15675
15931
  entryPointAddress,
15676
15932
  callGasLimit,
@@ -15699,8 +15955,7 @@ var BidManager = class {
15699
15955
  const userOpHash = this.crypto.computeUserOpHash(userOp, entryPointAddress, chainId);
15700
15956
  const sessionKey = order.session;
15701
15957
  const messageHash = keccak256(concat([userOpHash, order.id, sessionKey]));
15702
- const solverAccount_ = privateKeyToAccount(solverPrivateKey);
15703
- const solverSignature = await solverAccount_.signMessage({ message: { raw: messageHash } });
15958
+ const solverSignature = await solverSigner.signMessage(messageHash, Number(chainId));
15704
15959
  const signature = concat([order.id, solverSignature]);
15705
15960
  return { ...userOp, signature };
15706
15961
  }
@@ -18662,9 +18917,9 @@ async function fetchLocalAssetId(params) {
18662
18917
  const palletPrefix = xxhashAsU8a("TokenGateway", 128);
18663
18918
  const storagePrefix = xxhashAsU8a("LocalAssets", 128);
18664
18919
  const full_key = new Uint8Array([...palletPrefix, ...storagePrefix, ...assetId]);
18665
- const hexKey = bytesToHex(full_key);
18920
+ const hexKey2 = bytesToHex(full_key);
18666
18921
  const storage_value = await api.rpc.state.getStorage(
18667
- hexKey
18922
+ hexKey2
18668
18923
  );
18669
18924
  if (storage_value.isSome) {
18670
18925
  const assetId2 = storage_value.value.toU8a();
@@ -18937,6 +19192,6 @@ async function teleportDot(param_) {
18937
19192
  return stream;
18938
19193
  }
18939
19194
 
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 };
19195
+ 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
19196
  //# sourceMappingURL=index.js.map
18942
19197
  //# sourceMappingURL=index.js.map