@hyperbridge/sdk 1.3.22 → 1.3.26

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.
@@ -1606,6 +1606,8 @@ declare class ChainConfigService {
1606
1606
  getUniswapV4QuoterAddress(chain: string): HexString;
1607
1607
  getPermit2Address(chain: string): HexString;
1608
1608
  getCoingeckoId(chain: string): string | undefined;
1609
+ getEtherscanApiKey(): string | undefined;
1610
+ getCalldispatcherAddress(chain: string): HexString;
1609
1611
  }
1610
1612
 
1611
1613
  /**
@@ -1854,6 +1856,16 @@ declare function orderCommitment(order: Order): HexString;
1854
1856
  declare function bytes32ToBytes20(bytes32Address: string): HexString;
1855
1857
  declare function bytes20ToBytes32(bytes20Address: string): HexString;
1856
1858
  declare function hexToString(hex: string): string;
1859
+ /**
1860
+ * Retries a promise-returning operation with exponential backoff.
1861
+ * This function will attempt to execute the operation up to maxRetries times,
1862
+ * with an exponential backoff delay between attempts.
1863
+ *
1864
+ * @param operation The async operation to retry
1865
+ * @param retryConfig Configuration object containing retry parameters
1866
+ * @returns Promise that resolves with the operation result or rejects with the last error
1867
+ */
1868
+ declare function retryPromise<T>(operation: () => Promise<T>, retryConfig: RetryConfig): Promise<T>;
1857
1869
  /**
1858
1870
  * Calculates the commitment hash for a get request.
1859
1871
  * @param get The get request to calculate the commitment hash for.
@@ -1881,6 +1893,11 @@ declare function estimateGasForPost(params: {
1881
1893
  */
1882
1894
  declare function constructRedeemEscrowRequestBody(order: Order, beneficiary: HexString): HexString;
1883
1895
  declare function fetchPrice(identifier: string, chainId?: number, apiKey?: string): Promise<number>;
1896
+ /**
1897
+ * Fetches the current network gas price from an Etherscan-family explorer API.
1898
+ * Returns the ProposeGasPrice (in gwei) converted to wei as bigint.
1899
+ */
1900
+ declare function getGasPriceFromEtherscan(chainId: string, apiKey?: string): Promise<bigint>;
1884
1901
  /**
1885
1902
  * ERC20 method signatures used for storage slot detection
1886
1903
  */
