@hyperbridge/sdk 1.3.11 → 1.3.12

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,34 +2757,39 @@ declare class IntentGateway {
2747
2757
  } | {
2748
2758
  status: string;
2749
2759
  data: {
2750
- currentHeight: bigint;
2751
- deadline: bigint;
2752
- height?: undefined;
2753
- proof?: undefined;
2760
+ proof: `0x${string}`;
2761
+ height: bigint;
2762
+ failedHeight?: undefined;
2763
+ error?: undefined;
2764
+ deadline?: undefined;
2754
2765
  };
2755
2766
  } | {
2756
2767
  status: string;
2757
2768
  data: {
2758
- height: bigint;
2759
- currentHeight?: undefined;
2760
- deadline?: undefined;
2769
+ lastFailedHeight?: bigint | undefined;
2770
+ currentHeight: bigint;
2771
+ deadline: bigint;
2761
2772
  proof?: undefined;
2773
+ height?: undefined;
2774
+ failedHeight?: undefined;
2775
+ error?: undefined;
2762
2776
  };
2763
2777
  } | {
2764
2778
  status: string;
2765
2779
  data: {
2766
- proof: `0x${string}`;
2767
- height: bigint;
2768
- currentHeight?: undefined;
2769
- deadline?: undefined;
2780
+ failedHeight: bigint;
2781
+ error: string;
2782
+ deadline: bigint;
2783
+ proof?: undefined;
2784
+ height?: undefined;
2770
2785
  };
2771
2786
  } | {
2772
2787
  status: string;
2773
2788
  data?: undefined;
2774
2789
  } | {
2775
2790
  status: string;
2776
- data: `0x${string}`;
2777
- }, void, IGetRequest | undefined>;
2791
+ data: IProof;
2792
+ }, void, IGetRequest>;
2778
2793
  /**
2779
2794
  * Returns the tick spacing for a given fee tier in Uniswap V4
2780
2795
  * @param fee - The fee tier in basis points
@@ -2790,6 +2805,11 @@ declare class IntentGateway {
2790
2805
  */
2791
2806
  private isWithinThreshold;
2792
2807
  }
2808
+ interface StoredCancellationData {
2809
+ destIProof?: IProof;
2810
+ getRequest?: IGetRequest;
2811
+ sourceIProof?: IProof;
2812
+ }
2793
2813
 
2794
2814
  type HyperbridgeTxEvents = {
2795
2815
  kind: "Ready";
@@ -3073,4 +3093,4 @@ declare const coingeckoIds: {
3073
3093
  "EVM-130": string;
3074
3094
  };
3075
3095
 
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 };
3096
+ 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 };
@@ -7,7 +7,6 @@ import { hasWindow, isNode, env } from 'std-env';
7
7
  import { Vector, u8, Struct, Tuple, Enum, _void, u64, u32, Option, bool, u128, Bytes } from 'scale-ts';
8
8
  import { match } from 'ts-pattern';
9
9
  import { WsProvider, ApiPromise } from '@polkadot/api';
10
- import { RpcWebSocketClient } from 'rpc-websocket-client';
11
10
  import { keccakAsU8a, decodeAddress, keccakAsHex, xxhashAsU8a } from '@polkadot/util-crypto';
12
11
  import { GraphQLClient } from 'graphql-request';
13
12
  import { Decimal } from 'decimal.js';
@@ -4602,6 +4601,14 @@ function adjustFeeDecimals(feeInFeeToken, fromDecimals, toDecimals) {
4602
4601
  return (feeInFeeToken + scaleFactor - 1n) / scaleFactor;
4603
4602
  }
4604
4603
  }
4604
+ function replaceWebsocketWithHttp(url) {
4605
+ if (url.startsWith("ws://")) {
4606
+ return url.replace("ws://", "http://");
4607
+ } else if (url.startsWith("wss://")) {
4608
+ return url.replace("wss://", "https://");
4609
+ }
4610
+ return url;
4611
+ }
4605
4612
 
4606
4613
  // src/utils/exceptions.ts
