@hyperbridge/sdk 1.3.11 → 1.3.13

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.
@@ -1919,6 +1919,7 @@ interface SubstrateChainParams {
1919
1919
  declare class SubstrateChain implements IChain {
1920
1920
  private readonly params;
1921
1921
  api?: ApiPromise;
1922
+ private rpcClient;
1922
1923
  constructor(params: SubstrateChainParams);
1923
1924
  connect(): Promise<void>;
1924
1925
  /**
@@ -2019,6 +2020,17 @@ declare class SubstrateChain implements IChain {
2019
2020
  * @returns {IStateMachine} The corresponding enum value.
2020
2021
  */
2021
2022
  declare function convertStateMachineIdToEnum(id: string): IStateMachine;
2023
+ /**
2024
+ * Converts a stateId object back to the state_id format used by the RPC.
2025
+ * @param stateId - The stateId object from StateMachineIdParams
2026
+ * @returns The string representation like "EVM-11155111" or "SUBSTRATE-cere"
2027
+ */
2028
+ declare function convertStateIdToStateMachineId(stateId: {
2029
+ Evm?: number;
2030
+ Substrate?: HexString;
2031
+ Polkadot?: number;
2032
+ Kusama?: number;
2033
+ }): string;
2022
2034
  declare function encodeISMPMessage(message: IIsmpMessage): Uint8Array;
2023
2035
 
2024
2036
  /**
@@ -2575,9 +2587,6 @@ declare function queryGetRequest(params: {
2575
2587
  declare class IntentGateway {
2576
2588
  readonly source: EvmChain;
2577
2589
  readonly dest: EvmChain;
2578
- private destStateproofCache;
2579
- getCachedProof(id: HexString): IProof | undefined;
2580
- clearCachedProof(id: HexString): void;
2581
2590
  /**
2582
2591
  * Creates a new IntentGateway instance for cross-chain operations.
2583
2592
  * @param source - The source EVM chain
@@ -2663,7 +2672,8 @@ declare class IntentGateway {
2663
2672
  * @returns True if the order has been filled, false otherwise
2664
2673
  */
2665
2674
  isOrderFilled(order: Order): Promise<boolean>;
2666
- cancelOrder(order: Order, hyperbridgeConfig: IHyperbridgeConfig, indexerClient: IndexerClient): AsyncGenerator<{
2675
+ submitAndConfirmReceipt(hyperbridge: SubstrateChain, commitment: HexString, message: IGetRequestMessage): Promise<void>;
2676
+ cancelOrder(order: Order, hyperbridgeConfig: IHyperbridgeConfig, indexerClient: IndexerClient, storedData?: StoredCancellationData): AsyncGenerator<{
2667
2677
  status: RequestStatus["SOURCE"];
2668
2678
  metadata: {
2669
2679
  blockHash: string;
@@ -2747,25 +2757,39 @@ declare class IntentGateway {
2747
2757
  } | {
2748
2758
  status: string;
2749
2759
  data: {
2760
+ proof: IProof;
2761
+ failedHeight?: undefined;
2762
+ error?: undefined;
2763
+ deadline?: undefined;
2764
+ height?: undefined;
2765
+ };
2766
+ } | {
2767
+ status: string;
2768
+ data: {
2769
+ lastFailedHeight?: bigint | undefined;
2750
2770
  currentHeight: bigint;
2751
2771
  deadline: bigint;
2752
- height?: undefined;
2753
2772
  proof?: undefined;
2773
+ failedHeight?: undefined;
2774
+ error?: undefined;
2775
+ height?: undefined;
2754
2776
  };
2755
2777
  } | {
2756
2778
  status: string;
2757
2779
  data: {
2758
- height: bigint;
2759
- currentHeight?: undefined;
2760
- deadline?: undefined;
2780
+ failedHeight: bigint;
2781
+ error: string;
2782
+ deadline: bigint;
2761
2783
  proof?: undefined;
2784
+ height?: undefined;
2762
2785
  };
2763
2786
  } | {
2764
2787
  status: string;
2765
2788
  data: {
2766
2789
  proof: `0x${string}`;
2767
2790
  height: bigint;
2768
- currentHeight?: undefined;
2791
+ failedHeight?: undefined;
2792
+ error?: undefined;
2769
2793
  deadline?: undefined;
2770
2794
  };
2771
2795
  } | {
@@ -2773,8 +2797,8 @@ declare class IntentGateway {
2773
2797
  data?: undefined;
2774
2798
  } | {
2775
2799
  status: string;
2776
- data: `0x${string}`;
2777
- }, void, IGetRequest | undefined>;
2800
+ data: IProof;
2801
+ }, void, IGetRequest>;
2778
2802
  /**
2779
2803
  * Returns the tick spacing for a given fee tier in Uniswap V4
2780
2804
  * @param fee - The fee tier in basis points
@@ -2790,6 +2814,11 @@ declare class IntentGateway {
2790
2814
  */
2791
2815
  private isWithinThreshold;
2792
2816
  }
2817
+ interface StoredCancellationData {
2818
+ destIProof?: IProof;
2819
+ getRequest?: IGetRequest;
2820
+ sourceIProof?: IProof;
2821
+ }
2793
2822
 
2794
2823
  type HyperbridgeTxEvents = {
2795
2824
  kind: "Ready";
@@ -3073,4 +3102,4 @@ declare const coingeckoIds: {
3073
3102
  "EVM-130": string;
3074
3103
  };
3075
3104
 
3076
- export { ADDRESS_ZERO, type AllStatusKey, type AssetTeleported, type AssetTeleportedResponse, type BlockMetadata, type CancelOptions, type ChainConfig, ChainConfigService, type ChainId, Chains, type ClientConfig, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DUMMY_PRIVATE_KEY, type DecodedOrderPlacedLog, type DispatchGet, type DispatchPost, ERC20Method, type EstimateGasCallData, EvmChain, type EvmChainParams, type ExecutionResult, type FillOptions, type FillerConfig, type GetRequestResponse, type GetRequestWithStatus, type GetResponseByRequestIdResponse, type GetResponseStorageValues, type HexString, type HostParams, HyperClientStatus, type HyperbridgeTxEvents, type IChain, type IConfig, type IEvmConfig, type IGetRequest, type IGetRequestMessage, type IGetResponse, type IGetResponseMessage, type IHyperbridgeConfig, type IIsmpMessage, type IMessage, type IPostRequest, type IPostResponse, type IProof, type IRequestMessage, type ISubstrateConfig, type ITimeoutPostRequestMessage, IndexerClient, type IndexerQueryClient, IntentGateway, type IntentGatewayParams, type IsmpRequest, type NewDeployment, type Order, type OrderResponse, OrderStatus, type OrderStatusMetadata, type OrderWithStatus, type Params, type PaymentInfo, type PostRequestStatus, type PostRequestTimeoutStatus, type PostRequestWithStatus, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, type RequestBody, type RequestCommitment, RequestKind, type RequestResponse, RequestStatus, type RequestStatusKey, type RequestStatusWithMetadata, type ResponseCommitmentWithValues, type RetryConfig, STATE_COMMITMENTS_SLOT, type StateMachineHeight, type StateMachineIdParams, type StateMachineResponse, type StateMachineUpdate, SubstrateChain, type SubstrateChainParams, TeleportStatus, TimeoutStatus, type TimeoutStatusKey, type TokenGatewayAssetTeleportedResponse, type TokenGatewayAssetTeleportedWithStatus, type TokenInfo, type TokenPrice, type TokenPricesResponse, type TokenRegistry, type TokenRegistryResponse, WrappedNativeDecimals, type XcmGatewayParams, __test, addresses, adjustFeeDecimals, assets, bytes20ToBytes32, bytes32ToBytes20, chainIds, coingeckoIds, consensusStateIds, constructRedeemEscrowRequestBody, convertStateMachineIdToEnum, createQueryClient, createRpcUrls, encodeISMPMessage, estimateGasForPost, fetchPrice, generateRootWithProof, getChain, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, hexToString, orderCommitment, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, teleport, teleportDot, viemChains };
3105
+ export { ADDRESS_ZERO, type AllStatusKey, type AssetTeleported, type AssetTeleportedResponse, type BlockMetadata, type CancelOptions, type ChainConfig, ChainConfigService, type ChainId, Chains, type ClientConfig, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DUMMY_PRIVATE_KEY, type DecodedOrderPlacedLog, type DispatchGet, type DispatchPost, ERC20Method, type EstimateGasCallData, EvmChain, type EvmChainParams, type ExecutionResult, type FillOptions, type FillerConfig, type GetRequestResponse, type GetRequestWithStatus, type GetResponseByRequestIdResponse, type GetResponseStorageValues, type HexString, type HostParams, HyperClientStatus, type HyperbridgeTxEvents, type IChain, type IConfig, type IEvmConfig, type IGetRequest, type IGetRequestMessage, type IGetResponse, type IGetResponseMessage, type IHyperbridgeConfig, type IIsmpMessage, type IMessage, type IPostRequest, type IPostResponse, type IProof, type IRequestMessage, type ISubstrateConfig, type ITimeoutPostRequestMessage, IndexerClient, type IndexerQueryClient, IntentGateway, type IntentGatewayParams, type IsmpRequest, type NewDeployment, type Order, type OrderResponse, OrderStatus, type OrderStatusMetadata, type OrderWithStatus, type Params, type PaymentInfo, type PostRequestStatus, type PostRequestTimeoutStatus, type PostRequestWithStatus, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, type RequestBody, type RequestCommitment, RequestKind, type RequestResponse, RequestStatus, type RequestStatusKey, type RequestStatusWithMetadata, type ResponseCommitmentWithValues, type RetryConfig, STATE_COMMITMENTS_SLOT, type StateMachineHeight, type StateMachineIdParams, type StateMachineResponse, type StateMachineUpdate, SubstrateChain, type SubstrateChainParams, TeleportStatus, TimeoutStatus, type TimeoutStatusKey, type TokenGatewayAssetTeleportedResponse, type TokenGatewayAssetTeleportedWithStatus, type TokenInfo, type TokenPrice, type TokenPricesResponse, type TokenRegistry, type TokenRegistryResponse, WrappedNativeDecimals, type XcmGatewayParams, __test, addresses, adjustFeeDecimals, assets, bytes20ToBytes32, bytes32ToBytes20, chainIds, coingeckoIds, consensusStateIds, constructRedeemEscrowRequestBody, convertStateIdToStateMachineId, convertStateMachineIdToEnum, createQueryClient, createRpcUrls, encodeISMPMessage, estimateGasForPost, fetchPrice, generateRootWithProof, getChain, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, hexToString, orderCommitment, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, teleport, teleportDot, viemChains };
@@ -10,7 +10,6 @@ import { hasWindow, isNode, env } from 'std-env';
10
10
  import { Vector, u8, Struct, Tuple, Enum, _void, u64, u32, Option, bool, u128, Bytes } from 'scale-ts';
11
11
  import { match } from 'ts-pattern';
12
12
  import { WsProvider, ApiPromise } from '@polkadot/api';
13
- import { RpcWebSocketClient } from 'rpc-websocket-client';
14
13
  import { keccakAsU8a, decodeAddress, keccakAsHex, xxhashAsU8a } from '@polkadot/util-crypto';
15
14
  import { GraphQLClient } from 'graphql-request';
16
15
  import { Decimal } from 'decimal.js';
@@ -4553,6 +4552,14 @@ function adjustFeeDecimals(feeInFeeToken, fromDecimals, toDecimals) {
4553
4552
  return (feeInFeeToken + scaleFactor - 1n) / scaleFactor;
4554
4553
  }
4555
4554
  }
4555
+ function replaceWebsocketWithHttp(url) {
4556
+ if (url.startsWith("ws://")) {
4557
+ return url.replace("ws://", "http://");
4558
+ } else if (url.startsWith("wss://")) {
4559
+ return url.replace("wss://", "https://");
4560
+ }
4561
+ return url;
4562
+ }
4556
4563
 
4557
4564
  // src/utils/exceptions.ts
4558
4565
  var AbortSignalInternal = class _AbortSignalInternal extends Error {
@@ -5062,14 +5069,52 @@ function deriveSecondLevelSlot(key, firstLevelSlot) {
5062
5069
  const combined = new Uint8Array([...keyBytes, ...slotBytes]);
5063
5070
  return keccak256(combined);
5064
5071
  }
5072
+ var HttpRpcClient = class {
5073
+ constructor(url) {
5074
+ this.url = url;
5075
+ }
5076
+ /**
5077
+ * Make an RPC call over HTTP
5078
+ * @param method - The RPC method name
5079
+ * @param params - The parameters for the RPC call
5080
+ * @returns Promise resolving to the RPC response
5081
+ */
5082
+ async call(method, params = []) {
5083
+ const body = JSON.stringify({
5084
+ jsonrpc: "2.0",
5085
+ id: Date.now(),
5086
+ method,
5087
+ params
5088
+ });
5089
+ const response = await fetch(this.url, {
5090
+ method: "POST",
5091
+ headers: {
5092
+ "Content-Type": "application/json"
5093
+ },
5094
+ body
5095
+ });
5096
+ if (!response.ok) {
5097
+ throw new Error(`HTTP error! status: ${response.status}`);
5098
+ }
5099
+ const result = await response.json();
5100
+ if (result.error) {
5101
+ throw new Error(`RPC error: ${result.error.message}`);
5102
+ }
5103
+ return result.result;
5104
+ }
5105
+ };
5065
5106
  var SubstrateChain = class {
5066
5107
  constructor(params) {
5067
5108
  this.params = params;
5109
+ const url = this.params.ws;
5110
+ const httpUrl = replaceWebsocketWithHttp(url);
5111
+ this.rpcClient = new HttpRpcClient(httpUrl);
5068
5112
  }
5069
5113
  /*
5070
5114
  * api: The Polkadot API instance for the Substrate chain.
5071
5115
  */
5072
5116
  api;
5117
+ rpcClient;
5073
5118
  /*
5074
5119
  * connect: Connects to the Substrate chain using the provided WebSocket URL.
5075
5120
  */
@@ -5129,9 +5174,7 @@ var SubstrateChain = class {
5129
5174
  async queryRequestCommitment(commitment) {
5130
5175
  const prefix = toHex(":child_storage:default:ISMP");
5131
5176
  const key = this.requestCommitmentKey(commitment);
5132
- const rpc = new RpcWebSocketClient();
5133
- await rpc.connect(this.params.ws);
5134
- const item = await rpc.call("childstate_getStorage", [prefix, key]);
5177
+ const item = await this.rpcClient.call("childstate_getStorage", [prefix, key]);
5135
5178
  return item;
5136
5179
  }
5137
5180
  /**
@@ -5142,9 +5185,7 @@ var SubstrateChain = class {
5142
5185
  async queryRequestReceipt(commitment) {
5143
5186
  const prefix = toHex(":child_storage:default:ISMP");
5144
5187
  const key = this.requestReceiptKey(commitment);
5145
- const rpc = new RpcWebSocketClient();
5146
- await rpc.connect(this.params.ws);
5147
- const item = await rpc.call("childstate_getStorage", [prefix, key]);
5188
+ const item = await this.rpcClient.call("childstate_getStorage", [prefix, key]);
5148
5189
  return item;
5149
5190
  }
5150
5191
  /**
@@ -5164,15 +5205,13 @@ var SubstrateChain = class {
5164
5205
  * @returns {Promise<HexString>} The proof.
5165
5206
  */
5166
5207
  async queryProof(message, counterparty, at) {
5167
- const rpc = new RpcWebSocketClient();
5168
- await rpc.connect(this.params.ws);
5169
5208
  if (isEvmChain(counterparty)) {
5170
- const proof = await rpc.call("mmr_queryProof", [Number(at), message]);
5209
+ const proof = await this.rpcClient.call("mmr_queryProof", [Number(at), message]);
5171
5210
  return toHex(proof.proof);
5172
5211
  }
5173
5212
  if (isSubstrateChain(counterparty)) {
5174
5213
  const childTrieKeys = "Requests" in message ? message.Requests.map(requestCommitmentStorageKey) : message.Responses.map(responseCommitmentStorageKey);
5175
- const proof = await rpc.call("ismp_queryChildTrieProof", [Number(at), childTrieKeys]);
5214
+ const proof = await this.rpcClient.call("ismp_queryChildTrieProof", [Number(at), childTrieKeys]);
5176
5215
  const basicProof = BasicProof.dec(toHex(proof.proof));
5177
5216
  const encoded = SubstrateStateProof.enc({
5178
5217
  tag: "OverlayProof",
@@ -5236,10 +5275,8 @@ var SubstrateChain = class {
5236
5275
  * @returns The state proof as a hexadecimal string.
5237
5276
  */
5238
5277
  async queryStateProof(at, keys) {
5239
- const rpc = new RpcWebSocketClient();
5240
- await rpc.connect(this.params.ws);
5241
5278
  const encodedKeys = keys.map((key) => Array.from(hexToBytes(key)));
5242
- const proof = await rpc.call("ismp_queryChildTrieProof", [Number(at), encodedKeys]);
5279
+ const proof = await this.rpcClient.call("ismp_queryChildTrieProof", [Number(at), encodedKeys]);
5243
5280
  const basicProof = BasicProof.dec(toHex(proof.proof));
5244
5281
  const encoded = SubstrateStateProof.enc({
5245
5282
  tag: "OverlayProof",
@@ -5259,9 +5296,16 @@ var SubstrateChain = class {
5259
5296
  * @returns {Promise<bigint>} The latest state machine height.
5260
5297
  */
5261
5298
  async latestStateMachineHeight(stateMachineId) {
5262
- if (!this.api) throw new Error("API not initialized");
5263
- const latestHeight = await this.api.query.ismp.latestStateMachineHeight(stateMachineId);
5264
- return BigInt(latestHeight.toString());
5299
+ const state_id = convertStateIdToStateMachineId(stateMachineId.stateId);
5300
+ const consensusStateIdToBytes = hexToBytes(stateMachineId.consensusStateId);
5301
+ const decoder = new TextDecoder("utf-8");
5302
+ const decodedConsensusStateId = decoder.decode(consensusStateIdToBytes);
5303
+ const payload = {
5304
+ state_id,
5305
+ consensus_state_id: decodedConsensusStateId
5306
+ };
5307
+ const latestHeight = await this.rpcClient.call("ismp_queryStateMachineLatestHeight", [payload]);
5308
+ return BigInt(latestHeight);
5265
5309
  }
5266
5310
  /**
5267
5311
  * Get the state machine update time for a given state machine height.
@@ -5269,9 +5313,20 @@ var SubstrateChain = class {
5269
5313
  * @returns {Promise<bigint>} The statemachine update time in seconds.
5270
5314
  */
5271
5315
  async stateMachineUpdateTime(stateMachineHeight) {
5272
- if (!this.api) throw new Error("API not initialized");
5273
- const updateTime = await this.api.query.ismp.stateMachineUpdateTime(stateMachineHeight);
5274
- return BigInt(updateTime.toString());
5316
+ const state_id = convertStateIdToStateMachineId(stateMachineHeight.id.stateId);
5317
+ const consensusStateIdToBytes = hexToBytes(stateMachineHeight.id.consensusStateId);
5318
+ const decoder = new TextDecoder("utf-8");
5319
+ const decodedConsensusStateId = decoder.decode(consensusStateIdToBytes);
5320
+ const stateMachineId = {
5321
+ state_id,
5322
+ consensus_state_id: decodedConsensusStateId
5323
+ };
5324
+ const payload = {
5325
+ id: stateMachineId,
5326
+ height: Number(stateMachineHeight.height)
5327
+ };
5328
+ const updateTime = await this.rpcClient.call("ismp_queryStateMachineUpdateTime", [payload]);
5329
+ return BigInt(updateTime);
5275
5330
  }
5276
5331
  /**
5277
5332
  * Get the challenge period for a given state machine id.
@@ -5279,9 +5334,16 @@ var SubstrateChain = class {
5279
5334
  * @returns {Promise<bigint>} The challenge period in seconds.
5280
5335
  */
5281
5336
  async challengePeriod(stateMachineId) {
5282
- if (!this.api) throw new Error("API not initialized");
5283
- const challengePeriod = await this.api.query.ismp.challengePeriod(stateMachineId);
5284
- return BigInt(challengePeriod.toString());
5337
+ const state_id = convertStateIdToStateMachineId(stateMachineId.stateId);
5338
+ const consensusStateIdToBytes = hexToBytes(stateMachineId.consensusStateId);
5339
+ const decoder = new TextDecoder("utf-8");
5340
+ const decodedConsensusStateId = decoder.decode(consensusStateIdToBytes);
5341
+ const payload = {
5342
+ state_id,
5343
+ consensus_state_id: decodedConsensusStateId
5344
+ };
5345
+ const challengePeriod = await this.rpcClient.call("ismp_queryChallengePeriod", [payload]);
5346
+ return BigInt(challengePeriod);
5285
5347
  }
5286
5348
  /**
5287
5349
  * Encode an ISMP calldata for a substrate chain.
@@ -5331,6 +5393,24 @@ function convertStateMachineIdToEnum(id) {
5331
5393
  }
5332
5394
  return { tag, value };
5333
5395
  }
5396
+ function convertStateIdToStateMachineId(stateId) {
5397
+ switch (true) {
5398
+ case stateId.Evm !== void 0:
5399
+ return `EVM-${stateId.Evm}`;
5400
+ case stateId.Polkadot !== void 0:
5401
+ return `POLKADOT-${stateId.Polkadot}`;
5402
+ case stateId.Kusama !== void 0:
5403
+ return `KUSAMA-${stateId.Kusama}`;
5404
+ case stateId.Substrate !== void 0: {
5405
+ const bytes = hexToBytes(stateId.Substrate);
5406
+ const decoder = new TextDecoder("utf-8");
5407
+ const decoded = decoder.decode(bytes);
5408
+ return `SUBSTRATE-${decoded}`;
5409
+ }
5410
+ default:
5411
+ throw new Error("Unsupported stateId variant");
5412
+ }
5413
+ }
5334
5414
  function convertIPostRequestToCodec(request) {
5335
5415
  return {
5336
5416
  tag: "Post",
@@ -11600,13 +11680,6 @@ var IntentGateway = class {
11600
11680
  this.source = source;
11601
11681
  this.dest = dest;
11602
11682
  }
11603
- destStateproofCache = /* @__PURE__ */ new Map();
11604
- getCachedProof(id) {
11605
- return this.destStateproofCache.get(id);
11606
- }
11607
- clearCachedProof(id) {
11608
- this.destStateproofCache.delete(id);
11609
- }
11610
11683
  /**
11611
11684
  * Estimates the total cost required to fill an order, including gas fees, relayer fees,
11612
11685
  * protocol fees, and swap operations.
@@ -12215,118 +12288,128 @@ var IntentGateway = class {
12215
12288
  });
12216
12289
  return filledStatus !== "0x0000000000000000000000000000000000000000000000000000000000000000";
12217
12290
  }
12218
- async *cancelOrder(order, hyperbridgeConfig, indexerClient) {
12219
- const hyperbridge = await getChain({
12220
- ...hyperbridgeConfig,
12221
- hasher: "Keccak"
12222
- });
12291
+ async submitAndConfirmReceipt(hyperbridge, commitment, message) {
12292
+ let storageValue = await hyperbridge.queryRequestReceipt(commitment);
12293
+ if (!storageValue) {
12294
+ console.log("No receipt found. Attempting to submit...");
12295
+ try {
12296
+ await hyperbridge.submitUnsigned(message);
12297
+ } catch {
12298
+ console.warn("Submission failed. Awaiting network confirmation...");
12299
+ }
12300
+ console.log("Waiting for network state update...");
12301
+ await sleep(3e4);
12302
+ storageValue = await retryPromise(
12303
+ async () => {
12304
+ const value = await hyperbridge.queryRequestReceipt(commitment);
12305
+ if (!value) throw new Error("Receipt not found");
12306
+ return value;
12307
+ },
12308
+ { maxRetries: 5, backoffMs: 5e3, logMessage: "Checking for receipt" }
12309
+ );
12310
+ }
12311
+ console.log("Hyperbridge Receipt confirmed.");
12312
+ }
12313
+ async *cancelOrder(order, hyperbridgeConfig, indexerClient, storedData) {
12314
+ const hyperbridge = await getChain({ ...hyperbridgeConfig, hasher: "Keccak" });
12223
12315
  const sourceStateMachine = hexToString$1(order.sourceChain);
12224
12316
  const destStateMachine = hexToString$1(order.destChain);
12225
12317
  const sourceConsensusStateId = this.source.config.getConsensusStateId(sourceStateMachine);
12226
12318
  const destConsensusStateId = this.dest.config.getConsensusStateId(destStateMachine);
12227
- let latestHeight = 0n;
12228
- while (latestHeight <= order.deadline) {
12229
- const { stateId } = parseStateMachineId(destStateMachine);
12230
- latestHeight = await hyperbridge.latestStateMachineHeight({
12231
- stateId,
12232
- consensusStateId: destConsensusStateId
12233
- });
12234
- yield {
12235
- status: "AWAITING_DESTINATION_FINALIZED",
12236
- data: { currentHeight: latestHeight, deadline: order.deadline }
12237
- };
12238
- if (latestHeight <= order.deadline) {
12239
- await sleep(1e4);
12319
+ let destIProof;
12320
+ if (storedData?.destIProof) {
12321
+ destIProof = storedData.destIProof;
12322
+ yield { status: "DESTINATION_FINALIZED", data: { proof: destIProof } };
12323
+ } else {
12324
+ let latestHeight = 0n;
12325
+ let lastFailedHeight = null;
12326
+ let proofHex = null;
12327
+ while (!proofHex) {
12328
+ latestHeight = await retryPromise(
12329
+ () => hyperbridge.latestStateMachineHeight({
12330
+ stateId: parseStateMachineId(destStateMachine).stateId,
12331
+ consensusStateId: destConsensusStateId
12332
+ }),
12333
+ { maxRetries: 5, backoffMs: 500, logMessage: "Failed to fetch latest state machine height" }
12334
+ );
12335
+ const shouldFetchProof = lastFailedHeight === null ? latestHeight > order.deadline : latestHeight > lastFailedHeight;
12336
+ if (!shouldFetchProof) {
12337
+ yield {
12338
+ status: "AWAITING_DESTINATION_FINALIZED",
12339
+ data: {
12340
+ currentHeight: latestHeight,
12341
+ deadline: order.deadline,
12342
+ ...lastFailedHeight && { lastFailedHeight }
12343
+ }
12344
+ };
12345
+ await sleep(1e4);
12346
+ continue;
12347
+ }
12348
+ try {
12349
+ const intentGatewayAddress = this.dest.config.getIntentGatewayAddress(destStateMachine);
12350
+ const orderId = orderCommitment(order);
12351
+ const slotHash = await this.dest.client.readContract({
12352
+ abi: IntentGateway_default.ABI,
12353
+ address: intentGatewayAddress,
12354
+ functionName: "calculateCommitmentSlotHash",
12355
+ args: [orderId]
12356
+ });
12357
+ proofHex = await this.dest.queryStateProof(latestHeight, [slotHash], intentGatewayAddress);
12358
+ } catch (error) {
12359
+ lastFailedHeight = latestHeight;
12360
+ yield {
12361
+ status: "PROOF_FETCH_FAILED",
12362
+ data: {
12363
+ failedHeight: latestHeight,
12364
+ error: error instanceof Error ? error.message : String(error),
12365
+ deadline: order.deadline
12366
+ }
12367
+ };
12368
+ await sleep(1e4);
12369
+ }
12240
12370
  }
12371
+ destIProof = {
12372
+ consensusStateId: destConsensusStateId,
12373
+ height: latestHeight,
12374
+ proof: proofHex,
12375
+ stateMachine: destStateMachine
12376
+ };
12377
+ yield { status: "DESTINATION_FINALIZED", data: { proof: destIProof.proof, height: destIProof.height } };
12241
12378
  }
12242
- yield { status: "DESTINATION_FINALIZED", data: { height: latestHeight } };
12243
- const intentGatewayAddress = this.dest.config.getIntentGatewayAddress(destStateMachine);
12244
- const orderId = orderCommitment(order);
12245
- const slotHash = await this.dest.client.readContract({
12246
- abi: IntentGateway_default.ABI,
12247
- address: intentGatewayAddress,
12248
- functionName: "calculateCommitmentSlotHash",
12249
- args: [orderId]
12250
- });
12251
- const proof = await this.dest.queryStateProof(latestHeight, [slotHash], intentGatewayAddress);
12252
- const destIProof = {
12253
- consensusStateId: destConsensusStateId,
12254
- height: latestHeight,
12255
- proof,
12256
- stateMachine: destStateMachine
12257
- };
12258
- this.destStateproofCache.set(order.id, destIProof);
12259
- yield { status: "STATE_PROOF_RECEIVED", data: { proof, height: latestHeight } };
12260
- const getRequest = yield { status: "AWAITING_GET_REQUEST" };
12261
- if (!getRequest) {
12262
- throw new Error("[Cancel Order]: Get Request not provided");
12263
- }
12264
- const commitment = getRequestCommitment({
12265
- ...getRequest,
12266
- keys: [...getRequest.keys]
12267
- });
12268
- const statusStream = indexerClient.getRequestStatusStream(commitment);
12269
- for await (const statusUpdate of statusStream) {
12379
+ const getRequest = storedData?.getRequest ?? (yield { status: "AWAITING_GET_REQUEST" });
12380
+ if (!getRequest) throw new Error("[Cancel Order]: Get Request not provided");
12381
+ const commitment = getRequestCommitment({ ...getRequest, keys: [...getRequest.keys] });
12382
+ const sourceStatusStream = indexerClient.getRequestStatusStream(commitment);
12383
+ for await (const statusUpdate of sourceStatusStream) {
12270
12384
  if (statusUpdate.status === RequestStatus.SOURCE_FINALIZED) {
12271
- const sourceHeight = statusUpdate.metadata.blockNumber;
12272
- const proof2 = await this.source.queryProof(
12385
+ const sourceHeight = BigInt(statusUpdate.metadata.blockNumber);
12386
+ const proof = await this.source.queryProof(
12273
12387
  { Requests: [commitment] },
12274
12388
  hyperbridgeConfig.stateMachineId,
12275
- BigInt(sourceHeight)
12389
+ sourceHeight
12276
12390
  );
12277
- yield { status: "SOURCE_PROOF_RECIEVED", data: proof2 };
12278
- const { stateId } = parseStateMachineId(sourceStateMachine);
12279
12391
  const sourceIProof = {
12280
- height: BigInt(sourceHeight),
12392
+ height: sourceHeight,
12281
12393
  stateMachine: sourceStateMachine,
12282
12394
  consensusStateId: sourceConsensusStateId,
12283
- proof: proof2
12395
+ proof
12284
12396
  };
12397
+ yield { status: "SOURCE_PROOF_RECEIVED", data: sourceIProof };
12285
12398
  const getRequestMessage = {
12286
12399
  kind: "GetRequest",
12287
12400
  requests: [getRequest],
12288
12401
  source: sourceIProof,
12289
- response: this.getCachedProof(order.id),
12402
+ response: destIProof,
12290
12403
  signer: pad("0x")
12291
12404
  };
12292
12405
  await waitForChallengePeriod(hyperbridge, {
12293
- height: BigInt(sourceHeight),
12406
+ height: sourceHeight,
12294
12407
  id: {
12295
- stateId,
12408
+ stateId: parseStateMachineId(sourceStateMachine).stateId,
12296
12409
  consensusStateId: sourceConsensusStateId
12297
12410
  }
12298
12411
  });
12299
- const receiptKey = hyperbridge.requestReceiptKey(commitment);
12300
- const { api } = hyperbridge;
12301
- if (!api) {
12302
- throw new Error("Hyperbridge API is not available");
12303
- }
12304
- let storageValue = await api.rpc.childstate.getStorage(":child_storage:default:ISMP", receiptKey);
12305
- if (storageValue.isNone) {
12306
- console.log("No receipt found. Attempting to submit...");
12307
- try {
12308
- await hyperbridge.submitUnsigned(getRequestMessage);
12309
- } catch {
12310
- console.warn("Submission failed. Awaiting network confirmation...");
12311
- }
12312
- console.log("Waiting for network state update...");
12313
- await sleep(3e4);
12314
- storageValue = await retryPromise(
12315
- async () => {
12316
- const value = await api.rpc.childstate.getStorage(":child_storage:default:ISMP", receiptKey);
12317
- if (value.isNone) {
12318
- throw new Error("Receipt not found");
12319
- }
12320
- return value;
12321
- },
12322
- {
12323
- maxRetries: 10,
12324
- backoffMs: 5e3,
12325
- logMessage: "Checking for receipt"
12326
- }
12327
- );
12328
- }
12329
- console.log("Receipt confirmed on Hyperbridge. Proceeding.");
12412
+ await this.submitAndConfirmReceipt(hyperbridge, commitment, getRequestMessage);
12330
12413
  }
12331
12414
  yield statusUpdate;
12332
12415
  }
@@ -12702,6 +12785,6 @@ async function teleportDot(param_) {
12702
12785
  return stream;
12703
12786
  }
12704
12787
 
12705
- export { ADDRESS_ZERO, ChainConfigService, Chains, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DUMMY_PRIVATE_KEY, ERC20Method, EvmChain, HyperClientStatus, IndexerClient, IntentGateway, OrderStatus, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, RequestKind, RequestStatus, STATE_COMMITMENTS_SLOT, SubstrateChain, TeleportStatus, TimeoutStatus, WrappedNativeDecimals, __test, addresses, adjustFeeDecimals, assets, bytes20ToBytes32, bytes32ToBytes20, chainIds, coingeckoIds, consensusStateIds, constructRedeemEscrowRequestBody, convertStateMachineIdToEnum, createQueryClient, createRpcUrls, encodeISMPMessage, estimateGasForPost, fetchPrice, generateRootWithProof, getChain, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, hexToString, orderCommitment, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, teleport, teleportDot, viemChains };
12788
+ export { ADDRESS_ZERO, ChainConfigService, Chains, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DUMMY_PRIVATE_KEY, ERC20Method, EvmChain, HyperClientStatus, IndexerClient, IntentGateway, OrderStatus, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, RequestKind, RequestStatus, STATE_COMMITMENTS_SLOT, SubstrateChain, TeleportStatus, TimeoutStatus, WrappedNativeDecimals, __test, addresses, adjustFeeDecimals, assets, bytes20ToBytes32, bytes32ToBytes20, chainIds, coingeckoIds, consensusStateIds, constructRedeemEscrowRequestBody, convertStateIdToStateMachineId, convertStateMachineIdToEnum, createQueryClient, createRpcUrls, encodeISMPMessage, estimateGasForPost, fetchPrice, generateRootWithProof, getChain, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, hexToString, orderCommitment, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, teleport, teleportDot, viemChains };
12706
12789
  //# sourceMappingURL=index.js.map
12707
12790
  //# sourceMappingURL=index.js.map