@@ -1938,6 +1955,14 @@ declare function getStorageSlot(client: PublicClient, contractAddress: HexString
1938
1955
  * @returns The adjusted fee amount with the target decimal precision
1939
1956
  */
1940
1957
  declare function adjustFeeDecimals(feeInFeeToken: bigint, fromDecimals: number, toDecimals: number): bigint;
1958
+ /**
1959
+ * Chains that should prefer the Etherscan API for gas price lookup
1960
+ */
1961
+ declare const USE_ETHERSCAN_CHAINS: Set<string>;
1962
+ /**
1963
+ * Testnet chains
1964
+ */
1965
+ declare const TESTNET_CHAINS: Set<string>;
1941
1966
 
1942
1967
  interface SubstrateChainParams {
1943
1968
  ws: string;
@@ -2300,6 +2325,16 @@ declare class IndexerClient {
2300
2325
  commitmentTimestamp: bigint;
2301
2326
  chain: string;
2302
2327
  }): Promise<StateMachineUpdate | undefined>;
2328
+ /**
2329
+ * Query for the latest state machine update height
2330
+ * @params statemachineId - ID of the state machine
2331
+ * @params chain - The identifier for the chain where the state machine update should be queried (corresponds to a stateMachineId)
2332
+ * @returns Latest height or undefined if no updates found
2333
+ */
2334
+ queryLatestStateMachineHeight({ statemachineId, chain, }: {
2335
+ statemachineId: string;
2336
+ chain: string;
2337
+ }): Promise<bigint | undefined>;
2303
2338
  /**
2304
2339
  * Queries a request by CommitmentHash
2305
2340
  *
@@ -2764,6 +2799,13 @@ declare class IntentGateway {
2764
2799
  fee?: number;
2765
2800
  transactions?: Transaction[];
2766
2801
  }>;
2802
+ createMultiHopSwapThroughPair(dexPairAddress: HexString, tokenIn: HexString, tokenOut: HexString, amountIn: bigint, evmChainID: string, getQuoteIn: "source" | "dest", recipient: HexString, protocol?: "v2" | "v3"): Promise<{
2803
+ finalAmountOut: bigint;
2804
+ calldata: Transaction[];
2805
+ }>;
2806
+ private buildSwapPath;
2807
+ private executeSwapPath;
2808
+ private createSwapCalldata;
2767
2809
  /**
2768
2810
  * Checks if an order has been filled by verifying the commitment status on-chain.
2769
2811
  * Reads the storage slot corresponding to the order's commitment hash.
@@ -3195,4 +3237,4 @@ declare const coingeckoIds: {
3195
3237
  "EVM-130": string;
3196
3238
  };
3197
3239
 
3198
- 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, type Transaction, 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, maxBigInt, orderCommitment, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, requestCommitmentKey, teleport, teleportDot, viemChains };
3240
+ 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, TESTNET_CHAINS, TeleportStatus, TimeoutStatus, type TimeoutStatusKey, type TokenGatewayAssetTeleportedResponse, type TokenGatewayAssetTeleportedWithStatus, type TokenInfo, type TokenPrice, type TokenPricesResponse, type TokenRegistry, type TokenRegistryResponse, type Transaction, USE_ETHERSCAN_CHAINS, WrappedNativeDecimals, type XcmGatewayParams, __test, addresses, adjustFeeDecimals, assets, bytes20ToBytes32, bytes32ToBytes20, chainIds, coingeckoIds, consensusStateIds, constructRedeemEscrowRequestBody, convertStateIdToStateMachineId, convertStateMachineIdToEnum, createQueryClient, createRpcUrls, encodeISMPMessage, estimateGasForPost, fetchPrice, generateRootWithProof, getChain, getGasPriceFromEtherscan, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, hexToString, maxBigInt, orderCommitment, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, requestCommitmentKey, retryPromise, teleport, teleportDot, viemChains };
@@ -3528,7 +3528,13 @@ var addresses = {
3528
3528
  ["EVM-130" /* UNICHAIN_MAINNET */]: "0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203"
3529
3529
  },
3530
3530
  Calldispatcher: {
3531
- ["EVM-11155111" /* SEPOLIA */]: "0xC7f13b6D03A0A7F3239d38897503E90553ABe155"
3531
+ ["EVM-11155111" /* SEPOLIA */]: "0xC7f13b6D03A0A7F3239d38897503E90553ABe155",
3532
+ ["EVM-1" /* MAINNET */]: "0xc71251c8b3e7b02697a84363eef6dce8dfbdf333",
3533
+ ["EVM-56" /* BSC_MAINNET */]: "0xc71251c8b3e7b02697a84363eef6dce8dfbdf333",
3534
+ ["EVM-42161" /* ARBITRUM_MAINNET */]: "0xc71251c8b3e7b02697a84363eef6dce8dfbdf333",
3535
+ ["EVM-8453" /* BASE_MAINNET */]: "0xc71251c8b3e7b02697a84363eef6dce8dfbdf333",
3536
+ ["EVM-137" /* POLYGON_MAINNET */]: "0xc71251c8b3e7b02697a84363eef6dce8dfbdf333",
3537
+ ["EVM-130" /* UNICHAIN_MAINNET */]: "0xc71251c8b3e7b02697a84363eef6dce8dfbdf333"
3532
3538
  },
