@hyperbridge/sdk 1.3.14 → 1.3.16

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.
@@ -2611,6 +2611,7 @@ declare class IntentGateway {
2611
2611
  *
2612
2612
  * @param feeTokenAmount - The amount in fee token (DAI)
2613
2613
  * @param getQuoteIn - Whether to use "source" or "dest" chain for the conversion
2614
+ * @param evmChainID - The EVM chain ID in format "EVM-{id}"
2614
2615
  * @returns The fee token amount converted to native token amount
2615
2616
  * @private
2616
2617
  */
@@ -2621,6 +2622,7 @@ declare class IntentGateway {
2621
2622
  *
2622
2623
  * @param gasEstimate - The estimated gas units
2623
2624
  * @param gasEstimateIn - Whether to use "source" or "dest" chain for the conversion
2625
+ * @param evmChainID - The EVM chain ID in format "EVM-{id}"
2624
2626
  * @returns The gas cost converted to fee token amount
2625
2627
  * @private
2626
2628
  */
@@ -2656,10 +2658,11 @@ declare class IntentGateway {
2656
2658
  * @param tokenIn - The address of the input token
2657
2659
  * @param tokenOut - The address of the output token
2658
2660
  * @param amountIn - The input amount to swap
2661
+ * @param evmChainID - The EVM chain ID in format "EVM-{id}"
2659
2662
  * @param selectedProtocol - Optional specific protocol to use ("v2", "v3", or "v4")
2660
2663
  * @returns Object containing the best protocol, expected output amount, and fee tier (for V3/V4)
2661
2664
  */
2662
- findBestProtocolWithAmountIn(getQuoteIn: "source" | "dest", tokenIn: HexString, tokenOut: HexString, amountIn: bigint, selectedProtocol?: "v2" | "v3" | "v4"): Promise<{
2665
+ findBestProtocolWithAmountIn(getQuoteIn: "source" | "dest", tokenIn: HexString, tokenOut: HexString, amountIn: bigint, evmChainID: string, selectedProtocol?: "v2" | "v3" | "v4"): Promise<{
2663
2666
  protocol: "v2" | "v3" | "v4" | null;
2664
2667
  amountOut: bigint;
2665
2668
  fee?: number;
@@ -2,7 +2,7 @@ import { createConsola, LogLevels } from 'consola';
2
2
  import { flatten, zip, capitalize, maxBy, isNil } from 'lodash-es';
3
3
  import { toHex, hexToBytes, encodePacked, keccak256, encodeAbiParameters, bytesToHex, concatHex, createPublicClient, http, encodeFunctionData, erc20Abi, bytesToBigInt, pad, toBytes, maxUint256, formatUnits, parseUnits, hexToString as hexToString$1 } from 'viem';
4
4
  import mergeRace from '@async-generator/merge-race';
5
- import { gnosisChiado, gnosis, bscTestnet, bsc, soneium, baseSepolia, base, optimismSepolia, optimism, arbitrumSepolia, arbitrum, mainnet, unichain, polygon, sepolia } from 'viem/chains';
5
+ import { unichain, polygon, gnosisChiado, gnosis, bscTestnet, bsc, soneium, baseSepolia, base, optimismSepolia, optimism, arbitrumSepolia, arbitrum, mainnet, sepolia } from 'viem/chains';
6
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';
@@ -3443,7 +3443,7 @@ var assets = {
3443
3443
  USDT: "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2".toLowerCase()
3444
3444
  },
3445
3445
  ["EVM-137" /* POLYGON_MAINNET */]: {
3446
- WETH: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619".toLowerCase(),
3446
+ WETH: "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270".toLowerCase(),
3447
3447
  DAI: "0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063".toLowerCase(),
3448
3448
  USDC: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359".toLowerCase(),
3449
3449
  USDT: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F".toLowerCase()
@@ -4643,7 +4643,9 @@ var chains = {
4643
4643
  [bsc.id]: bsc,
4644
4644
  [bscTestnet.id]: bscTestnet,
4645
4645
  [gnosis.id]: gnosis,
4646
- [gnosisChiado.id]: gnosisChiado
4646
+ [gnosisChiado.id]: gnosisChiado,
4647
+ [polygon.id]: polygon,
4648
+ [unichain.id]: unichain
4647
4649
  };
4648
4650
  var DEFAULT_ADDRESS = "0x0000000000000000000000000000000000000000";
4649
4651
  var EvmChain = class {
@@ -11749,7 +11751,11 @@ var IntentGateway = class {
11749
11751
  const { decimals: sourceChainFeeTokenDecimals } = await this.source.getFeeTokenWithDecimals();
11750
11752
  const { address: destChainFeeTokenAddress, decimals: destChainFeeTokenDecimals } = await this.dest.getFeeTokenWithDecimals();
11751
11753
  const { gas: postGasEstimate, postRequestCalldata } = await this.source.estimateGas(postRequest);
11752
- const postGasEstimateInSourceFeeToken = await this.convertGasToFeeToken(postGasEstimate, "source");
11754
+ const postGasEstimateInSourceFeeToken = await this.convertGasToFeeToken(
11755
+ postGasEstimate,
11756
+ "source",
11757
+ order.sourceChain
11758
+ );
11753
11759
  const relayerFeeInSourceFeeToken = postGasEstimateInSourceFeeToken + 25n * 10n ** BigInt(sourceChainFeeTokenDecimals - 2);
11754
11760
  const relayerFeeInDestFeeToken = adjustFeeDecimals(
11755
11761
  relayerFeeInSourceFeeToken,
@@ -11804,7 +11810,6 @@ var IntentGateway = class {
11804
11810
  }))
11805
11811
  ];
11806
11812
  let destChainFillGas = 0n;
11807
- let filledWithNativeToken = false;
11808
11813
  try {
11809
11814
  let protocolFeeInNativeToken = await this.quoteNative(postRequest, relayerFeeInDestFeeToken);
11810
11815
  protocolFeeInNativeToken = protocolFeeInNativeToken + protocolFeeInNativeToken * 50n / 10000n;
@@ -11817,7 +11822,6 @@ var IntentGateway = class {
11817
11822
  value: totalEthValue + protocolFeeInNativeToken,
11818
11823
  stateOverride: stateOverrides
11819
11824
  });
11820
- filledWithNativeToken = true;
11821
11825
  } catch {
11822
11826
  console.warn(
11823
11827
  `Could not estimate gas for fill order with native token as fees for chain ${order.destChain}, now trying with fee token as fees`
@@ -11852,7 +11856,7 @@ var IntentGateway = class {
11852
11856
  stateOverride: stateOverrides
11853
11857
  });
11854
11858
  }
11855
- const fillGasInDestFeeToken = await this.convertGasToFeeToken(destChainFillGas, "dest");
11859
+ const fillGasInDestFeeToken = await this.convertGasToFeeToken(destChainFillGas, "dest", order.destChain);
11856
11860
  const fillGasInSourceFeeToken = adjustFeeDecimals(
11857
11861
  fillGasInDestFeeToken,
11858
11862
  destChainFeeTokenDecimals,
@@ -11864,7 +11868,11 @@ var IntentGateway = class {
11864
11868
  sourceChainFeeTokenDecimals
11865
11869
  );
11866
11870
  let totalEstimateInSourceFeeToken = fillGasInSourceFeeToken + protocolFeeInSourceFeeToken + relayerFeeInSourceFeeToken;
11867
- let totalNativeTokenAmount = await this.convertFeeTokenToNative(totalEstimateInSourceFeeToken, "source");
11871
+ let totalNativeTokenAmount = await this.convertFeeTokenToNative(
11872
+ totalEstimateInSourceFeeToken,
11873
+ "source",
11874
+ order.sourceChain
11875
+ );
11868
11876
  if ([order.destChain, order.sourceChain].includes("EVM-1")) {
11869
11877
  totalEstimateInSourceFeeToken = totalEstimateInSourceFeeToken + totalEstimateInSourceFeeToken * 3000n / 10000n;
11870
11878
  totalNativeTokenAmount = totalNativeTokenAmount + totalNativeTokenAmount * 3200n / 10000n;
@@ -11884,12 +11892,12 @@ var IntentGateway = class {
11884
11892
  *
11885
11893
  * @param feeTokenAmount - The amount in fee token (DAI)
11886
11894
  * @param getQuoteIn - Whether to use "source" or "dest" chain for the conversion
11895
+ * @param evmChainID - The EVM chain ID in format "EVM-{id}"
11887
11896
  * @returns The fee token amount converted to native token amount
11888
11897
  * @private
11889
11898
  */
11890
- async convertFeeTokenToNative(feeTokenAmount, getQuoteIn) {
11899
+ async convertFeeTokenToNative(feeTokenAmount, getQuoteIn, evmChainID) {
11891
11900
  const client = this[getQuoteIn].client;
11892
- const evmChainID = `EVM-${client.chain?.id}`;
11893
11901
  const wethAsset = this[getQuoteIn].config.getWrappedNativeAssetWithDecimals(evmChainID).asset;
11894
11902
  const feeToken = await this[getQuoteIn].getFeeTokenWithDecimals();
11895
11903
  try {
@@ -11898,6 +11906,7 @@ var IntentGateway = class {
11898
11906
  feeToken.address,
11899
11907
  wethAsset,
11900
11908
  feeTokenAmount,
11909
+ evmChainID,
11901
11910
  "v2"
11902
11911
  );
11903
11912
  if (amountOut === 0n) {
@@ -11906,7 +11915,7 @@ var IntentGateway = class {
11906
11915
  return amountOut;
11907
11916
  } catch {
11908
11917
  const nativeCurrency = client.chain?.nativeCurrency;
11909
- const chainId = client.chain?.id;
11918
+ const chainId = Number.parseInt(evmChainID.split("-")[1]);
11910
11919
  const feeTokenAmountDecimal = new Decimal(formatUnits(feeTokenAmount, feeToken.decimals));
11911
11920
  const nativeTokenPriceUsd = new Decimal(await fetchPrice(nativeCurrency?.symbol, chainId));
11912
11921
  const totalCostInNativeToken = feeTokenAmountDecimal.dividedBy(nativeTokenPriceUsd);
@@ -11919,14 +11928,14 @@ var IntentGateway = class {
11919
11928
  *
11920
11929
  * @param gasEstimate - The estimated gas units
11921
11930
  * @param gasEstimateIn - Whether to use "source" or "dest" chain for the conversion
11931
+ * @param evmChainID - The EVM chain ID in format "EVM-{id}"
11922
11932
  * @returns The gas cost converted to fee token amount
11923
11933
  * @private
11924
11934
  */
11925
- async convertGasToFeeToken(gasEstimate, gasEstimateIn) {
11935
+ async convertGasToFeeToken(gasEstimate, gasEstimateIn, evmChainID) {
11926
11936
  const client = this[gasEstimateIn].client;
11927
11937
  const gasPrice = await client.getGasPrice();
11928
11938
  const gasCostInWei = gasEstimate * gasPrice;
11929
- const evmChainID = `EVM-${client.chain?.id}`;
11930
11939
  const wethAddr = this[gasEstimateIn].config.getWrappedNativeAssetWithDecimals(evmChainID).asset;
11931
11940
  const feeToken = await this[gasEstimateIn].getFeeTokenWithDecimals();
11932
11941
  try {
@@ -11935,15 +11944,17 @@ var IntentGateway = class {
11935
11944
  wethAddr,
11936
11945
  feeToken.address,
11937
11946
  gasCostInWei,
11947
+ evmChainID,
11938
11948
  "v2"
11939
11949
  );
11940
11950
  if (amountOut === 0n) {
11951
+ console.log("Amount out not found");
11941
11952
  throw new Error();
11942
11953
  }
11943
11954
  return amountOut;
11944
11955
  } catch {
11945
11956
  const nativeCurrency = client.chain?.nativeCurrency;
11946
- const chainId = client.chain?.id;
11957
+ const chainId = Number.parseInt(evmChainID.split("-")[1]);
11947
11958
  const gasCostInToken = new Decimal(formatUnits(gasCostInWei, nativeCurrency?.decimals));
11948
11959
  const tokenPriceUsd = await fetchPrice(nativeCurrency?.symbol, chainId);
11949
11960
  const gasCostUsd = gasCostInToken.times(tokenPriceUsd);
@@ -12149,12 +12160,12 @@ var IntentGateway = class {
12149
12160
  * @param tokenIn - The address of the input token
12150
12161
  * @param tokenOut - The address of the output token
12151
12162
  * @param amountIn - The input amount to swap
12163
+ * @param evmChainID - The EVM chain ID in format "EVM-{id}"
12152
12164
  * @param selectedProtocol - Optional specific protocol to use ("v2", "v3", or "v4")
12153
12165
  * @returns Object containing the best protocol, expected output amount, and fee tier (for V3/V4)
12154
12166
  */
12155
- async findBestProtocolWithAmountIn(getQuoteIn, tokenIn, tokenOut, amountIn, selectedProtocol) {
12167
+ async findBestProtocolWithAmountIn(getQuoteIn, tokenIn, tokenOut, amountIn, evmChainID, selectedProtocol) {
12156
12168
  const client = this[getQuoteIn].client;
12157
- const evmChainID = `EVM-${client.chain?.id}`;
12158
12169
  let amountOutV2 = BigInt(0);
12159
12170
  let amountOutV3 = BigInt(0);
12160
12171
  let amountOutV4 = BigInt(0);
@@ -12354,7 +12365,7 @@ var IntentGateway = class {
12354
12365
  if (!value) throw new Error("Receipt not found");
12355
12366
  return value;
12356
12367
  },
12357
- { maxRetries: 5, backoffMs: 5e3, logMessage: "Checking for receipt" }
12368
+ { maxRetries: 10, backoffMs: 5e3, logMessage: "Checking for receipt" }
12358
12369
  );
12359
12370
  }
12360
12371
  console.log("Hyperbridge Receipt confirmed.");
@@ -12431,34 +12442,74 @@ var IntentGateway = class {
12431
12442
  const sourceStatusStream = indexerClient.getRequestStatusStream(commitment);
12432
12443
  for await (const statusUpdate of sourceStatusStream) {
12433
12444
  if (statusUpdate.status === RequestStatus.SOURCE_FINALIZED) {
12434
- const sourceHeight = BigInt(statusUpdate.metadata.blockNumber);
12435
- const proof = await this.source.queryProof(
12436
- { Requests: [commitment] },
12437
- hyperbridgeConfig.stateMachineId,
12438
- sourceHeight
12439
- );
12440
- const sourceIProof = {
12441
- height: sourceHeight,
12442
- stateMachine: sourceStateMachine,
12443
- consensusStateId: sourceConsensusStateId,
12444
- proof
12445
+ let sourceHeight = BigInt(statusUpdate.metadata.blockNumber);
12446
+ let proof;
12447
+ const checkIfAlreadyDelivered = async () => {
12448
+ const currentStatus = await indexerClient.queryGetRequestWithStatus(commitment);
12449
+ return currentStatus?.statuses.some(
12450
+ (status) => status.status === RequestStatus.HYPERBRIDGE_DELIVERED
12451
+ ) ?? false;
12445
12452
  };
12446
- yield { status: "SOURCE_PROOF_RECEIVED", data: sourceIProof };
12447
- const getRequestMessage = {
12448
- kind: "GetRequest",
12449
- requests: [getRequest],
12450
- source: sourceIProof,
12451
- response: destIProof,
12452
- signer: pad("0x")
12453
- };
12454
- await waitForChallengePeriod(hyperbridge, {
12455
- height: sourceHeight,
12456
- id: {
12457
- stateId: parseStateMachineId(sourceStateMachine).stateId,
12458
- consensusStateId: sourceConsensusStateId
12453
+ while (true) {
12454
+ try {
12455
+ proof = await this.source.queryProof(
12456
+ { Requests: [commitment] },
12457
+ hyperbridgeConfig.stateMachineId,
12458
+ sourceHeight
12459
+ );
12460
+ break;
12461
+ } catch {
12462
+ const failedHeight = sourceHeight;
12463
+ while (sourceHeight <= failedHeight) {
12464
+ if (await checkIfAlreadyDelivered()) {
12465
+ break;
12466
+ }
12467
+ const nextHeight = await retryPromise(
12468
+ () => hyperbridge.latestStateMachineHeight({
12469
+ stateId: parseStateMachineId(sourceStateMachine).stateId,
12470
+ consensusStateId: sourceConsensusStateId
12471
+ }),
12472
+ {
12473
+ maxRetries: 5,
12474
+ backoffMs: 5e3,
12475
+ logMessage: "Failed to fetch latest state machine height (post-source-proof failure)"
12476
+ }
12477
+ );
12478
+ if (nextHeight <= failedHeight) {
12479
+ await sleep(1e4);
12480
+ continue;
12481
+ }
12482
+ sourceHeight = nextHeight;
12483
+ }
12484
+ if (await checkIfAlreadyDelivered()) {
12485
+ break;
12486
+ }
12459
12487
  }
12460
- });
12461
- await this.submitAndConfirmReceipt(hyperbridge, commitment, getRequestMessage);
12488
+ }
12489
+ if (proof) {
12490
+ const sourceIProof = {
12491
+ height: sourceHeight,
12492
+ stateMachine: sourceStateMachine,
12493
+ consensusStateId: sourceConsensusStateId,
12494
+ proof
12495
+ };
12496
+ yield { status: "SOURCE_PROOF_RECEIVED", data: sourceIProof };
12497
+ const getRequestMessage = {
12498
+ kind: "GetRequest",
12499
+ requests: [getRequest],
12500
+ source: sourceIProof,
12501
+ response: destIProof,
12502
+ signer: pad("0x")
12503
+ };
12504
+ await waitForChallengePeriod(hyperbridge, {
12505
+ height: sourceHeight,
12506
+ id: {
12507
+ stateId: parseStateMachineId(sourceStateMachine).stateId,
12508
+ consensusStateId: sourceConsensusStateId
12509
+ }
12510
+ });
12511
+ await this.submitAndConfirmReceipt(hyperbridge, commitment, getRequestMessage);
12512
+ }
12462
12513
  }
12463
12514
  yield statusUpdate;
12464
12515
  }