@hyperbridge/sdk 1.1.12 → 1.2.2

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.
@@ -3,6 +3,7 @@ import { GraphQLClient } from 'graphql-request';
3
3
  import { Hex, Log, PublicClient } from 'viem';
4
4
  import { ApiPromise } from '@polkadot/api';
5
5
  import { SignerOptions } from '@polkadot/api/types';
6
+ import { Chain } from 'viem/chains';
6
7
 
7
8
  type HexString = `0x${string}`;
8
9
  interface IConfig {
@@ -859,10 +860,6 @@ interface HostParams {
859
860
  */
860
861
  hyperbridge: HexString;
861
862
  }
862
- declare enum EvmLanguage {
863
- Solidity = 0,
864
- Vyper = 1
865
- }
866
863
  interface OrderStatusMetadata {
867
864
  status: OrderStatus;
868
865
  chain: string;
@@ -942,11 +939,80 @@ interface OrderResponse {
942
939
  }>;
943
940
  };
944
941
  }
942
+ interface TokenPrice {
943
+ symbol: string;
944
+ address?: string;
945
+ currency: string;
946
+ price: string;
947
+ lastUpdatedAt: bigint;
948
+ }
949
+ interface TokenPricesResponse {
950
+ tokenPrices: {
951
+ nodes: Array<{
952
+ id: string;
953
+ symbol: string;
954
+ address: string;
955
+ currency: string;
956
+ price: string;
957
+ lastUpdatedAt: bigint;
958
+ }>;
959
+ };
960
+ }
961
+ interface TokenRegistry {
962
+ id: string;
963
+ name: string;
964
+ symbol: string;
965
+ address?: string;
966
+ updateFrequencySeconds: number;
967
+ lastUpdatedAt: bigint;
968
+ createdAt: Date;
969
+ }
970
+ interface TokenRegistryResponse {
971
+ tokenRegistries: {
972
+ nodes: Array<{
973
+ id: string;
974
+ name: string;
975
+ symbol: string;
976
+ address: string;
977
+ updateFrequencySeconds: number;
978
+ lastUpdatedAt: bigint;
979
+ createdAt: string;
980
+ }>;
981
+ };
982
+ }
945
983
  declare class AbortSignalInternal extends Error {
946
984
  constructor(message: string);
947
985
  static isError(error: unknown): error is AbortSignalInternal;
948
986
  }
949
987
 
988
+ declare class ChainConfigService {
989
+ private rpcUrls;
990
+ constructor(env?: NodeJS.ProcessEnv);
991
+ getChainConfig(chain: string): ChainConfig;
992
+ getIntentGatewayAddress(chain: string): `0x${string}`;
993
+ getHostAddress(chain: string): `0x${string}`;
994
+ getWrappedNativeAssetWithDecimals(chain: string): {
995
+ asset: HexString;
996
+ decimals: number;
997
+ };
998
+ getDaiAsset(chain: string): HexString;
999
+ getUsdtAsset(chain: string): HexString;
1000
+ getUsdcAsset(chain: string): HexString;
1001
+ getChainId(chain: string): number;
1002
+ getConsensusStateId(chain: string): HexString;
1003
+ getHyperbridgeChainId(): number;
1004
+ getRpcUrl(chain: string): string;
1005
+ getUniswapRouterV2Address(chain: string): HexString;
1006
+ getUniswapV2FactoryAddress(chain: string): HexString;
1007
+ getBatchExecutorAddress(chain: string): HexString;
1008
+ getUniversalRouterAddress(chain: string): HexString;
1009
+ getUniswapV3RouterAddress(chain: string): HexString;
1010
+ getUniswapV3FactoryAddress(chain: string): HexString;
1011
+ getUniswapV3QuoterAddress(chain: string): HexString;
1012
+ getUniswapV4PoolManagerAddress(chain: string): HexString;
1013
+ getUniswapV4QuoterAddress(chain: string): HexString;
1014
+ }
1015
+
950
1016
  /**
951
1017
  * The default address used as fallback when no address is provided.
952
1018
  * This represents the zero address in EVM chains.
@@ -975,7 +1041,11 @@ interface EvmChainParams {
975
1041
  declare class EvmChain implements IChain {
976
1042
  private readonly params;
977
1043
  private publicClient;
1044
+ private chainConfigService;
978
1045
  constructor(params: EvmChainParams);
1046
+ get client(): PublicClient;
1047
+ get host(): HexString;
1048
+ get config(): ChainConfigService;
979
1049
  /**
980
1050
  * Derives the key for the request receipt.
981
1051
  * @param {HexString} commitment - The commitment to derive the key from.
@@ -1016,7 +1086,7 @@ declare class EvmChain implements IChain {
1016
1086
  latestStateMachineHeight(stateMachineId: StateMachineIdParams): Promise<bigint>;
1017
1087
  /**
1018
1088
  * Get the state machine update time for a given state machine height.
1019
- * @param {StateMachineHeight} stateMachineheight - The state machine height.
1089
+ * @param {StateMachineHeight} stateMachineHeight - The state machine height.
1020
1090
  * @returns {Promise<bigint>} The statemachine update time in seconds.
1021
1091
  */