3533
3539
  Permit2: {
3534
3540
  ["EVM-1" /* MAINNET */]: "0x000000000022D473030F116dDEE9F6B43aC78BA3",
@@ -3643,6 +3649,12 @@ var ChainConfigService = class {
3643
3649
  getCoingeckoId(chain) {
3644
3650
  return coingeckoIds[chain];
3645
3651
  }
3652
+ getEtherscanApiKey() {
3653
+ return typeof process !== "undefined" ? process?.env?.ETHERSCAN_API_KEY : void 0;
3654
+ }
3655
+ getCalldispatcherAddress(chain) {
3656
+ return addresses.Calldispatcher[chain];
3657
+ }
3646
3658
  };
3647
3659
  function getPeakPosByHeight(height) {
3648
3660
  return (1n << BigInt(height + 1)) - 2n;
@@ -4525,6 +4537,24 @@ async function fetchPrice(identifier, chainId = 1, apiKey) {
4525
4537
  }
4526
4538
  return data[key].usd;
4527
4539
  }
4540
+ async function getGasPriceFromEtherscan(chainId, apiKey) {
4541
+ let parsedChainId = Number(chainId.split("-")[1]);
4542
+ const url = apiKey ? `https://api.etherscan.io/v2/api?chainid=${parsedChainId}&module=gastracker&action=gasoracle&apikey=${apiKey}` : `https://api.etherscan.io/v2/api?chainid=${parsedChainId}&module=gastracker&action=gasoracle`;
4543
+ const response = await fetch(url);
4544
+ const data = await response.json();
4545
+ return gweiToWei(data.result.ProposeGasPrice);
4546
+ }
4547
+ function gweiToWei(gwei) {
4548
+ if (!gwei || typeof gwei !== "string") {
4549
+ throw new Error(`Invalid gwei value: ${gwei}`);
4550
+ }
4551
+ const [intPart, fracPartRaw] = gwei.split(".");
4552
+ const fracPart = (fracPartRaw || "").slice(0, 9);
4553
+ const fracPadded = fracPart.padEnd(9, "0");
4554
+ const whole = BigInt(intPart || "0") * 1000000000n;
4555
+ const fractional = BigInt(fracPadded || "0");
4556
+ return whole + fractional;
4557
+ }
4528
4558
  var ERC20Method = /* @__PURE__ */ ((ERC20Method2) => {
4529
4559
  ERC20Method2["BALANCE_OF"] = "0x70a08231";
4530
4560
  ERC20Method2["ALLOWANCE"] = "0xdd62ed3e";
@@ -4631,6 +4661,8 @@ function adjustFeeDecimals(feeInFeeToken, fromDecimals, toDecimals) {
4631
4661
  return (feeInFeeToken + scaleFactor - 1n) / scaleFactor;
4632
4662
  }
4633
4663
  }
4664
+ var USE_ETHERSCAN_CHAINS = /* @__PURE__ */ new Set(["EVM-137", "EVM-56", "EVM-1"]);
4665
+ var TESTNET_CHAINS = /* @__PURE__ */ new Set(["EVM-10200", "EVM-97"]);
4634
4666
  function replaceWebsocketWithHttp(url) {
4635
4667
  if (url.startsWith("ws://")) {
4636
4668
  return url.replace("ws://", "http://");
@@ -6716,6 +6748,30 @@ query StateMachineUpdatesByTimestamp($statemachineId: String!, $commitmentTimest
6716
6748
  }
6717
6749
  }
6718
6750
  `;
6751
+ var LATEST_STATE_MACHINE_UPDATE = `
6752
+ query LatestStateMachineUpdate($statemachineId: String!, $chain: String!) {
6753
+ stateMachineUpdateEvents(
6754
+ filter: {
6755
+ and: [
6756
+ { stateMachineId: { equalTo: $statemachineId } }
6757
+ { chain: { equalTo: $chain } }
6758
+ ]
6759
+ }
6760
+ orderBy: HEIGHT_DESC
6761
+ first: 1
6762
+ ) {
6763
+ nodes {
6764
+ height
6765
+ stateMachineId
6766
+ chain
6767
+ blockHash
6768
+ blockNumber
6769
+ transactionHash
6770
+ createdAt
6771
+ }
6772
+ }
6773
+ }
6774
+ `;
6719
6775
  var ASSET_TELEPORTED_BY_PARAMS = `
6720
6776
  query AssetTeleportedByParams($id: String!) {
6721
6777
  assetTeleported(id: $id) {
@@ -7105,6 +7161,32 @@ var IndexerClient = class {
7105
7161
  logger.trace("Response >", first_node);
7106
7162
  return first_node;
7107
7163
  }
7164
+ /**
7165
+ * Query for the latest state machine update height
7166
+ * @params statemachineId - ID of the state machine
7167
+ * @params chain - The identifier for the chain where the state machine update should be queried (corresponds to a stateMachineId)
7168
+ * @returns Latest height or undefined if no updates found
7169
+ */
7170
+ async queryLatestStateMachineHeight({
7171
+ statemachineId,
7172
+ chain
7173
+ }) {
7174
+ const logger = this.logger.withTag("[queryLatestStateMachineHeight]()");
7175
+ const message = `querying latest StateMachineId(${statemachineId}) height in chain Chain(${chain})`;
7176
+ const response = await this.withRetry(
7177
+ () => {
7178
+ return this.client.request(LATEST_STATE_MACHINE_UPDATE, {
7179
+ statemachineId,
7180
+ chain
7181
+ });
7182
+ },
7183
+ { logger, logMessage: message }
7184
+ );
7185
+ const first_node = response?.stateMachineUpdateEvents?.nodes[0];
7186
+ if (!first_node) return void 0;
7187
+ logger.trace("Latest height >", first_node.height);
7188
+ return BigInt(first_node.height);
7189
+ }
7108
7190
  /**
7109
7191
  * Queries a request by CommitmentHash
7110
7192
  *
@@ -10331,6 +10413,37 @@ var UNISWAP_V4_QUOTER_ABI = [
10331
10413
  }
10332
10414
  ];
10333
10415
 
10416
+ // src/abis/uniswapV2Pair.ts
10417
+ var ABI6 = [
10418
+ {
10419
+ inputs: [],
10420
+ name: "token0",
10421
+ outputs: [
10422
+ {
10423
+ internalType: "address",
10424
+ name: "",
10425
+ type: "address"
10426
+ }
10427
+ ],
10428
+ stateMutability: "view",
10429
+ type: "function"
10430
+ },
10431
+ {
10432
+ inputs: [],
10433
+ name: "token1",
10434
+ outputs: [
10435
+ {
10436
+ internalType: "address",
10437
+ name: "",
10438
+ type: "address"
10439
+ }
10440
+ ],
10441
+ stateMutability: "view",
10442
+ type: "function"
10443
+ }
10444
+ ];
10445
+ var uniswapV2Pair_default = { ABI: ABI6 };
10446
+
10334
10447
  // src/abis/permit2.ts
10335
10448
  var PERMIT2_ABI = [
10336
10449
  {
@@ -10363,7 +10476,7 @@ var PERMIT2_ABI = [
10363
10476
  ];
10364
10477
 
10365
10478
  // src/abis/universalRouter.ts
10366
- var ABI6 = [
10479
+ var ABI7 = [
10367
10480
  {
10368
10481
  inputs: [
10369
10482
  {
@@ -10806,7 +10919,7 @@ var ABI6 = [
10806
10919
  type: "receive"
10807
10920
  }
10808
10921
  ];
10809
- var universalRouter_default = { ABI: ABI6 };
10922
+ var universalRouter_default = { ABI: ABI7 };
10810
10923
 
10811
10924
  // src/protocols/intents.ts
10812
10925
  var IntentGateway = class {
@@ -11026,7 +11139,15 @@ var IntentGateway = class {
11026
11139
  */
11027
11140
  async convertGasToFeeToken(gasEstimate, gasEstimateIn, evmChainID) {
11028
11141
  const client = this[gasEstimateIn].client;
11029
- const gasPrice = await client.getGasPrice();
11142
+ const useEtherscan = USE_ETHERSCAN_CHAINS.has(evmChainID);
11143
+ const etherscanApiKey = useEtherscan ? this[gasEstimateIn].config.getEtherscanApiKey() : void 0;
11144
+ const gasPrice = useEtherscan && etherscanApiKey ? await retryPromise(() => getGasPriceFromEtherscan(evmChainID, etherscanApiKey), {
11145
+ maxRetries: 3,
11146
+ backoffMs: 250
11147
+ }).catch(async () => {
11148
+ console.warn({ evmChainID }, "Error getting gas price from etherscan, using client's gas price");
11149
+ return await client.getGasPrice();
11150
+ }) : await client.getGasPrice();
11030
11151
  const gasCostInWei = gasEstimate * gasPrice;
11031
11152
  const wethAddr = this[gasEstimateIn].config.getWrappedNativeAssetWithDecimals(evmChainID).asset;
11032
11153
  const feeToken = await this[gasEstimateIn].getFeeTokenWithDecimals();
@@ -11098,8 +11219,8 @@ var IntentGateway = class {
11098
11219
  args: [amountOut, [tokenInForQuote, tokenOutForQuote]]
11099
11220
  });
11100
11221
  return v2AmountIn.result[0];
11101
- } catch (error) {
11102
- console.warn("V2 quote failed:", error);
11222
+ } catch {
11223
+ console.warn("V2 quote failed:");
11103
11224
  return maxUint256;
11104
11225
  }
11105
11226
  }
@@ -11122,8 +11243,8 @@ var IntentGateway = class {
11122
11243
  args: [amountIn, [tokenInForQuote, tokenOutForQuote]]
11123
11244
  });
11124
11245
  return v2AmountOut.result[1];
11125
- } catch (error) {
11126
- console.warn("V2 quote failed:", error);
11246
+ } catch {
11247
+ console.warn("V2 quote failed:");
11127
11248
  return BigInt(0);
11128
11249
  }
11129
11250
  }