4607
4614
  var AbortSignalInternal = class _AbortSignalInternal extends Error {
@@ -5111,14 +5118,52 @@ function deriveSecondLevelSlot(key, firstLevelSlot) {
5111
5118
  const combined = new Uint8Array([...keyBytes, ...slotBytes]);
5112
5119
  return keccak256(combined);
5113
5120
  }
5121
+ var HttpRpcClient = class {
5122
+ constructor(url) {
5123
+ this.url = url;
5124
+ }
5125
+ /**
5126
+ * Make an RPC call over HTTP
5127
+ * @param method - The RPC method name
5128
+ * @param params - The parameters for the RPC call
5129
+ * @returns Promise resolving to the RPC response
5130
+ */
5131
+ async call(method, params = []) {
5132
+ const body = JSON.stringify({
5133
+ jsonrpc: "2.0",
5134
+ id: Date.now(),
5135
+ method,
5136
+ params
5137
+ });
5138
+ const response = await fetch(this.url, {
5139
+ method: "POST",
5140
+ headers: {
5141
+ "Content-Type": "application/json"
5142
+ },
5143
+ body
5144
+ });
5145
+ if (!response.ok) {
5146
+ throw new Error(`HTTP error! status: ${response.status}`);
5147
+ }
5148
+ const result = await response.json();
5149
+ if (result.error) {
5150
+ throw new Error(`RPC error: ${result.error.message}`);
5151
+ }
5152
+ return result.result;
5153
+ }
5154
+ };
5114
5155
  var SubstrateChain = class {
5115
5156
  constructor(params) {
5116
5157
  this.params = params;
5158
+ const url = this.params.ws;
5159
+ const httpUrl = replaceWebsocketWithHttp(url);
5160
+ this.rpcClient = new HttpRpcClient(httpUrl);
5117
5161
  }
5118
5162
  /*
5119
5163
  * api: The Polkadot API instance for the Substrate chain.
5120
5164
  */
5121
5165
  api;
5166
+ rpcClient;
5122
5167
  /*
5123
5168
  * connect: Connects to the Substrate chain using the provided WebSocket URL.
5124
5169
  */
@@ -5178,9 +5223,7 @@ var SubstrateChain = class {
5178
5223
  async queryRequestCommitment(commitment) {
5179
5224
  const prefix = toHex(":child_storage:default:ISMP");
5180
5225
  const key = this.requestCommitmentKey(commitment);
5181
- const rpc = new RpcWebSocketClient();
5182
- await rpc.connect(this.params.ws);
5183
- const item = await rpc.call("childstate_getStorage", [prefix, key]);
5226
+ const item = await this.rpcClient.call("childstate_getStorage", [prefix, key]);
5184
5227
  return item;
5185
5228
  }
5186
5229
  /**
@@ -5191,9 +5234,7 @@ var SubstrateChain = class {
5191
5234
  async queryRequestReceipt(commitment) {
5192
5235
  const prefix = toHex(":child_storage:default:ISMP");
5193
5236
  const key = this.requestReceiptKey(commitment);
5194
- const rpc = new RpcWebSocketClient();
5195
- await rpc.connect(this.params.ws);
5196
- const item = await rpc.call("childstate_getStorage", [prefix, key]);
5237
+ const item = await this.rpcClient.call("childstate_getStorage", [prefix, key]);
5197
5238
  return item;
5198
5239
  }
5199
5240
  /**
@@ -5213,15 +5254,13 @@ var SubstrateChain = class {
5213
5254
  * @returns {Promise<HexString>} The proof.
5214
5255
  */
5215
5256
  async queryProof(message, counterparty, at) {
5216
- const rpc = new RpcWebSocketClient();
5217
- await rpc.connect(this.params.ws);
5218
5257
  if (isEvmChain(counterparty)) {
5219
- const proof = await rpc.call("mmr_queryProof", [Number(at), message]);
5258
+ const proof = await this.rpcClient.call("mmr_queryProof", [Number(at), message]);
5220
5259
  return toHex(proof.proof);
5221
5260
  }
5222
5261
  if (isSubstrateChain(counterparty)) {
5223
5262
  const childTrieKeys = "Requests" in message ? message.Requests.map(requestCommitmentStorageKey) : message.Responses.map(responseCommitmentStorageKey);
5224
- const proof = await rpc.call("ismp_queryChildTrieProof", [Number(at), childTrieKeys]);
5263
+ const proof = await this.rpcClient.call("ismp_queryChildTrieProof", [Number(at), childTrieKeys]);
5225
5264
  const basicProof = BasicProof.dec(toHex(proof.proof));
5226
5265
  const encoded = SubstrateStateProof.enc({
5227
5266
  tag: "OverlayProof",
@@ -5285,10 +5324,8 @@ var SubstrateChain = class {
5285
5324
  * @returns The state proof as a hexadecimal string.
5286
5325
  */
5287
5326
  async queryStateProof(at, keys) {
5288
- const rpc = new RpcWebSocketClient();
5289
- await rpc.connect(this.params.ws);
5290
5327
  const encodedKeys = keys.map((key) => Array.from(hexToBytes(key)));
5291
- const proof = await rpc.call("ismp_queryChildTrieProof", [Number(at), encodedKeys]);
5328
+ const proof = await this.rpcClient.call("ismp_queryChildTrieProof", [Number(at), encodedKeys]);
5292
5329
  const basicProof = BasicProof.dec(toHex(proof.proof));
5293
5330
  const encoded = SubstrateStateProof.enc({
5294
5331
  tag: "OverlayProof",
@@ -5308,9 +5345,16 @@ var SubstrateChain = class {
5308
5345
  * @returns {Promise<bigint>} The latest state machine height.
5309
5346
  */
5310
5347
  async latestStateMachineHeight(stateMachineId) {
5311
- if (!this.api) throw new Error("API not initialized");
5312
- const latestHeight = await this.api.query.ismp.latestStateMachineHeight(stateMachineId);
5313
- return BigInt(latestHeight.toString());
5348
+ const state_id = convertStateIdToStateMachineId(stateMachineId.stateId);
5349
+ const consensusStateIdToBytes = hexToBytes(stateMachineId.consensusStateId);
5350
+ const decoder = new TextDecoder("utf-8");
5351
+ const decodedConsensusStateId = decoder.decode(consensusStateIdToBytes);
5352
+ const payload = {
5353
+ state_id,
5354
+ consensus_state_id: decodedConsensusStateId
5355
+ };
5356
+ const latestHeight = await this.rpcClient.call("ismp_queryStateMachineLatestHeight", [payload]);
5357
+ return BigInt(latestHeight);
5314
5358
  }
5315
5359
  /**
5316
5360
  * Get the state machine update time for a given state machine height.
@@ -5318,9 +5362,20 @@ var SubstrateChain = class {
5318
5362
  * @returns {Promise<bigint>} The statemachine update time in seconds.
5319
5363
  */
5320
5364
  async stateMachineUpdateTime(stateMachineHeight) {
5321
- if (!this.api) throw new Error("API not initialized");
5322
- const updateTime = await this.api.query.ismp.stateMachineUpdateTime(stateMachineHeight);
5323
- return BigInt(updateTime.toString());
5365
+ const state_id = convertStateIdToStateMachineId(stateMachineHeight.id.stateId);
5366
+ const consensusStateIdToBytes = hexToBytes(stateMachineHeight.id.consensusStateId);
5367
+ const decoder = new TextDecoder("utf-8");
5368
+ const decodedConsensusStateId = decoder.decode(consensusStateIdToBytes);
5369
+ const stateMachineId = {
5370
+ state_id,
5371
+ consensus_state_id: decodedConsensusStateId
5372
+ };
5373
+ const payload = {
5374
+ id: stateMachineId,
5375
+ height: Number(stateMachineHeight.height)
5376
+ };
5377
+ const updateTime = await this.rpcClient.call("ismp_queryStateMachineUpdateTime", [payload]);
5378
+ return BigInt(updateTime);
5324
5379
  }
5325
5380
  /**
5326
5381
  * Get the challenge period for a given state machine id.
@@ -5328,9 +5383,16 @@ var SubstrateChain = class {
5328
5383
  * @returns {Promise<bigint>} The challenge period in seconds.
5329
5384
  */
5330
5385
  async challengePeriod(stateMachineId) {
5331
- if (!this.api) throw new Error("API not initialized");
5332
- const challengePeriod = await this.api.query.ismp.challengePeriod(stateMachineId);
5333
- return BigInt(challengePeriod.toString());
5386
+ const state_id = convertStateIdToStateMachineId(stateMachineId.stateId);
5387
+ const consensusStateIdToBytes = hexToBytes(stateMachineId.consensusStateId);
5388
+ const decoder = new TextDecoder("utf-8");
5389
+ const decodedConsensusStateId = decoder.decode(consensusStateIdToBytes);
5390
+ const payload = {
5391
+ state_id,
5392
+ consensus_state_id: decodedConsensusStateId
5393
+ };
5394
+ const challengePeriod = await this.rpcClient.call("ismp_queryChallengePeriod", [payload]);
5395
+ return BigInt(challengePeriod);
5334
5396
  }
5335
5397
  /**
5336
5398
  * Encode an ISMP calldata for a substrate chain.
@@ -5380,6 +5442,24 @@ function convertStateMachineIdToEnum(id) {
5380
5442
  }
5381
5443
  return { tag, value };
5382
5444
  }
5445
+ function convertStateIdToStateMachineId(stateId) {
5446
+ switch (true) {
5447
+ case stateId.Evm !== void 0:
5448
+ return `EVM-${stateId.Evm}`;
5449
+ case stateId.Polkadot !== void 0:
5450
+ return `POLKADOT-${stateId.Polkadot}`;
5451
+ case stateId.Kusama !== void 0:
5452
+ return `KUSAMA-${stateId.Kusama}`;
5453
+ case stateId.Substrate !== void 0: {
5454
+ const bytes = hexToBytes(stateId.Substrate);
5455
+ const decoder = new TextDecoder("utf-8");
5456
+ const decoded = decoder.decode(bytes);
5457
+ return `SUBSTRATE-${decoded}`;
5458
+ }
5459
+ default:
5460
+ throw new Error("Unsupported stateId variant");
5461
+ }
5462
+ }
5383
5463
  function convertIPostRequestToCodec(request) {
5384
5464
  return {
5385
5465
  tag: "Post",
@@ -11649,13 +11729,6 @@ var IntentGateway = class {
11649
11729
  this.source = source;
11650
11730
  this.dest = dest;
11651
11731
  }
11652
- destStateproofCache = /* @__PURE__ */ new Map();
11653
- getCachedProof(id) {
11654
- return this.destStateproofCache.get(id);
11655
- }
11656
- clearCachedProof(id) {
11657
- this.destStateproofCache.delete(id);
11658
- }
11659
11732
  /**
11660
11733
  * Estimates the total cost required to fill an order, including gas fees, relayer fees,
11661
11734
  * protocol fees, and swap operations.
@@ -12264,118 +12337,128 @@ var IntentGateway = class {
12264
12337
  });
12265
12338
  return filledStatus !== "0x0000000000000000000000000000000000000000000000000000000000000000";
12266
12339
  }
12267
- async *cancelOrder(order, hyperbridgeConfig, indexerClient) {
12268
- const hyperbridge = await getChain({
12269
- ...hyperbridgeConfig,
12270
- hasher: "Keccak"
12271
- });
12340
+ async submitAndConfirmReceipt(hyperbridge, commitment, message) {
12341
+ let storageValue = await hyperbridge.queryRequestReceipt(commitment);
12342
+ if (!storageValue) {
12343
+ console.log("No receipt found. Attempting to submit...");
12344
+ try {
12345
+ await hyperbridge.submitUnsigned(message);
12346
+ } catch {
12347
+ console.warn("Submission failed. Awaiting network confirmation...");
12348
+ }
12349
+ console.log("Waiting for network state update...");
12350
+ await sleep(3e4);
12351
+ storageValue = await retryPromise(
12352
+ async () => {
12353
+ const value = await hyperbridge.queryRequestReceipt(commitment);
12354
+ if (!value) throw new Error("Receipt not found");
12355
+ return value;
12356
+ },
12357
+ { maxRetries: 5, backoffMs: 5e3, logMessage: "Checking for receipt" }
12358
+ );
12359
+ }
12360
+ console.log("Hyperbridge Receipt confirmed.");
12361
+ }
12362
+ async *cancelOrder(order, hyperbridgeConfig, indexerClient, storedData) {
12363
+ const hyperbridge = await getChain({ ...hyperbridgeConfig, hasher: "Keccak" });
12272
12364
  const sourceStateMachine = hexToString$1(order.sourceChain);
12273
12365
  const destStateMachine = hexToString$1(order.destChain);
12274
12366
  const sourceConsensusStateId = this.source.config.getConsensusStateId(sourceStateMachine);
12275
12367
  const destConsensusStateId = this.dest.config.getConsensusStateId(destStateMachine);
12276
- let latestHeight = 0n;
12277
- while (latestHeight <= order.deadline) {
12278
- const { stateId } = parseStateMachineId(destStateMachine);
12279
- latestHeight = await hyperbridge.latestStateMachineHeight({
12280
- stateId,
12281
- consensusStateId: destConsensusStateId
12282
- });
12283
- yield {
12284
- status: "AWAITING_DESTINATION_FINALIZED",
12285
- data: { currentHeight: latestHeight, deadline: order.deadline }
12286
- };
12287
- if (latestHeight <= order.deadline) {
12288
- await sleep(1e4);
12368
+ let destIProof;
12369
+ if (storedData?.destIProof) {
12370
+ destIProof = storedData.destIProof;
12371
+ yield { status: "DESTINATION_FINALIZED", data: { proof: destIProof.proof, height: destIProof.height } };
12372
+ } else {
12373
+ let latestHeight = 0n;
12374
+ let lastFailedHeight = null;
12375
+ let proofHex = null;
12376
+ while (!proofHex) {
12377
+ latestHeight = await retryPromise(
12378
+ () => hyperbridge.latestStateMachineHeight({
12379
+ stateId: parseStateMachineId(destStateMachine).stateId,
12380
+ consensusStateId: destConsensusStateId
12381
+ }),
12382
+ { maxRetries: 5, backoffMs: 500, logMessage: "Failed to fetch latest state machine height" }
12383
+ );
12384
+ const shouldFetchProof = lastFailedHeight === null ? latestHeight > order.deadline : latestHeight > lastFailedHeight;
12385
+ if (!shouldFetchProof) {
12386
+ yield {
12387
+ status: "AWAITING_DESTINATION_FINALIZED",
12388
+ data: {
12389
+ currentHeight: latestHeight,
12390
+ deadline: order.deadline,
12391
+ ...lastFailedHeight && { lastFailedHeight }
12392
+ }
12393
+ };
12394
+ await sleep(1e4);
12395
+ continue;
12396
+ }
12397
+ try {
12398
+ const intentGatewayAddress = this.dest.config.getIntentGatewayAddress(destStateMachine);
12399
+ const orderId = orderCommitment(order);
12400
+ const slotHash = await this.dest.client.readContract({
12401
+ abi: IntentGateway_default.ABI,
12402
+ address: intentGatewayAddress,
12403
+ functionName: "calculateCommitmentSlotHash",
12404
+ args: [orderId]
12405
+ });
12406
+ proofHex = await this.dest.queryStateProof(latestHeight, [slotHash], intentGatewayAddress);
12407
+ } catch (error) {
12408
+ lastFailedHeight = latestHeight;
12409
+ yield {
12410
+ status: "PROOF_FETCH_FAILED",
12411
+ data: {
12412
+ failedHeight: latestHeight,
12413
+ error: error instanceof Error ? error.message : String(error),
12414
+ deadline: order.deadline
12415
+ }
12416
+ };
12417
+ await sleep(1e4);
12418
+ }
12289
12419
  }
12420
+ destIProof = {
12421
+ consensusStateId: destConsensusStateId,
12422
+ height: latestHeight,
12423
+ proof: proofHex,
12424
+ stateMachine: destStateMachine
12425
+ };
12426
+ yield { status: "DESTINATION_FINALIZED", data: { proof: destIProof.proof, height: destIProof.height } };
12290
12427
  }
12291
- yield { status: "DESTINATION_FINALIZED", data: { height: latestHeight } };
12292
- const intentGatewayAddress = this.dest.config.getIntentGatewayAddress(destStateMachine);
12293
- const orderId = orderCommitment(order);
12294
- const slotHash = await this.dest.client.readContract({
12295
- abi: IntentGateway_default.ABI,
12296
- address: intentGatewayAddress,
12297
- functionName: "calculateCommitmentSlotHash",
12298
- args: [orderId]
12299
- });
12300
- const proof = await this.dest.queryStateProof(latestHeight, [slotHash], intentGatewayAddress);
12301
- const destIProof = {
12302
- consensusStateId: destConsensusStateId,
12303
- height: latestHeight,
12304
- proof,
12305
- stateMachine: destStateMachine
12306
- };
12307
- this.destStateproofCache.set(order.id, destIProof);
12308
- yield { status: "STATE_PROOF_RECEIVED", data: { proof, height: latestHeight } };
12309
- const getRequest = yield { status: "AWAITING_GET_REQUEST" };
12310
- if (!getRequest) {
12311
- throw new Error("[Cancel Order]: Get Request not provided");
12312
- }
12313
- const commitment = getRequestCommitment({
12314
- ...getRequest,
12315
- keys: [...getRequest.keys]
12316
- });
12317
- const statusStream = indexerClient.getRequestStatusStream(commitment);
12318
- for await (const statusUpdate of statusStream) {
12428
+ const getRequest = storedData?.getRequest ?? (yield { status: "AWAITING_GET_REQUEST" });
12429
+ if (!getRequest) throw new Error("[Cancel Order]: Get Request not provided");
12430
+ const commitment = getRequestCommitment({ ...getRequest, keys: [...getRequest.keys] });
12431
+ const sourceStatusStream = indexerClient.getRequestStatusStream(commitment);
12432
+ for await (const statusUpdate of sourceStatusStream) {
12319
12433
  if (statusUpdate.status === RequestStatus.SOURCE_FINALIZED) {
12320
- const sourceHeight = statusUpdate.metadata.blockNumber;
12321
- const proof2 = await this.source.queryProof(
12434
+ const sourceHeight = BigInt(statusUpdate.metadata.blockNumber);
12435
+ const proof = await this.source.queryProof(
12322
12436
  { Requests: [commitment] },
12323
12437
  hyperbridgeConfig.stateMachineId,
12324
- BigInt(sourceHeight)
12438
+ sourceHeight
12325
12439
  );
12326
- yield { status: "SOURCE_PROOF_RECIEVED", data: proof2 };
12327
- const { stateId } = parseStateMachineId(sourceStateMachine);
12328
12440
  const sourceIProof = {
12329
- height: BigInt(sourceHeight),
12441
+ height: sourceHeight,
12330
12442
  stateMachine: sourceStateMachine,
12331
12443
  consensusStateId: sourceConsensusStateId,
12332
- proof: proof2
12444
+ proof
12333
12445
  };
12446
+ yield { status: "SOURCE_PROOF_RECEIVED", data: sourceIProof };
12334
12447
  const getRequestMessage = {
12335
12448
  kind: "GetRequest",
12336
12449
  requests: [getRequest],
12337
12450
  source: sourceIProof,
12338
- response: this.getCachedProof(order.id),
12451
+ response: destIProof,
12339
12452
  signer: pad("0x")
12340
12453
  };
12341
12454
  await waitForChallengePeriod(hyperbridge, {
12342
- height: BigInt(sourceHeight),
12455
+ height: sourceHeight,
12343
12456
  id: {
12344
- stateId,
12457
+ stateId: parseStateMachineId(sourceStateMachine).stateId,
12345
12458
  consensusStateId: sourceConsensusStateId
12346
12459
  }
12347
12460
  });
12348
- const receiptKey = hyperbridge.requestReceiptKey(commitment);
12349
- const { api } = hyperbridge;
12350
- if (!api) {
12351
- throw new Error("Hyperbridge API is not available");
12352
- }
12353
- let storageValue = await api.rpc.childstate.getStorage(":child_storage:default:ISMP", receiptKey);
12354
- if (storageValue.isNone) {
12355
- console.log("No receipt found. Attempting to submit...");
12356
- try {
12357
- await hyperbridge.submitUnsigned(getRequestMessage);
12358
- } catch {
12359
- console.warn("Submission failed. Awaiting network confirmation...");
12360
- }
12361
- console.log("Waiting for network state update...");
12362
- await sleep(3e4);
12363
- storageValue = await retryPromise(
12364
- async () => {
12365
- const value = await api.rpc.childstate.getStorage(":child_storage:default:ISMP", receiptKey);
12366
- if (value.isNone) {
12367
- throw new Error("Receipt not found");
12368
- }
12369
- return value;
12370
- },
12371
- {
12372
- maxRetries: 10,
12373
- backoffMs: 5e3,
12374
- logMessage: "Checking for receipt"
12375
- }
12376
- );
12377
- }
12378
- console.log("Receipt confirmed on Hyperbridge. Proceeding.");
12461
+ await this.submitAndConfirmReceipt(hyperbridge, commitment, getRequestMessage);
12379
12462
  }
12380
12463
  yield statusUpdate;
12381
12464
  }
@@ -12751,6 +12834,6 @@ async function teleportDot(param_) {
12751
12834
  return stream;
12752
12835
  }
12753
12836
 
12754
- 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 };
12837
+ 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 };
12755
12838
  //# sourceMappingURL=index.js.map
12756
12839
  //# sourceMappingURL=index.js.map