@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.
@@ -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,148 +7115,26 @@ 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({
7253
7135
  /**
7254
- * Proof of the contract state.
7136
+ * Proof of the contract state (EVM account trie) or, for Revive / Substrate EVM, the main state trie proof
7137
+ * (`AccountInfo` + child root) — same SCALE shape as `SubstrateEvmProof::main_proof` on the Rust side.
7255
7138
  */
7256
7139
  contractProof: Vector(Vector(u8)),
7257
7140
  /**
@@ -7630,6 +7513,379 @@ var Message = Enum({
7630
7513
  TimeoutMessage
7631
7514
  });
7632
7515
 
7516
+ // src/chains/polkadotHub.ts
7517
+ var DEFAULT_CHILD_STORAGE_PREFIX = new TextEncoder().encode(":child_storage:default:");
7518
+ var SubstrateHttpRpc = class {
7519
+ constructor(url) {
7520
+ this.url = url;
7521
+ }
7522
+ async call(method, params = []) {
7523
+ const body = JSON.stringify({
7524
+ jsonrpc: "2.0",
7525
+ id: Date.now(),
7526
+ method,
7527
+ params
7528
+ });
7529
+ const response = await fetch(this.url, {
7530
+ method: "POST",
7531
+ headers: { "Content-Type": "application/json" },
7532
+ body
7533
+ });
7534
+ if (!response.ok) {
7535
+ throw new Error(`Substrate RPC HTTP error: ${response.status}`);
7536
+ }
7537
+ const json = await response.json();
7538
+ if (json.error) {
7539
+ throw new Error(`Substrate RPC error: ${json.error.message}`);
7540
+ }
7541
+ return json.result;
7542
+ }
7543
+ };
7544
+ function contractInfoKey(address20) {
7545
+ const key = new Uint8Array(16 + 16 + 20);
7546
+ key.set(xxhashAsU8a("Revive", 128), 0);
7547
+ key.set(xxhashAsU8a("AccountInfoOf", 128), 16);
7548
+ key.set(address20, 32);
7549
+ return key;
7550
+ }
7551
+ function childPrefixedStorageKey(trieId) {
7552
+ return u8aConcat(DEFAULT_CHILD_STORAGE_PREFIX, trieId);
7553
+ }
7554
+ function storageKeyForSlot(slot32) {
7555
+ return blake2AsU8a(slot32, 256);
7556
+ }
7557
+ function hexKey(k) {
7558
+ return bytesToHex(k);
7559
+ }
7560
+ var PolkadotHubChain = class _PolkadotHubChain {
7561
+ constructor(params, evm) {
7562
+ this.params = params;
7563
+ this.evm = evm;
7564
+ this.substrateRpc = new SubstrateHttpRpc(replaceWebsocketWithHttp(params.substrateRpcUrl));
7565
+ }
7566
+ evm;
7567
+ substrateRpc;
7568
+ static fromParams(params) {
7569
+ const { substrateRpcUrl, ...evmParams } = params;
7570
+ const evm = EvmChain.fromParams(evmParams);
7571
+ return new _PolkadotHubChain(params, evm);
7572
+ }
7573
+ /**
7574
+ * Creates a `PolkadotHubChain` by auto-detecting the EVM chain ID and `IsmpHost` address via
7575
+ * {@link EvmChain.create}, plus a Substrate RPC URL for Revive child-trie proofs.
7576
+ *
7577
+ * @param evmRpcUrl - HTTP(S) JSON-RPC URL of the EVM (Revive) node
7578
+ * @param substrateRpcUrl - Substrate node RPC (HTTP or WebSocket) for proof queries
7579
+ * @param bundlerUrl - Optional ERC-4337 bundler URL (forwarded to `EvmChain.create`)
7580
+ */
7581
+ static async create(evmRpcUrl, substrateRpcUrl, bundlerUrl) {
7582
+ const evm = await EvmChain.create(evmRpcUrl, bundlerUrl);
7583
+ const chainId = Number.parseInt(evm.config.stateMachineId.replace(/^EVM-/, ""), 10);
7584
+ if (!Number.isFinite(chainId)) {
7585
+ throw new Error(`Unexpected EVM stateMachineId: ${evm.config.stateMachineId}`);
7586
+ }
7587
+ const params = {
7588
+ chainId,
7589
+ rpcUrl: evm.config.rpcUrl,
7590
+ host: evm.config.host,
7591
+ consensusStateId: evm.config.consensusStateId,
7592
+ bundlerUrl: evm.bundlerUrl,
7593
+ substrateRpcUrl
7594
+ };
7595
+ return new _PolkadotHubChain(params, evm);
7596
+ }
7597
+ get client() {
7598
+ return this.evm.client;
7599
+ }
7600
+ get host() {
7601
+ return this.evm.host;
7602
+ }
7603
+ get bundlerUrl() {
7604
+ return this.evm.bundlerUrl;
7605
+ }
7606
+ get configService() {
7607
+ return this.evm.configService;
7608
+ }
7609
+ get config() {
7610
+ return {
7611
+ ...this.evm.config,
7612
+ substrateRpcUrl: this.params.substrateRpcUrl
7613
+ };
7614
+ }
7615
+ hostAddress20() {
7616
+ return hexToBytes(getAddress(this.evm.host));
7617
+ }
7618
+ async fetchCombinedProof(at, queries) {
7619
+ const height = Number(at);
7620
+ if (!Number.isSafeInteger(height) || height < 0) {
7621
+ throw new Error("Block height must be a non-negative safe integer for Substrate RPC");
7622
+ }
7623
+ const blockHash = await this.substrateRpc.call("chain_getBlockHash", [height]);
7624
+ if (!blockHash) {
7625
+ throw new Error(`Block hash not found for height ${height}`);
7626
+ }
7627
+ const mainKeys = [];
7628
+ const childInfoByAddr = /* @__PURE__ */ new Map();
7629
+ const contractEntries = [...queries.entries()];
7630
+ for (const [addr20] of contractEntries) {
7631
+ const infoKey = contractInfoKey(addr20);
7632
+ const storageHex = await this.substrateRpc.call("state_getStorage", [hexKey(infoKey), blockHash]);
7633
+ if (!storageHex) {
7634
+ throw new Error(`Revive AccountInfo not found for contract ${hexKey(addr20)}`);
7635
+ }
7636
+ const trieId = decodeReviveContractTrieId(hexToBytes(storageHex));
7637
+ const prefixed = childPrefixedStorageKey(trieId);
7638
+ mainKeys.push(hexKey(infoKey));
7639
+ mainKeys.push(hexKey(prefixed));
7640
+ childInfoByAddr.set(hexKey(addr20), { trieId, prefixed });
7641
+ }
7642
+ const mainRead = await this.substrateRpc.call("state_getReadProof", [mainKeys, blockHash]);
7643
+ const mainProofBytes = mainRead.proof.map((p) => hexToBytes(p));
7644
+ const storageProofEncoded = /* @__PURE__ */ new Map();
7645
+ for (const [addr20, innerKeys] of contractEntries) {
7646
+ const addrHex = hexKey(addr20);
7647
+ const info = childInfoByAddr.get(addrHex);
7648
+ if (!info) {
7649
+ throw new Error("Internal error: missing child info for contract");
7650
+ }
7651
+ const childKeysHex = innerKeys.map((k) => hexKey(k));
7652
+ const childRead = await this.substrateRpc.call("state_getChildReadProof", [
7653
+ hexKey(info.prefixed),
7654
+ childKeysHex,
7655
+ blockHash
7656
+ ]);
7657
+ storageProofEncoded.set(
7658
+ addr20,
7659
+ childRead.proof.map((p) => hexToBytes(p))
7660
+ );
7661
+ }
7662
+ const encoded = EvmStateProof.enc({
7663
+ contractProof: mainProofBytes,
7664
+ storageProof: Array.from(storageProofEncoded.entries())
7665
+ });
7666
+ return bytesToHex(encoded);
7667
+ }
7668
+ timestamp() {
7669
+ return this.evm.timestamp();
7670
+ }
7671
+ requestReceiptKey(commitment) {
7672
+ return this.evm.requestReceiptKey(commitment);
7673
+ }
7674
+ queryRequestReceipt(commitment) {
7675
+ return this.evm.queryRequestReceipt(commitment);
7676
+ }
7677
+ async queryProof(message, _counterparty, at) {
7678
+ if (at === void 0) {
7679
+ throw new Error("PolkadotHubChain.queryProof requires an explicit block height `at`");
7680
+ }
7681
+ const host = this.hostAddress20();
7682
+ const storageKeys = "Requests" in message ? message.Requests.map((c) => storageKeyForSlot(hexToBytes(requestCommitmentKey(c).slot1))) : message.Responses.map((c) => storageKeyForSlot(hexToBytes(responseCommitmentKey(c))));
7683
+ const q = /* @__PURE__ */ new Map();
7684
+ q.set(host, storageKeys);
7685
+ return this.fetchCombinedProof(at, q);
7686
+ }
7687
+ async queryStateProof(at, keys, _address) {
7688
+ const keyBytes = keys.map((k) => hexToBytes(k));
7689
+ const host = this.hostAddress20();
7690
+ if (keyBytes.every((k) => k.length === 32)) {
7691
+ const storageKeys = keyBytes.map((slot) => storageKeyForSlot(slot));
7692
+ const q = /* @__PURE__ */ new Map();
7693
+ q.set(host, storageKeys);
7694
+ return this.fetchCombinedProof(at, q);
7695
+ }
7696
+ if (keyBytes.every((k) => k.length === 52)) {
7697
+ const groups = /* @__PURE__ */ new Map();
7698
+ for (const full of keyBytes) {
7699
+ const addr = full.subarray(0, 20);
7700
+ const slot = full.subarray(20, 52);
7701
+ const h = hexKey(addr);
7702
+ const arr = groups.get(h) ?? [];
7703
+ arr.push(storageKeyForSlot(slot));
7704
+ groups.set(h, arr);
7705
+ }
7706
+ const q = /* @__PURE__ */ new Map();
7707
+ for (const [addrHex, sks] of groups) {
7708
+ q.set(hexToBytes(addrHex), sks);
7709
+ }
7710
+ return this.fetchCombinedProof(at, q);
7711
+ }
7712
+ throw new Error(
7713
+ "PolkadotHubChain.queryStateProof: keys must be either all 32-byte ISMP slots or all 52-byte (20-byte address + 32-byte slot) entries"
7714
+ );
7715
+ }
7716
+ encode(message) {
7717
+ return this.evm.encode(message);
7718
+ }
7719
+ latestStateMachineHeight(stateMachineId) {
7720
+ return this.evm.latestStateMachineHeight(stateMachineId);
7721
+ }
7722
+ challengePeriod(stateMachineId) {
7723
+ return this.evm.challengePeriod(stateMachineId);
7724
+ }
7725
+ stateMachineUpdateTime(stateMachineHeight) {
7726
+ return this.evm.stateMachineUpdateTime(stateMachineHeight);
7727
+ }
7728
+ getHostNonce() {
7729
+ return this.evm.getHostNonce();
7730
+ }
7731
+ quoteNative(request, fee) {
7732
+ return this.evm.quoteNative(request, fee);
7733
+ }
7734
+ getFeeTokenWithDecimals() {
7735
+ return this.evm.getFeeTokenWithDecimals();
7736
+ }
7737
+ getPlaceOrderCalldata(txHash, intentGatewayAddress) {
7738
+ return this.evm.getPlaceOrderCalldata(txHash, intentGatewayAddress);
7739
+ }
7740
+ estimateGas(request) {
7741
+ return this.evm.estimateGas(request);
7742
+ }
7743
+ broadcastTransaction(signedTransaction) {
7744
+ return this.evm.broadcastTransaction(signedTransaction);
7745
+ }
7746
+ getTransactionReceipt(hash) {
7747
+ return this.evm.getTransactionReceipt(hash);
7748
+ }
7749
+ };
7750
+ function getPeakPosByHeight(height) {
7751
+ return (1n << BigInt(height + 1)) - 2n;
7752
+ }
7753
+ function leftPeakHeightPos(mmrSize) {
7754
+ let height = 1;
7755
+ let prevPos = 0n;
7756
+ let pos = getPeakPosByHeight(height);
7757
+ while (pos < mmrSize) {
7758
+ height += 1;
7759
+ prevPos = pos;
7760
+ pos = getPeakPosByHeight(height);
7761
+ }
7762
+ return [height - 1, prevPos];
7763
+ }
7764
+ function getRightPeak(initialHeight, initialPos, mmrSize) {
7765
+ let height = initialHeight;
7766
+ let pos = initialPos;
7767
+ pos += siblingOffset(height);
7768
+ while (pos > mmrSize - 1n) {
7769
+ if (height === 0) {
7770
+ return null;
7771
+ }
7772
+ pos -= parentOffset(height - 1);
7773
+ height -= 1;
7774
+ }
7775
+ return [height, pos];
7776
+ }
7777
+ function getPeaks(mmrSize) {
7778
+ const positions = [];
7779
+ let [height, pos] = leftPeakHeightPos(mmrSize);
7780
+ positions.push(pos);
7781
+ while (height > 0) {
7782
+ const peak = getRightPeak(height, pos, mmrSize);
7783
+ if (!peak) break;
7784
+ [height, pos] = peak;
7785
+ positions.push(pos);
7786
+ }
7787
+ return positions;
7788
+ }
7789
+ function allOnes(num) {
7790
+ if (num === 0n) return false;
7791
+ return num.toString(2).split("").every((bit) => bit === "1");
7792
+ }
7793
+ function jumpLeft(pos) {
7794
+ const bitLength = pos.toString(2).length;
7795
+ const mostSignificantBits = 1n << BigInt(bitLength - 1);
7796
+ return pos - (mostSignificantBits - 1n);
7797
+ }
7798
+ function posHeightInTree(initialPos) {
7799
+ let pos = initialPos + 1n;
7800
+ while (!allOnes(pos)) {
7801
+ pos = jumpLeft(pos);
7802
+ }
7803
+ return pos.toString(2).length - 1;
7804
+ }
7805
+ function parentOffset(height) {
7806
+ return 2n << BigInt(height);
7807
+ }
7808
+ function siblingOffset(height) {
7809
+ return (2n << BigInt(height)) - 1n;
7810
+ }
7811
+ function takeWhileVec(v, p) {
7812
+ const index = v.findIndex((item) => !p(item));
7813
+ if (index === -1) {
7814
+ const result = [...v];
7815
+ v.length = 0;
7816
+ return result;
7817
+ }
7818
+ return v.splice(0, index);
7819
+ }
7820
+ function mmrPositionToKIndex(initialLeaves, mmrSize) {
7821
+ const leaves = [...initialLeaves];
7822
+ const peaks = getPeaks(mmrSize);
7823
+ const leavesWithKIndices = [];
7824
+ for (const peak of peaks) {
7825
+ const peakLeaves = takeWhileVec(leaves, (pos) => pos <= peak);
7826
+ if (peakLeaves.length > 0) {
7827
+ for (const pos of peakLeaves) {
7828
+ const height = posHeightInTree(peak);
7829
+ let index = 0n;
7830
+ let parentPos = peak;
7831
+ for (let h = height; h >= 1; h--) {
7832
+ const leftChild = parentPos - parentOffset(h - 1);
7833
+ const rightChild = leftChild + siblingOffset(h - 1);
7834
+ index *= 2n;
7835
+ if (leftChild >= pos) {
7836
+ parentPos = leftChild;
7837
+ } else {
7838
+ parentPos = rightChild;
7839
+ index += 1n;
7840
+ }
7841
+ }
7842
+ leavesWithKIndices.push([pos, index]);
7843
+ }
7844
+ }
7845
+ }
7846
+ return leavesWithKIndices;
7847
+ }
7848
+ function calculateMMRSize(numberOfLeaves) {
7849
+ const numberOfPeaks = numberOfLeaves.toString(2).split("1").length - 1;
7850
+ return 2n * numberOfLeaves - BigInt(numberOfPeaks);
7851
+ }
7852
+ async function generateRootWithProof(postRequest, treeSize) {
7853
+ const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7854
+ const { commitment: hash, encodePacked: encodePacked4 } = postRequestCommitment(postRequest);
7855
+ const result = JSON.parse(generate_root_with_proof2(hexToBytes(encodePacked4), treeSize));
7856
+ const { root, proof, mmr_size, leaf_positions, keccak_hash_calldata } = result;
7857
+ if (keccak_hash_calldata !== hash) {
7858
+ console.log("keccak_hash", keccak_hash_calldata);
7859
+ console.log("hash", hash);
7860
+ throw new Error("Abi keccak hash mismatch");
7861
+ }
7862
+ const [[, kIndex]] = mmrPositionToKIndex(leaf_positions, BigInt(mmr_size));
7863
+ return {
7864
+ root,
7865
+ proof,
7866
+ index: treeSize - 1n,
7867
+ kIndex,
7868
+ treeSize,
7869
+ mmrSize: mmr_size
7870
+ };
7871
+ }
7872
+ async function load_ckb_mmr() {
7873
+ if (hasWindow) {
7874
+ const wasm2 = await Promise.resolve().then(() => (init_web(), web_exports));
7875
+ await wasm2.default();
7876
+ return wasm2;
7877
+ }
7878
+ if (isNode) {
7879
+ const wasm2 = await Promise.resolve().then(() => (init_web(), web_exports));
7880
+ return wasm2;
7881
+ }
7882
+ throw new Error(`SDK not setup for ${env}`);
7883
+ }
7884
+ async function __test() {
7885
+ const { generate_root_with_proof: generate_root_with_proof2 } = await load_ckb_mmr();
7886
+ return generate_root_with_proof2(new Uint8Array(), 120n);
7887
+ }
7888
+
7633
7889
  // src/utils.ts
7634
7890
  var DEFAULT_POLL_INTERVAL = 5e3;
7635
7891
  var ADDRESS_ZERO2 = "0x0000000000000000000000000000000000000000";
@@ -15730,7 +15986,7 @@ var BidManager = class {
15730
15986
  const {
15731
15987
  order,
15732
15988
  solverAccount,
15733
- solverPrivateKey,
15989
+ solverSigner,
15734
15990
  nonce,
15735
15991
  entryPointAddress,
15736
15992
  callGasLimit,
@@ -15759,8 +16015,7 @@ var BidManager = class {
15759
16015
  const userOpHash = this.crypto.computeUserOpHash(userOp, entryPointAddress, chainId);
15760
16016
  const sessionKey = order.session;
15761
16017
  const messageHash = keccak256(concat([userOpHash, order.id, sessionKey]));
15762
- const solverAccount_ = privateKeyToAccount(solverPrivateKey);
15763
- const solverSignature = await solverAccount_.signMessage({ message: { raw: messageHash } });
16018
+ const solverSignature = await solverSigner.signMessage(messageHash, Number(chainId));
15764
16019
  const signature = concat([order.id, solverSignature]);
15765
16020
  return { ...userOp, signature };
15766
16021
  }
@@ -18722,9 +18977,9 @@ async function fetchLocalAssetId(params) {
18722
18977
  const palletPrefix = xxhashAsU8a("TokenGateway", 128);
18723
18978
  const storagePrefix = xxhashAsU8a("LocalAssets", 128);
18724
18979
  const full_key = new Uint8Array([...palletPrefix, ...storagePrefix, ...assetId]);
18725
- const hexKey = bytesToHex(full_key);
18980
+ const hexKey2 = bytesToHex(full_key);
18726
18981
  const storage_value = await api.rpc.state.getStorage(
18727
- hexKey
18982
+ hexKey2
18728
18983
  );
18729
18984
  if (storage_value.isSome) {
18730
18985
  const assetId2 = storage_value.value.toU8a();
@@ -18997,6 +19252,6 @@ async function teleportDot(param_) {
18997
19252
  return stream;
18998
19253
  }
18999
19254
 
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 };
19255
+ 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
19256
  //# sourceMappingURL=index.js.map
19002
19257
  //# sourceMappingURL=index.js.map