@@ -11160,7 +11281,7 @@ var IntentGateway = class {
11160
11281
  bestAmountIn = amountIn;
11161
11282
  bestFee = fee;
11162
11283
  }
11163
- } catch (error) {
11284
+ } catch {
11164
11285
  console.warn(`V3 quote failed for fee ${fee}, continuing to next fee tier`);
11165
11286
  }
11166
11287
  }
@@ -11199,7 +11320,7 @@ var IntentGateway = class {
11199
11320
  bestAmountOut = amountOut;
11200
11321
  bestFee = fee;
11201
11322
  }
11202
- } catch (error) {
11323
+ } catch {
11203
11324
  console.warn(`V3 quote failed for fee ${fee}, continuing to next fee tier`);
11204
11325
  }
11205
11326
  }
@@ -11244,7 +11365,7 @@ var IntentGateway = class {
11244
11365
  bestAmountIn = amountIn;
11245
11366
  bestFee = fee;
11246
11367
  }
11247
- } catch (error) {
11368
+ } catch {
11248
11369
  console.warn(`V4 quote failed for fee ${fee}, continuing to next fee tier`);
11249
11370
  }
11250
11371
  }
@@ -11289,7 +11410,7 @@ var IntentGateway = class {
11289
11410
  bestAmountOut = amountOut;
11290
11411
  bestFee = fee;
11291
11412
  }