1022
1092
  stateMachineUpdateTime(stateMachineHeight: StateMachineHeight): Promise<bigint>;
@@ -1032,6 +1102,43 @@ declare class EvmChain implements IChain {
1032
1102
  * @returns {HexString} The encoded calldata.
1033
1103
  */
1034
1104
  encode(message: IIsmpMessage): HexString;
1105
+ /**
1106
+ * Calculates the fee required to send a post request to the destination chain.
1107
+ * The fee is calculated based on the per-byte fee for the destination chain
1108
+ * multiplied by the size of the request body.
1109
+ *
1110
+ * @param request - The post request to calculate the fee for
1111
+ * @returns The total fee in wei required to send the post request
1112
+ */
1113
+ quote(request: IPostRequest): Promise<bigint>;
1114
+ /**
1115
+ * Estimates the gas required for a post request execution on this chain.
1116
+ * This function generates mock proofs for the post request, creates a state override
1117
+ * with the necessary overlay root, and estimates the gas cost for executing the
1118
+ * handlePostRequests transaction on the handler contract.
1119
+ *
1120
+ * @param request - The post request to estimate gas for
1121
+ * @param paraId - The ID of the parachain (Hyperbridge) that will process the request
1122
+ * @returns The estimated gas amount in gas units
1123
+ */
1124
+ estimateGas(request: IPostRequest): Promise<bigint>;
1125
+ /**
1126
+ * Gets the fee token address and decimals for the chain.
1127
+ * This function gets the fee token address and decimals for the chain.
1128
+ *
1129
+ * @returns The fee token address and decimals
1130
+ */
1131
+ getFeeTokenWithDecimals(): Promise<{
1132
+ address: HexString;
1133
+ decimals: number;
1134
+ }>;
1135
+ /**
1136
+ * Gets the nonce of the host.
1137
+ * This function gets the nonce of the host.
1138
+ *
1139
+ * @returns The nonce of the host
1140
+ */
1141
+ getHostNonce(): Promise<bigint>;
1035
1142
  }
1036
1143
  /**
1037
1144
  * Slot for storing request commitments.
@@ -1158,15 +1265,69 @@ declare function estimateGasForPost(params: {
1158
1265
  */
1159
1266
  declare function constructRedeemEscrowRequestBody(order: Order, beneficiary: HexString): HexString;