11292
- } catch (error) {
11413
+ } catch {
11293
11414
  console.warn(`V4 quote failed for fee ${fee}, continuing to next fee tier`);
11294
11415
  }
11295
11416
  }
@@ -12181,6 +12302,108 @@ var IntentGateway = class {
12181
12302
  };
12182
12303
  }
12183
12304
  }
12305
+ async createMultiHopSwapThroughPair(dexPairAddress, tokenIn, tokenOut, amountIn, evmChainID, getQuoteIn, recipient, protocol = "v2") {
12306
+ const client = this[getQuoteIn].client;
12307
+ const wethAsset = this[getQuoteIn].config.getWrappedNativeAssetWithDecimals(evmChainID).asset;
12308
+ const calldispatcher = this[getQuoteIn].config.getCalldispatcherAddress(evmChainID);
12309
+ const [token0, token1] = await Promise.all([
12310
+ client.readContract({
12311
+ address: dexPairAddress,
12312
+ abi: uniswapV2Pair_default.ABI,
12313
+ functionName: "token0"
12314
+ }),
12315
+ client.readContract({
12316
+ address: dexPairAddress,
12317
+ abi: uniswapV2Pair_default.ABI,
12318
+ functionName: "token1"
12319
+ })
12320
+ ]);
12321
+ const intermediateToken = tokenOut.toLowerCase() === token0.toLowerCase() ? token1 : token0;
12322
+ const swapPath = this.buildSwapPath(tokenIn, tokenOut, intermediateToken, wethAsset, calldispatcher, recipient);
12323
+ return this.executeSwapPath(swapPath, amountIn, evmChainID, getQuoteIn, protocol);
12324
+ }
12325
+ buildSwapPath(tokenIn, tokenOut, intermediateToken, wethAsset, calldispatcher, recipient) {
12326
+ const normalize = (token) => token.toLowerCase();
12327
+ if (normalize(intermediateToken) === normalize(tokenIn)) {
12328
+ return [{ from: tokenIn, to: tokenOut, recipient }];
12329
+ }
12330
+ if (normalize(intermediateToken) === normalize(wethAsset)) {
12331
+ return [
12332
+ { from: tokenIn, to: wethAsset, recipient: calldispatcher },
12333
+ { from: wethAsset, to: tokenOut, recipient }
12334
+ ];
12335
+ }
12336
+ return [
12337
+ { from: tokenIn, to: wethAsset, recipient: calldispatcher },
12338
+ { from: wethAsset, to: intermediateToken, recipient: calldispatcher },
12339
+ { from: intermediateToken, to: tokenOut, recipient }
12340
+ ];
12341
+ }
12342
+ async executeSwapPath(path, initialAmount, evmChainID, getQuoteIn, protocol) {
12343
+ let currentAmount = initialAmount;
12344
+ const calldata = [];
12345
+ for (let i = 0; i < path.length; i++) {
12346
+ const segment = path[i];
12347
+ const isLastSwap = i === path.length - 1;
12348
+ const slippage = isLastSwap && path.length > 1 ? 990n : 995n;
12349
+ const swapResult = await this.createSwapCalldata(
12350
+ protocol,
12351
+ segment.from,
12352
+ segment.to,
12353
+ currentAmount,
12354
+ segment.recipient,
12355
+ evmChainID,
12356
+ getQuoteIn,
12357
+ slippage
12358
+ );
12359
+ currentAmount = swapResult.amountOut;
12360
+ calldata.push(...swapResult.calldata);
12361
+ }
12362
+ return {
12363
+ finalAmountOut: currentAmount,
12364
+ calldata
12365
+ };
12366
+ }
12367
+ async createSwapCalldata(protocol, tokenIn, tokenOut, amountIn, recipient, evmChainID, getQuoteIn, slippageFactor) {
12368
+ if (protocol === "v2") {
12369
+ let amountOut = await this.getV2QuoteWithAmountIn(getQuoteIn, tokenIn, tokenOut, amountIn, evmChainID);
12370
+ amountOut = amountOut * slippageFactor / 1000n;
12371
+ return {
12372
+ amountOut,
12373
+ calldata: this.createV2SwapCalldataExactIn(
12374
+ tokenIn,
12375
+ tokenOut,
12376
+ amountIn,
12377
+ amountOut,
12378
+ recipient,
12379
+ evmChainID,
12380
+ getQuoteIn
12381
+ )
12382
+ };
12383
+ } else {
12384
+ const { amountOut, fee } = await this.getV3QuoteWithAmountIn(
12385
+ getQuoteIn,
12386
+ tokenIn,
12387
+ tokenOut,
12388
+ amountIn,
12389
+ evmChainID
12390
+ );
12391
+ const adjustedAmountOut = amountOut * slippageFactor / 1000n;
12392
+ return {
12393
+ amountOut: adjustedAmountOut,
12394
+ calldata: this.createV3SwapCalldataExactIn(
12395
+ tokenIn,
12396
+ tokenOut,
12397
+ amountIn,
12398
+ adjustedAmountOut,
12399
+ fee,
12400
+ recipient,
12401
+ evmChainID,
12402
+ getQuoteIn
12403
+ )
12404
+ };
12405
+ }
12406
+ }
12184
12407
  /**
12185
12408
  * Checks if an order has been filled by verifying the commitment status on-chain.
12186
12409
  * Reads the storage slot corresponding to the order's commitment hash.
@@ -12239,13 +12462,17 @@ var IntentGateway = class {
12239
12462
  let lastFailedHeight = null;
12240
12463
  let proofHex = null;
12241
12464
  while (!proofHex) {
12242
- latestHeight = await retryPromise(
12243
- () => hyperbridge.latestStateMachineHeight({
12244
- stateId: parseStateMachineId(destStateMachine).stateId,
12245
- consensusStateId: destConsensusStateId
12465
+ const height = await retryPromise(
12466
+ () => indexerClient.queryLatestStateMachineHeight({
12467
+ statemachineId: destStateMachine,
12468
+ chain: hyperbridgeConfig.stateMachineId
12246
12469
  }),
12247
12470
  { maxRetries: 5, backoffMs: 500, logMessage: "Failed to fetch latest state machine height" }
12248
12471
  );
12472
+ if (!height) {
12473
+ throw new Error("No state machine updates found for destination chain");
12474
+ }
12475
+ latestHeight = height;
12249
12476
  const shouldFetchProof = lastFailedHeight === null ? latestHeight > order.deadline : latestHeight > lastFailedHeight;
12250
12477
  if (!shouldFetchProof) {
12251
12478
  yield {
@@ -12317,9 +12544,9 @@ var IntentGateway = class {
12317
12544
  break;
12318
12545
  }
12319
12546
  const nextHeight = await retryPromise(
12320
- () => hyperbridge.latestStateMachineHeight({
12321
- stateId: parseStateMachineId(sourceStateMachine).stateId,
12322
- consensusStateId: sourceConsensusStateId
12547
+ () => indexerClient.queryLatestStateMachineHeight({
12548
+ statemachineId: sourceStateMachine,
12549
+ chain: hyperbridgeConfig.stateMachineId
12323
12550
  }),
12324
12551
  {
12325
12552
  maxRetries: 5,
@@ -12327,6 +12554,11 @@ var IntentGateway = class {
12327
12554
  logMessage: "Failed to fetch latest state machine height (post-source-proof failure)"
12328
12555
  }
12329
12556
  );
12557
+ if (!nextHeight) {
12558
+ throw new Error(
12559
+ `No state machine updates found for ${sourceStateMachine} on chain ${hyperbridgeConfig.stateMachineId}`
12560
+ );
12561
+ }
12330
12562
  if (nextHeight <= failedHeight) {
12331
12563
  await sleep(1e4);
12332
12564
  continue;
@@ -12746,6 +12978,6 @@ async function teleportDot(param_) {
12746
12978
  return stream;
12747
12979
  }
12748
12980
 
12749
- 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, maxBigInt, orderCommitment, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, requestCommitmentKey, teleport, teleportDot, viemChains };
12981
+ 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, TESTNET_CHAINS, TeleportStatus, TimeoutStatus, USE_ETHERSCAN_CHAINS, WrappedNativeDecimals, __test, addresses, adjustFeeDecimals, assets, bytes20ToBytes32, bytes32ToBytes20, chainIds, coingeckoIds, consensusStateIds, constructRedeemEscrowRequestBody, convertStateIdToStateMachineId, convertStateMachineIdToEnum, createQueryClient, createRpcUrls, encodeISMPMessage, estimateGasForPost, fetchPrice, generateRootWithProof, getChain, getGasPriceFromEtherscan, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, hexToString, maxBigInt, orderCommitment, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, requestCommitmentKey, retryPromise, teleport, teleportDot, viemChains };
12750
12982
  //# sourceMappingURL=index.js.map
12751
12983
  //# sourceMappingURL=index.js.map