1160
1267
  /**
1161
- * Calculates the balance mapping location for a given slot and holder address.
1162
- * This function handles the different encoding formats used by Solidity and Vyper.
1268
+ * Fetches the USD price of a token from CoinGecko with Defillama fallback
1269
+ * @param identifier - The ticker symbol of the token (e.g., "BTC", "ETH", "USDC") or contract address
1270
+ * @note This function will be replaced by internal price indexer
1271
+ * @returns The USD price of the token as a number (preserves decimals)
1272
+ */
1273
+ declare function fetchTokenUsdPrice(identifier: string): Promise<number>;
1274
+ /**
1275
+ * ERC20 method signatures used for storage slot detection
1276
+ */
1277
+ declare enum ERC20Method {
1278
+ /** ERC20 balanceOf(address) method signature */
1279
+ BALANCE_OF = "0x70a08231",
1280
+ /** ERC20 allowance(address,address) method signature */
1281
+ ALLOWANCE = "0xdd62ed3e"
1282
+ }
1283
+ /**
1284
+ * Retrieves the storage slot for a contract call using debug_traceCall
1285
+ *
1286
+ * This function uses the Ethereum debug API to trace contract execution and identify
1287
+ * the storage slot accessed during the call. It's commonly used for ERC20 token state
1288
+ * mappings like balanceOf and allowance, but can work with any contract call that
1289
+ * performs SLOAD operations.
1290
+ *
1291
+ * @param client - The viem PublicClient instance connected to an RPC node with debug API enabled
1292
+ * @param tokenAddress - The address of the contract to trace
1293
+ * @param data - The full encoded function call data (method signature + encoded parameters)
1294
+ * @returns The storage slot as a hex string
1295
+ * @throws Error if the storage slot cannot be found or if debug API is not available
1296
+ *
1297
+ * @example
1298
+ * ```ts
1299
+ * import { ERC20Method, bytes20ToBytes32 } from '@hyperbridge/sdk'
1163
1300
  *
1164
- * @param slot - The slot number to calculate the mapping location for.
1165
- * @param holder - The address of the holder to calculate the mapping location for.
1166
- * @param language - The language of the contract.
1167
- * @returns The balance mapping location as a HexString.
1301
+ * // Get balance storage slot for ERC20
1302
+ * const balanceData = ERC20Method.BALANCE_OF + bytes20ToBytes32(userAddress).slice(2)
1303
+ * const balanceSlot = await getStorageSlot(
1304
+ * client,
1305
+ * tokenAddress,
1306
+ * balanceData as HexString
1307
+ * )
1308
+ *
1309
+ * // Get allowance storage slot for ERC20
1310
+ * const allowanceData = ERC20Method.ALLOWANCE +
1311
+ * bytes20ToBytes32(ownerAddress).slice(2) +
1312
+ * bytes20ToBytes32(spenderAddress).slice(2)
1313
+ * const allowanceSlot = await getStorageSlot(
1314
+ * client,
1315
+ * tokenAddress,
1316
+ * allowanceData as HexString
1317
+ * )
1318
+ * ```
1319
+ */
1320
+ declare function getStorageSlot(client: PublicClient, contractAddress: HexString, data: HexString): Promise<string>;
1321
+ /**
1322
+ * Adjusts fee amounts between different decimal precisions.
1323
+ * Handles scaling up or down based on the decimal difference.
1324
+ *
1325
+ * @param feeInFeeToken - The fee amount to adjust
1326
+ * @param fromDecimals - The current decimal precision
1327
+ * @param toDecimals - The target decimal precision
1328
+ * @returns The adjusted fee amount with the target decimal precision
1168
1329
  */
1169
- declare function calculateBalanceMappingLocation(slot: bigint, holder: string, language: EvmLanguage): HexString;
1330
+ declare function adjustFeeDecimals(feeInFeeToken: bigint, fromDecimals: number, toDecimals: number): bigint;
1170
1331
 
1171
1332
  interface SubstrateChainParams {
1172
1333
  ws: string;
@@ -1794,6 +1955,93 @@ declare function queryGetRequest(params: {
1794
1955
  queryClient: IndexerQueryClient;
1795
1956
  }): Promise<GetRequestWithStatus | undefined>;
1796
1957
 
1958
+ /**
1959
+ * IntentGateway handles cross-chain intent operations between EVM chains.
1960
+ * It provides functionality for estimating fill orders, finding optimal swap protocols,
1961
+ * and checking order statuses across different chains.
1962
+ */
1963
+ declare class IntentGateway {
1964
+ readonly source: EvmChain;
1965
+ readonly dest: EvmChain;
1966
+ /**
1967
+ * Creates a new IntentGateway instance for cross-chain operations.
1968
+ * @param source - The source EVM chain
1969
+ * @param dest - The destination EVM chain
1970
+ */
1971
+ constructor(source: EvmChain, dest: EvmChain);
1972
+ /**
1973
+ * Estimates the total cost required to fill an order, including gas fees, relayer fees,
1974
+ * protocol fees, and swap operations.
1975
+ *
1976
+ * @param order - The order to estimate fill costs for
1977
+ * @returns The estimated total cost in the source chain's fee token
1978
+ */
1979
+ estimateFillOrder(order: Order): Promise<bigint>;
1980
+ /**
1981
+ * Finds the best Uniswap protocol (V2 or V3) for swapping tokens given a desired output amount.
1982
+ * Compares liquidity and pricing across different protocols and fee tiers.
1983
+ *
1984
+ * @param chain - The chain identifier where the swap will occur
1985
+ * @param tokenIn - The address of the input token
1986
+ * @param tokenOut - The address of the output token
1987
+ * @param amountOut - The desired output amount
1988
+ * @returns Object containing the best protocol, required input amount, and fee tier (for V3)
1989
+ */
1990
+ findBestProtocolWithAmountOut(chain: string, tokenIn: HexString, tokenOut: HexString, amountOut: bigint): Promise<{
1991
+ protocol: "v2" | "v3" | "v4" | null;
1992
+ amountIn: bigint;
1993
+ fee?: number;
1994
+ }>;
1995
+ /**
1996
+ * Finds the best Uniswap protocol (V2 or V3) for swapping tokens given an input amount.
1997
+ * Compares liquidity and pricing across different protocols and fee tiers.
1998
+ *
1999
+ * @param chain - The chain identifier where the swap will occur
2000
+ * @param tokenIn - The address of the input token
2001
+ * @param tokenOut - The address of the output token
2002
+ * @param amountIn - The input amount to swap
2003
+ * @returns Object containing the best protocol, expected output amount, and fee tier (for V3)
2004
+ */
2005
+ findBestProtocolWithAmountIn(chain: string, tokenIn: HexString, tokenOut: HexString, amountIn: bigint): Promise<{
2006
+ protocol: "v2" | "v3" | "v4" | null;
2007
+ amountOut: bigint;
2008
+ fee?: number;
2009
+ }>;
2010
+ /**
2011
+ * Converts gas costs to the equivalent amount in the fee token (DAI).
2012
+ * Uses USD pricing to convert between native token gas costs and fee token amounts.
2013
+ *
2014
+ * @param gasEstimate - The estimated gas units
2015
+ * @param publicClient - The client for the chain to get gas prices
2016
+ * @param targetDecimals - The decimal places of the target fee token
2017
+ * @returns The gas cost converted to fee token amount
2018
+ * @private
2019
+ */
2020
+ private convertGasToFeeToken;
2021
+ /**
2022
+ * Checks if an order has been filled by verifying the commitment status on-chain.
2023
+ * Reads the storage slot corresponding to the order's commitment hash.
2024
+ *
2025
+ * @param order - The order to check
2026
+ * @returns True if the order has been filled, false otherwise
2027
+ */
2028
+ isOrderFilled(order: Order): Promise<boolean>;
2029
+ /**
2030
+ * Returns the tick spacing for a given fee tier in Uniswap V4
2031
+ * @param fee - The fee tier in basis points
2032
+ * @returns The tick spacing value
2033
+ */
2034
+ private getTickSpacing;
2035
+ /**
2036
+ * Returns true if candidate <= reference * (1 + thresholdBps/10000)
2037
+ * @param candidate - The candidate amount to compare
2038
+ * @param reference - The reference amount
2039
+ * @param thresholdBps - The threshold in basis points
2040
+ * @returns True if candidate is within threshold of reference
2041
+ */
2042
+ private isWithinThreshold;
2043
+ }
2044
+
1797
2045
  type HyperbridgeTxEvents = {
1798
2046
  kind: "Ready";
1799
2047
  transaction_hash: HexString;
@@ -1949,4 +2197,78 @@ declare function teleport(teleport_param: {
1949
2197
  options: Partial<SignerOptions>;
1950
2198
  }): Promise<ReadableStream<HyperbridgeTxEvents>>;
1951
2199
 
1952
- export { ADDRESS_ZERO, AbortSignalInternal, type AllStatusKey, type AssetTeleported, type AssetTeleportedResponse, type BlockMetadata, type CancelOptions, type ChainConfig, type ClientConfig, DEFAULT_ADDRESS, DUMMY_PRIVATE_KEY, type DecodedOrderPlacedLog, type DispatchGet, type DispatchPost, EvmChain, type EvmChainParams, EvmLanguage, 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, 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 XcmGatewayParams, __test, bytes20ToBytes32, bytes32ToBytes20, calculateBalanceMappingLocation, constructRedeemEscrowRequestBody, convertStateMachineIdToEnum, createQueryClient, encodeISMPMessage, estimateGasForPost, generateRootWithProof, getChain, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, hexToString, orderCommitment, postRequestCommitment, queryGetRequest, queryPostRequest, teleport, teleportDot };
2200
+ declare enum Chains {
2201
+ BSC_CHAPEL = "EVM-97",
2202
+ GNOSIS_CHIADO = "EVM-10200",
2203
+ HYPERBRIDGE_GARGANTUA = "KUSAMA-4009",
2204
+ SEPOLIA = "EVM-11155111",
2205
+ MAINNET = "EVM-1",
2206
+ BSC_MAINNET = "EVM-56"
2207
+ }
2208
+ type AddressMap = {
2209
+ [key: string]: {
2210
+ [K in Chains]?: `0x${string}`;
2211
+ };
2212
+ };
2213
+ type RpcMap = Record<Chains, string>;
2214
+ declare const chainIds: {
2215
+ readonly "EVM-97": 97;
2216
+ readonly "EVM-10200": 10200;
2217
+ readonly "KUSAMA-4009": 4009;
2218
+ readonly "EVM-11155111": 11155111;
2219
+ readonly "EVM-1": 1;
2220
+ readonly "EVM-56": 56;
2221
+ };
2222
+ type ChainId = typeof chainIds;
2223
+ declare const viemChains: Record<string, Chain>;
2224
+ declare const WrappedNativeDecimals: {
2225
+ "EVM-97": number;
2226
+ "EVM-10200": number;
2227
+ "EVM-11155111": number;
2228
+ "EVM-1": number;
2229
+ "EVM-56": number;
2230
+ };
2231
+ declare const assets: {
2232
+ "EVM-97": {
2233
+ WETH: string;
2234
+ DAI: string;
2235
+ USDC: string;
2236
+ USDT: string;
2237
+ };
2238
+ "EVM-10200": {
2239
+ WETH: string;
2240
+ DAI: string;
2241
+ USDC: string;
2242
+ USDT: string;
2243
+ };
2244
+ "EVM-11155111": {
2245
+ WETH: string;
2246
+ USDC: string;
2247
+ USDT: string;
2248
+ DAI: string;
2249
+ };
2250
+ "EVM-1": {
2251
+ WETH: string;
2252
+ DAI: string;
2253
+ USDC: string;
2254
+ USDT: string;
2255
+ };
2256
+ "EVM-56": {
2257
+ WETH: string;
2258
+ DAI: string;
2259
+ USDC: string;
2260
+ USDT: string;
2261
+ };
2262
+ };
2263
+ declare const addresses: AddressMap;
2264
+ declare const createRpcUrls: (env: NodeJS.ProcessEnv) => RpcMap;
2265
+ declare const consensusStateIds: {
2266
+ "EVM-97": string;
2267
+ "EVM-10200": string;
2268
+ "KUSAMA-4009": string;
2269
+ "EVM-11155111": string;
2270
+ "EVM-1": string;
2271
+ "EVM-56": string;
2272
+ };
2273
+
2274
+ export { ADDRESS_ZERO, AbortSignalInternal, type AllStatusKey, type AssetTeleported, type AssetTeleportedResponse, type BlockMetadata, type CancelOptions, type ChainConfig, ChainConfigService, type ChainId, Chains, type ClientConfig, DEFAULT_ADDRESS, DUMMY_PRIVATE_KEY, type DecodedOrderPlacedLog, type DispatchGet, type DispatchPost, ERC20Method, 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, consensusStateIds, constructRedeemEscrowRequestBody, convertStateMachineIdToEnum, createQueryClient, createRpcUrls, encodeISMPMessage, estimateGasForPost, fetchTokenUsdPrice, generateRootWithProof, getChain, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, hexToString, orderCommitment, postRequestCommitment, queryGetRequest, queryPostRequest, teleport, teleportDot, viemChains };