@hyperbridge/sdk 2.0.0 → 2.0.1

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.
@@ -1,5 +1,5 @@
1
1
  import { createConsola, LogLevels } from 'consola';
2
- import { defineChain, keccak256, toHex, createPublicClient, http, hexToBytes, bytesToHex, encodeFunctionData, erc20Abi, bytesToBigInt, pad, toBytes, numberToBytes, getAddress, encodePacked, encodeAbiParameters, maxUint256, parseAbiParameters, parseAbiItem, concat, decodeFunctionData, decodeAbiParameters, isHex, hexToString as hexToString$1, parseEventLogs, parseUnits, concatHex, formatUnits } from 'viem';
2
+ import { defineChain, keccak256, toHex, createPublicClient, http, hexToBytes, bytesToHex, encodeFunctionData, erc20Abi, bytesToBigInt, pad, toBytes, numberToBytes, getAddress, encodePacked, isHex, encodeAbiParameters, maxUint256, parseAbiParameters, parseAbiItem, concat, decodeFunctionData, decodeAbiParameters, hexToString as hexToString$1, parseEventLogs, parseUnits, concatHex, formatUnits } from 'viem';
3
3
  import { baseSepolia, optimismSepolia, arbitrumSepolia, soneium, gnosis, optimism, polygonAmoy, unichain, polygon, base, arbitrum, bsc, mainnet, sepolia, gnosisChiado, bscTestnet, tron } from 'viem/chains';
4
4
  import { TronWeb } from 'tronweb';
5
5
  import { flatten, zip, capitalize, maxBy, isNil } from 'lodash-es';
@@ -7894,15 +7894,24 @@ function postRequestCommitment(post) {
7894
7894
  };
7895
7895
  }
7896
7896
  function bytes32ToBytes20(bytes32Address) {
7897
+ if (bytes32Address.length === 42) {
7898
+ return bytes32Address;
7899
+ }
7897
7900
  if (bytes32Address === ADDRESS_ZERO2) {
7898
7901
  return ADDRESS_ZERO2;
7899
7902
  }
7903
+ if (bytes32Address.length !== 66) {
7904
+ throw new Error(`Expected a 20-byte or 32-byte hex value, got ${bytes32Address.length} characters`);
7905
+ }
7900
7906
  const bytes = hexToBytes(bytes32Address);
7901
7907
  const addressBytes = bytes.slice(12);
7902
7908
  return bytesToHex(addressBytes);
7903
7909
  }
7904
7910
  function bytes20ToBytes32(bytes20Address) {
7905
7911
  if (bytes20Address.length === 66) return bytes20Address;
7912
+ if (bytes20Address.length !== 42) {
7913
+ throw new Error(`Expected a 20-byte or 32-byte hex value, got ${bytes20Address.length} characters`);
7914
+ }
7906
7915
  return `0x${bytes20Address.slice(2).padStart(64, "0")}`;
7907
7916
  }
7908
7917
  function hexToString(hex) {
@@ -7913,6 +7922,33 @@ function hexToString(hex) {
7913
7922
  }
7914
7923
  return new TextDecoder().decode(bytes);
7915
7924
  }
7925
+ function normalizeStateMachineId(stateMachineId) {
7926
+ return isHex(stateMachineId) ? hexToString(stateMachineId) : stateMachineId;
7927
+ }
7928
+ function normalizeEvmChainId(chainId) {
7929
+ if (typeof chainId === "number") {
7930
+ if (!Number.isInteger(chainId) || chainId <= 0) {
7931
+ throw new Error(`Invalid EVM chain ID: ${chainId}. Expected a positive integer.`);
7932
+ }
7933
+ return { chainId, stateMachineId: `EVM-${chainId}` };
7934
+ }
7935
+ const stateMachineId = normalizeStateMachineId(chainId);
7936
+ const { stateId } = parseStateMachineId(stateMachineId);
7937
+ if (!stateId.Evm) {
7938
+ throw new Error(`Unsupported chainId format: ${chainId}. Expected a number or EVM state machine ID.`);
7939
+ }
7940
+ return { chainId: stateId.Evm, stateMachineId };
7941
+ }
7942
+ function encodeStateMachineId(stateMachineId) {
7943
+ return isHex(stateMachineId) ? stateMachineId : toHex(stateMachineId);
7944
+ }
7945
+ function normalizeAddressForEvmBytes32(address) {
7946
+ if (address.length === 66) return address;
7947
+ return bytes20ToBytes32(address);
7948
+ }
7949
+ function normalizeAddressForStateMachine(address, stateMachineId) {
7950
+ return isEvmChain(normalizeStateMachineId(stateMachineId)) ? normalizeAddressForEvmBytes32(address) : address;
7951
+ }
7916
7952
  var DEFAULT_LOGGER = createConsola({
7917
7953
  level: LogLevels.silent
7918
7954
  });
@@ -8059,7 +8095,10 @@ function encodeWithdrawalRequest(order, beneficiary) {
8059
8095
  {
8060
8096
  commitment: order.id,
8061
8097
  beneficiary: bytes20ToBytes32(beneficiary),
8062
- tokens: order.inputs
8098
+ tokens: order.inputs.map((token) => ({
8099
+ ...token,
8100
+ token: normalizeAddressForEvmBytes32(token.token)
8101
+ }))
8063
8102
  }
8064
8103
  ]
8065
8104
  );
@@ -11432,13 +11471,200 @@ var PERMIT2_ABI = [
11432
11471
  type: "function"
11433
11472
  }
11434
11473
  ];
11474
+ var UniswapQuoteEngine = class {
11475
+ constructor(adapter, chainConfigService = new ChainConfigService()) {
11476
+ this.adapter = adapter;
11477
+ this.chainConfigService = chainConfigService;
11478
+ }
11479
+ adapter;
11480
+ chainConfigService;
11481
+ async quote(params, options = {}) {
11482
+ this.validateQuoteParams(params);
11483
+ const protocols = this.getQuoteProtocols(params.protocols);
11484
+ const { chainId, stateMachineId: evmChainID } = normalizeEvmChainId(params.chainId);
11485
+ const client = options.client ?? this.resolveClient(params.chainId);
11486
+ const quotes = [];
11487
+ for (const protocol of protocols) {
11488
+ const quote = params.tradeType === "EXACT_INPUT" ? await this.quoteExactInputForProtocol(params, client, protocol, chainId, evmChainID) : await this.quoteExactOutputForProtocol(params, client, protocol, chainId, evmChainID);
11489
+ if (quote) quotes.push(quote);
11490
+ }
11491
+ return { bestQuote: this.selectBestQuote(quotes, params.tradeType), quotes };
11492
+ }
11493
+ resolveClient(chainId) {
11494
+ const { stateMachineId: evmChainID } = normalizeEvmChainId(chainId);
11495
+ const rpcUrl = this.chainConfigService.getRpcUrl(evmChainID);
11496
+ if (!rpcUrl) {
11497
+ throw new Error(`No RPC URL configured for chain ${evmChainID}`);
11498
+ }
11499
+ return createPublicClient({ transport: http(rpcUrl) });
11500
+ }
11501
+ getQuoteProtocols(protocols) {
11502
+ return protocols?.length ? protocols : ["v2", "v3", "v4"];
11503
+ }
11504
+ validateQuoteParams(params) {
11505
+ if (params.tradeType === "EXACT_INPUT" && params.amountIn === void 0) {
11506
+ throw new Error("amountIn is required for EXACT_INPUT quotes");
11507
+ }
11508
+ if (params.tradeType === "EXACT_OUTPUT" && params.amountOut === void 0) {
11509
+ throw new Error("amountOut is required for EXACT_OUTPUT quotes");
11510
+ }
11511
+ if (params.slippageBps !== void 0 && (params.slippageBps < 0 || params.slippageBps > 1e4)) {
11512
+ throw new Error("slippageBps must be between 0 and 10000");
11513
+ }
11514
+ }
11515
+ applySlippageToAmountOut(amountOut, slippageBps) {
11516
+ return amountOut * BigInt(1e4 - slippageBps) / 10000n;
11517
+ }
11518
+ applySlippageToAmountIn(amountIn, slippageBps) {
11519
+ const numerator = amountIn * BigInt(1e4 + slippageBps);
11520
+ return (numerator + 9999n) / 10000n;
11521
+ }
11522
+ selectBestQuote(quotes, tradeType) {
11523
+ if (quotes.length === 0) return null;
11524
+ if (tradeType === "EXACT_INPUT") {
11525
+ return quotes.reduce((best, current) => {
11526
+ return current.amountOut > best.amountOut ? current : best;
11527
+ });
11528
+ }
11529
+ return quotes.reduce((best, current) => {
11530
+ return current.amountIn < best.amountIn ? current : best;
11531
+ });
11532
+ }
11533
+ createExactInputTransactions(protocol, params, minAmountOut, fee, evmChainID) {
11534
+ const amountIn = params.amountIn;
11535
+ const recipient = params.recipient;
11536
+ const path = [params.tokenIn.address, params.tokenOut.address];
11537
+ switch (protocol) {
11538
+ case "v2":
11539
+ return this.adapter.createV2SwapCalldataExactIn(path, amountIn, minAmountOut, recipient, evmChainID);
11540
+ case "v3":
11541
+ return this.adapter.createV3SwapCalldataExactIn(
11542
+ path,
11543
+ amountIn,
11544
+ minAmountOut,
11545
+ [fee],
11546
+ recipient,
11547
+ evmChainID
11548
+ );
11549
+ case "v4":
11550
+ return this.adapter.createV4SwapCalldataExactIn(
11551
+ params.tokenIn.address,
11552
+ params.tokenOut.address,
11553
+ amountIn,
11554
+ minAmountOut,
11555
+ fee,
11556
+ evmChainID
11557
+ );
11558
+ }
11559
+ }
11560
+ createExactOutputTransactions(protocol, params, maxAmountIn, fee, evmChainID) {
11561
+ const amountOut = params.amountOut;
11562
+ const recipient = params.recipient;
11563
+ const path = [params.tokenIn.address, params.tokenOut.address];
11564
+ switch (protocol) {
11565
+ case "v2":
11566
+ return this.adapter.createV2SwapCalldataExactOut(path, amountOut, maxAmountIn, recipient, evmChainID);
11567
+ case "v3":
11568
+ return this.adapter.createV3SwapCalldataExactOut(
11569
+ path,
11570
+ amountOut,
11571
+ maxAmountIn,
11572
+ [fee],
11573
+ recipient,
11574
+ evmChainID
11575
+ );
11576
+ case "v4":
11577
+ return this.adapter.createV4SwapCalldataExactOut(
11578
+ params.tokenIn.address,
11579
+ params.tokenOut.address,
11580
+ amountOut,
11581
+ maxAmountIn,
11582
+ fee,
11583
+ evmChainID
11584
+ );
11585
+ }
11586
+ }
11587
+ async quoteExactInputForProtocol(params, client, protocol, chainId, evmChainID) {
11588
+ const generateCalldata = !!params.recipient;
11589
+ const result = await this.adapter.findBestProtocolWithAmountIn(
11590
+ client,
11591
+ params.tokenIn.address,
11592
+ params.tokenOut.address,
11593
+ params.amountIn,
11594
+ evmChainID,
11595
+ {
11596
+ selectedProtocol: protocol,
11597
+ generateCalldata,
11598
+ recipient: params.recipient
11599
+ }
11600
+ );
11601
+ if (result.protocol === null || result.amountOut === 0n) return null;
11602
+ let transactions = result.transactions;
11603
+ const slippageBps = params.slippageBps ?? 0;
11604
+ if (generateCalldata && slippageBps > 0) {
11605
+ const minAmountOut = this.applySlippageToAmountOut(result.amountOut, slippageBps);
11606
+ transactions = this.createExactInputTransactions(protocol, params, minAmountOut, result.fee, evmChainID);
11607
+ }
11608
+ return {
11609
+ protocol,
11610
+ tradeType: params.tradeType,
11611
+ chainId,
11612
+ tokenIn: params.tokenIn,
11613
+ tokenOut: params.tokenOut,
11614
+ amountIn: params.amountIn,
11615
+ amountOut: result.amountOut,
11616
+ fee: result.fee,
11617
+ route: { tokens: [params.tokenIn.address, params.tokenOut.address] },
11618
+ transactions
11619
+ };
11620
+ }
11621
+ async quoteExactOutputForProtocol(params, client, protocol, chainId, evmChainID) {
11622
+ const generateCalldata = !!params.recipient;
11623
+ const result = await this.adapter.findBestProtocolWithAmountOut(
11624
+ client,
11625
+ params.tokenIn.address,
11626
+ params.tokenOut.address,
11627
+ params.amountOut,
11628
+ evmChainID,
11629
+ {
11630
+ selectedProtocol: protocol,
11631
+ generateCalldata,
11632
+ recipient: params.recipient
11633
+ }
11634
+ );
11635
+ if (result.protocol === null || result.amountIn === maxUint256) return null;
11636
+ let transactions = result.transactions;
11637
+ const slippageBps = params.slippageBps ?? 0;
11638
+ if (generateCalldata && slippageBps > 0) {
11639
+ const maxAmountIn = this.applySlippageToAmountIn(result.amountIn, slippageBps);
11640
+ transactions = this.createExactOutputTransactions(protocol, params, maxAmountIn, result.fee, evmChainID);
11641
+ }
11642
+ return {
11643
+ protocol,
11644
+ tradeType: params.tradeType,
11645
+ chainId,
11646
+ tokenIn: params.tokenIn,
11647
+ tokenOut: params.tokenOut,
11648
+ amountIn: result.amountIn,
11649
+ amountOut: params.amountOut,
11650
+ fee: result.fee,
11651
+ route: { tokens: [params.tokenIn.address, params.tokenOut.address] },
11652
+ transactions
11653
+ };
11654
+ }
11655
+ };
11435
11656
 
11436
11657
  // src/utils/swap.ts
11437
11658
  var COMMON_FEE_TIERS = [100, 500, 2500, 3e3, 1e4];
11438
11659
  var Swap = class {
11439
11660
  chainConfigService;
11661
+ uniswapQuoteEngine;
11440
11662
  constructor() {
11441
11663
  this.chainConfigService = new ChainConfigService();
11664
+ this.uniswapQuoteEngine = new UniswapQuoteEngine(this, this.chainConfigService);
11665
+ }
11666
+ async quoteUniswap(params) {
11667
+ return this.uniswapQuoteEngine.quote(params);
11442
11668
  }
11443
11669
  /**
11444
11670
  * Gets V2 quote for exact output swap.
@@ -12777,6 +13003,9 @@ var Swap = class {
12777
13003
  }
12778
13004
  }
12779
13005
  };
13006
+ async function quoteUniswap(params) {
13007
+ return new Swap().quoteUniswap(params);
13008
+ }
12780
13009
 
12781
13010
  // src/abis/erc7281.ts
12782
13011
  var ABI6 = [
@@ -15281,17 +15510,18 @@ function transformOrderForContract(order) {
15281
15510
  const { id: _id, ...contractOrder } = order;
15282
15511
  return {
15283
15512
  ...contractOrder,
15284
- source: order.source.startsWith("0x") ? order.source : toHex(order.source),
15285
- destination: order.destination.startsWith("0x") ? order.destination : toHex(order.destination),
15286
- inputs: order.inputs.map((t) => ({ ...t, token: bytes20ToBytes32(t.token) })),
15513
+ source: encodeStateMachineId(order.source),
15514
+ destination: encodeStateMachineId(order.destination),
15515
+ user: normalizeAddressForEvmBytes32(order.user),
15516
+ inputs: order.inputs.map((t) => ({ ...t, token: normalizeAddressForEvmBytes32(t.token) })),
15287
15517
  predispatch: {
15288
15518
  ...order.predispatch,
15289
- assets: order.predispatch.assets.map((t) => ({ ...t, token: bytes20ToBytes32(t.token) }))
15519
+ assets: order.predispatch.assets.map((t) => ({ ...t, token: normalizeAddressForEvmBytes32(t.token) }))
15290
15520
  },
15291
15521
  output: {
15292
15522
  ...order.output,
15293
- beneficiary: bytes20ToBytes32(order.output.beneficiary),
15294
- assets: order.output.assets.map((t) => ({ ...t, token: bytes20ToBytes32(t.token) }))
15523
+ beneficiary: normalizeAddressForEvmBytes32(order.output.beneficiary),
15524
+ assets: order.output.assets.map((t) => ({ ...t, token: normalizeAddressForEvmBytes32(t.token) }))
15295
15525
  }
15296
15526
  };
15297
15527
  }
@@ -15421,7 +15651,7 @@ var OrderPlacer = class {
15421
15651
  args: [transformOrderForContract(order), graffiti]
15422
15652
  });
15423
15653
  const intentGatewayAddress = this.ctx.source.configService.getIntentGatewayV2Address(
15424
- hexToString(order.source)
15654
+ normalizeStateMachineId(order.source)
15425
15655
  );
15426
15656
  const signedTransaction = yield {
15427
15657
  to: intentGatewayAddress,
@@ -15511,7 +15741,9 @@ var OrderExecutor = class {
15511
15741
  * UserOperation, pre-bound to the order's destination chain and entry point.
15512
15742
  */
15513
15743
  createUserOpHasher(order) {
15514
- const entryPointAddress = this.ctx.dest.configService.getEntryPointV08Address(hexToString(order.destination));
15744
+ const entryPointAddress = this.ctx.dest.configService.getEntryPointV08Address(
15745
+ normalizeStateMachineId(order.destination)
15746
+ );
15515
15747
  const chainId = BigInt(
15516
15748
  this.ctx.dest.client.chain?.id ?? Number.parseInt(this.ctx.dest.config.stateMachineId.split("-")[1])
15517
15749
  );
@@ -15796,12 +16028,12 @@ var OrderCanceller = class {
15796
16028
  * submitting the cancel transaction.
15797
16029
  *
15798
16030
  * @param order - The order to quote.
15799
- * @param fromDest - If `true`, quotes the destination-initiated path.
16031
+ * @param options - Choose the initiation side. Defaults to source-side cancellation.
15800
16032
  * @returns `{ nativeValue }` — native token amount (wei) to send as `value`;
15801
16033
  * `{ relayerFee }` — relayer incentive denominated in the chain's fee token.
15802
16034
  */
15803
- async quoteCancelOrder(order, fromDest = false) {
15804
- if (fromDest) {
16035
+ async quoteCancelOrder(order, options = {}) {
16036
+ if (options.from === "destination") {
15805
16037
  return this.quoteCancelFromDest(order);
15806
16038
  }
15807
16039
  return this.quoteCancelFromSource(order);
@@ -15818,10 +16050,10 @@ var OrderCanceller = class {
15818
16050
  */
15819
16051
  async quoteCancelFromSource(order) {
15820
16052
  if (order.source === order.destination) return { nativeValue: 0n, relayerFee: 0n };
15821
- const sourceStateMachine = order.source.startsWith("0x") ? hexToString(order.source) : order.source;
16053
+ const sourceStateMachine = normalizeStateMachineId(order.source);
15822
16054
  const height = order.deadline + 1n;
15823
16055
  const destIntentGateway = this.ctx.dest.configService.getIntentGatewayV2Address(
15824
- hexToString(order.destination)
16056
+ normalizeStateMachineId(order.destination)
15825
16057
  );
15826
16058
  const slotHash = await this.ctx.dest.client.readContract({
15827
16059
  abi: ABI7,
@@ -15833,8 +16065,8 @@ var OrderCanceller = class {
15833
16065
  const context = encodeWithdrawalRequest(order, order.user);
15834
16066
  const getRequest = {
15835
16067
  source: sourceStateMachine,
15836
- dest: order.destination.startsWith("0x") ? hexToString(order.destination) : order.destination,
15837
- from: this.ctx.source.configService.getIntentGatewayV2Address(hexToString(order.destination)),
16068
+ dest: normalizeStateMachineId(order.destination),
16069
+ from: this.ctx.source.configService.getIntentGatewayV2Address(normalizeStateMachineId(order.destination)),
15838
16070
  nonce: await this.ctx.source.getHostNonce(),
15839
16071
  height,
15840
16072
  keys: [key],
@@ -15856,13 +16088,13 @@ var OrderCanceller = class {
15856
16088
  * @param order - The order to cancel.
15857
16089
  * @param indexerClient - Indexer client used to stream ISMP request status
15858
16090
  * updates and query state-machine heights.
15859
- * @param fromDest - If `true`, initiates cancellation from the destination chain.
15860
- * Defaults to `false` (source-side cancellation).
16091
+ * @param options - Choose the initiation side. Defaults to source-side cancellation.
15861
16092
  * @yields {@link CancelEvent} objects describing each stage of the
15862
16093
  * cancellation lifecycle.
15863
16094
  */
15864
- async *cancelOrder(order, indexerClient, fromDest = false) {
15865
- if (fromDest) {
16095
+ async *cancelOrder(order, indexerClient, options = {}) {
16096
+ const isSameChain = order.source === order.destination;
16097
+ if (options.from === "destination" && !isSameChain) {
15866
16098
  yield* this.cancelOrderFromDest(order, indexerClient);
15867
16099
  return;
15868
16100
  }
@@ -15895,7 +16127,7 @@ var OrderCanceller = class {
15895
16127
  const orderId = order.id;
15896
16128
  const isSameChain = order.source === order.destination;
15897
16129
  const intentGatewayAddress = this.ctx.source.configService.getIntentGatewayV2Address(
15898
- hexToString(order.source)
16130
+ normalizeStateMachineId(order.source)
15899
16131
  );
15900
16132
  if (isSameChain) {
15901
16133
  const data = encodeFunctionData({
@@ -15926,7 +16158,7 @@ var OrderCanceller = class {
15926
16158
  return;
15927
16159
  }
15928
16160
  const hyperbridge = indexerClient.hyperbridge;
15929
- const sourceStateMachine = hexToString(order.source);
16161
+ const sourceStateMachine = normalizeStateMachineId(order.source);
15930
16162
  const sourceConsensusStateId = this.ctx.source.configService.getConsensusStateId(sourceStateMachine);
15931
16163
  let destIProof = await this.ctx.cancellationStorage.getItem(STORAGE_KEYS.destProof(orderId));
15932
16164
  if (!destIProof) {
@@ -16036,8 +16268,8 @@ var OrderCanceller = class {
16036
16268
  */
16037
16269
  async quoteCancelFromDest(order) {
16038
16270
  if (order.source === order.destination) return { nativeValue: 0n, relayerFee: 0n };
16039
- const destStateMachine = order.destination.startsWith("0x") ? hexToString(order.destination) : order.destination;
16040
- const sourceStateMachine = order.source.startsWith("0x") ? hexToString(order.source) : order.source;
16271
+ const destStateMachine = normalizeStateMachineId(order.destination);
16272
+ const sourceStateMachine = normalizeStateMachineId(order.source);
16041
16273
  const destIntentGateway = this.ctx.dest.configService.getIntentGatewayV2Address(destStateMachine);
16042
16274
  const sourceIntentGateway = this.ctx.source.configService.getIntentGatewayV2Address(sourceStateMachine);
16043
16275
  const relayerFee = await this.estimateRelayerFee(sourceStateMachine, destStateMachine);
@@ -16058,7 +16290,8 @@ var OrderCanceller = class {
16058
16290
  * Async generator that cancels an order by initiating from the destination
16059
16291
  * chain and streaming status updates until the source-chain escrow is refunded.
16060
16292
  *
16061
- * Throws if called with a same-chain order (use source-side cancellation instead).
16293
+ * Same-chain requests are handled by the top-level router and fall back to
16294
+ * the direct source-side cancellation path.
16062
16295
  *
16063
16296
  * **Steps:**
16064
16297
  * 1. Yields `AWAITING_CANCEL_TRANSACTION` so the caller can sign and submit
@@ -16071,15 +16304,11 @@ var OrderCanceller = class {
16071
16304
  * @param order - The cross-chain order to cancel.
16072
16305
  * @param indexerClient - Used to stream POST request status updates.
16073
16306
  * @yields {@link CancelEvent} at each lifecycle stage.
16074
- * @throws If the order is same-chain, or if the cancel transaction does not
16075
- * contain a `PostRequestEvent`.
16307
+ * @throws If the cancel transaction does not contain a `PostRequestEvent`.
16076
16308
  */
16077
16309
  async *cancelOrderFromDest(order, indexerClient) {
16078
16310
  const orderId = order.id;
16079
- if (order.source === order.destination) {
16080
- throw new Error("Cannot cancel same-chain order from destination; use cancelOrder instead");
16081
- }
16082
- const destStateMachine = order.destination.startsWith("0x") ? hexToString(order.destination) : order.destination;
16311
+ const destStateMachine = normalizeStateMachineId(order.destination);
16083
16312
  const intentGatewayAddress = this.ctx.dest.configService.getIntentGatewayV2Address(destStateMachine);
16084
16313
  let commitment = await this.ctx.cancellationStorage.getItem(
16085
16314
  STORAGE_KEYS.postCommitment(orderId)
@@ -16356,7 +16585,7 @@ var BidManager = class {
16356
16585
  throw new Error("No valid bids found");
16357
16586
  }
16358
16587
  const intentGatewayV2Address = this.ctx.dest.configService.getIntentGatewayV2Address(
16359
- hexToString(order.destination)
16588
+ normalizeStateMachineId(order.destination)
16360
16589
  );
16361
16590
  const domainSeparator = CryptoUtils.getDomainSeparator(
16362
16591
  "IntentGateway",
@@ -16415,7 +16644,7 @@ var BidManager = class {
16415
16644
  signature: finalSignature
16416
16645
  };
16417
16646
  const entryPointAddress = this.ctx.dest.configService.getEntryPointV08Address(
16418
- hexToString(order.destination)
16647
+ normalizeStateMachineId(order.destination)
16419
16648
  );
16420
16649
  BigInt(
16421
16650
  this.ctx.dest.client.chain?.id ?? Number.parseInt(this.ctx.dest.config.stateMachineId.split("-")[1])
@@ -18411,7 +18640,10 @@ var GasEstimator = class {
18411
18640
  const fillOptions = {
18412
18641
  relayerFee: crossChainFees.postRequestFee,
18413
18642
  nativeDispatchFee: crossChainFees.protocolFee,
18414
- outputs: order.output.assets
18643
+ outputs: order.output.assets.map((asset) => ({
18644
+ ...asset,
18645
+ token: normalizeAddressForEvmBytes32(asset.token)
18646
+ }))
18415
18647
  };
18416
18648
  const totalNativeValue = totalEthValue + fillOptions.nativeDispatchFee;
18417
18649
  const priorityFeeBumpPercent = params.maxPriorityFeePerGasBumpPercent ?? 8;
@@ -19063,12 +19295,18 @@ var IntentGateway = class _IntentGateway {
19063
19295
  * Delegates to {@link OrderCanceller.quoteCancelOrder}.
19064
19296
  *
19065
19297
  * @param order - The order to quote cancellation for.
19066
- * @param fromDest - If `true`, quotes the destination-initiated cancellation fee.
19298
+ * @param options - Choose the initiation side. Defaults to source-side cancellation.
19067
19299
  * @returns `{ nativeValue }` — native token amount (wei) to send as `value`;
19068
19300
  * `{ relayerFee }` — relayer incentive denominated in the chain's fee token.
19069
19301
  */
19070
- async quoteCancelOrder(order, fromDest = false) {
19071
- return this.orderCanceller.quoteCancelOrder(order, fromDest);
19302
+ async quoteCancelOrder(order, options = {}) {
19303
+ return this.orderCanceller.quoteCancelOrder(order, options);
19304
+ }
19305
+ async quoteCancelOrderFromSource(order) {
19306
+ return this.orderCanceller.quoteCancelOrder(order, { from: "source" });
19307
+ }
19308
+ async quoteCancelOrderFromDest(order) {
19309
+ return this.orderCanceller.quoteCancelOrder(order, { from: "destination" });
19072
19310
  }
19073
19311
  /**
19074
19312
  * Async generator that cancels an order and streams status events until
@@ -19078,12 +19316,17 @@ var IntentGateway = class _IntentGateway {
19078
19316
  *
19079
19317
  * @param order - The order to cancel.
19080
19318
  * @param indexerClient - Indexer client used for ISMP request status streaming.
19081
- * @param fromDest - If `true`, initiates cancellation from the destination chain.
19082
- * Defaults to `false` (source-side cancellation).
19319
+ * @param options - Choose the initiation side. Defaults to source-side cancellation.
19083
19320
  * @yields {@link CancelEvent} objects describing each cancellation stage.
19084
19321
  */
19085
- async *cancelOrder(order, indexerClient, fromDest = false) {
19086
- yield* this.orderCanceller.cancelOrder(order, indexerClient, fromDest);
19322
+ async *cancelOrder(order, indexerClient, options = {}) {
19323
+ yield* this.orderCanceller.cancelOrder(order, indexerClient, options);
19324
+ }
19325
+ async *cancelOrderFromSource(order, indexerClient) {
19326
+ yield* this.orderCanceller.cancelOrder(order, indexerClient, { from: "source" });
19327
+ }
19328
+ async *cancelOrderFromDest(order, indexerClient) {
19329
+ yield* this.orderCanceller.cancelOrder(order, indexerClient, { from: "destination" });
19087
19330
  }
19088
19331
  /**
19089
19332
  * Constructs a signed `PackedUserOperation` for a solver to submit as a bid.
@@ -19264,7 +19507,7 @@ var TokenGateway = class {
19264
19507
  * @returns The TokenGateway contract address
19265
19508
  */
19266
19509
  getTokenGatewayAddress(chain) {
19267
- const chainStr = typeof chain === "string" ? chain : new TextDecoder().decode(chain);
19510
+ const chainStr = normalizeStateMachineId(typeof chain === "string" ? chain : new TextDecoder().decode(chain));
19268
19511
  return this.source.configService.getTokenGatewayAddress(chainStr);
19269
19512
  }
19270
19513
  /**
@@ -19307,10 +19550,13 @@ var TokenGateway = class {
19307
19550
  */
19308
19551
  async quoteNative(params) {
19309
19552
  const dataHex = params.data ? typeof params.data === "string" ? params.data : toHex(params.data) : "0x";
19553
+ const destChainId = normalizeStateMachineId(
19554
+ typeof params.dest === "string" ? params.dest : new TextDecoder().decode(params.dest)
19555
+ );
19556
+ const recipient = normalizeAddressForStateMachine(params.to, destChainId);
19310
19557
  const sourceTokenGatewayAddress = this.getTokenGatewayAddress(this.source.config.stateMachineId);
19311
19558
  const destTokenGatewayAddress = this.getTokenGatewayAddress(params.dest);
19312
19559
  let relayerFee = 0n;
19313
- const destChainId = typeof params.dest === "string" ? params.dest : new TextDecoder().decode(params.dest);
19314
19560
  const isEvmDest = destChainId.startsWith("EVM-") && this.dest instanceof EvmChain;
19315
19561
  if (isEvmDest) {
19316
19562
  const randomHex = "0x" + Array.from({ length: 191 * 2 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
@@ -19337,7 +19583,7 @@ var TokenGateway = class {
19337
19583
  // Use the calculated relayer fee (0 for non-EVM destinations)
19338
19584
  params.assetId,
19339
19585
  params.redeem,
19340
- params.to,
19586
+ recipient,
19341
19587
  dataHex
19342
19588
  ]
19343
19589
  );
@@ -19521,17 +19767,14 @@ async function fetchLocalAssetId(params) {
19521
19767
  }
19522
19768
  async function teleport(teleport_param) {
19523
19769
  const { params, apiPromise, extrinsics = [] } = teleport_param;
19524
- const substrateComplianceAddr = (address, stateMachine) => {
19525
- if (stateMachine.startsWith("EVM-")) return pad(address, { size: 32, dir: "left" });
19526
- return address;
19527
- };
19528
19770
  const assetId = keccakAsU8a(params.symbol);
19529
19771
  const scaleEncodedAssetId = await fetchLocalAssetId({ api: apiPromise, assetId });
19530
19772
  if (scaleEncodedAssetId === null) {
19531
19773
  throw new Error("Unknown asset id provided");
19532
19774
  }
19533
- const destination = convertStateMachineIdToEnum(params.destination);
19534
- const recipient = hexToBytes(substrateComplianceAddr(params.recipient, params.destination));
19775
+ const destinationStateMachine = normalizeStateMachineId(params.destination);
19776
+ const destination = convertStateMachineIdToEnum(destinationStateMachine);
19777
+ const recipient = hexToBytes(normalizeAddressForStateMachine(params.recipient, destinationStateMachine));
19535
19778
  const teleportParams = {
19536
19779
  destination,
19537
19780
  recepient: Array.from(recipient),
@@ -19784,6 +20027,6 @@ async function teleportDot(param_) {
19784
20027
  return stream;
19785
20028
  }
19786
20029
 
19787
- export { ADDRESS_ZERO2 as ADDRESS_ZERO, BundlerMethod, ChainConfigService, Chains, CryptoUtils, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DOMAIN_TYPEHASH, DUMMY_PRIVATE_KEY, ERC20Method, ERC7821_BATCH_MODE, EvmChain, ABI as EvmHostABI, EvmLanguage, HyperClientStatus, IntentGateway, ABI7 as IntentGatewayV2ABI, IntentOrderStatus, IntentsCoprocessor, IsmpClient, MOCK_ADDRESS, ORDER_V2_PARAM_TYPE, OrderStatus, OrderStatusChecker, PACKED_USEROP_TYPEHASH, PLACE_ORDER_SELECTOR, PharosChain, PolkadotHubChain, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, RequestKind, RequestStatus, SELECT_SOLVER_TYPEHASH, STATE_COMMITMENTS_SLOT, SubstrateChain, Swap, TESTNET_CHAINS, TeleportStatus, TimeoutStatus, TokenGateway, TronChain, USE_ETHERSCAN_CHAINS, __test, adjustDecimals, bytes20ToBytes32, bytes32ToBytes20, calculateAllowanceMappingLocation, calculateBalanceMappingLocation, chainConfigs, constructRedeemEscrowRequestBody, constructRefundEscrowRequestBody, convertCodecToIGetRequest, convertCodecToIProof, convertIGetRequestToCodec, convertIProofToCodec, convertStateIdToStateMachineId, convertStateMachineEnumToString, convertStateMachineIdToEnum, createEvmChain, createQueryClient, decodeUserOpScale, encodeERC7821ExecuteBatch, encodeISMPMessage, encodeUserOpScale, encodeWithdrawalRequest, estimateGasForPost, fetchPrice, fetchSourceProof, generateRootWithProof, getChainId, getConfigByStateMachineId, getContractCallInput, getGasPriceFromEtherscan, getOrFetchStorageSlot, getOrderPlacedFromTx, getPostRequestEventFromTx, getPostResponseEventFromTx, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, getViemChain, hexToString, hyperbridgeAddress, maxBigInt, orderCommitment, parseStateMachineId, pharosAtlantic, pharosMainnet, polkadotAssetHubPaseo, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, requestCommitmentKey, responseCommitmentKey, retryPromise, teleport, teleportDot, transformOrderForContract, tronChainIds, tronNile };
20030
+ export { ADDRESS_ZERO2 as ADDRESS_ZERO, BundlerMethod, ChainConfigService, Chains, CryptoUtils, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DOMAIN_TYPEHASH, DUMMY_PRIVATE_KEY, ERC20Method, ERC7821_BATCH_MODE, EvmChain, ABI as EvmHostABI, EvmLanguage, HyperClientStatus, IntentGateway, ABI7 as IntentGatewayV2ABI, IntentOrderStatus, IntentsCoprocessor, IsmpClient, MOCK_ADDRESS, ORDER_V2_PARAM_TYPE, OrderStatus, OrderStatusChecker, PACKED_USEROP_TYPEHASH, PLACE_ORDER_SELECTOR, PharosChain, PolkadotHubChain, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, RequestKind, RequestStatus, SELECT_SOLVER_TYPEHASH, STATE_COMMITMENTS_SLOT, SubstrateChain, Swap, TESTNET_CHAINS, TeleportStatus, TimeoutStatus, TokenGateway, TronChain, USE_ETHERSCAN_CHAINS, __test, adjustDecimals, bytes20ToBytes32, bytes32ToBytes20, calculateAllowanceMappingLocation, calculateBalanceMappingLocation, chainConfigs, constructRedeemEscrowRequestBody, constructRefundEscrowRequestBody, convertCodecToIGetRequest, convertCodecToIProof, convertIGetRequestToCodec, convertIProofToCodec, convertStateIdToStateMachineId, convertStateMachineEnumToString, convertStateMachineIdToEnum, createEvmChain, createQueryClient, decodeUserOpScale, encodeERC7821ExecuteBatch, encodeISMPMessage, encodeStateMachineId, encodeUserOpScale, encodeWithdrawalRequest, estimateGasForPost, fetchPrice, fetchSourceProof, generateRootWithProof, getChainId, getConfigByStateMachineId, getContractCallInput, getGasPriceFromEtherscan, getOrFetchStorageSlot, getOrderPlacedFromTx, getPostRequestEventFromTx, getPostResponseEventFromTx, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, getViemChain, hexToString, hyperbridgeAddress, maxBigInt, normalizeAddressForEvmBytes32, normalizeAddressForStateMachine, normalizeEvmChainId, normalizeStateMachineId, orderCommitment, parseStateMachineId, pharosAtlantic, pharosMainnet, polkadotAssetHubPaseo, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, quoteUniswap, requestCommitmentKey, responseCommitmentKey, retryPromise, teleport, teleportDot, transformOrderForContract, tronChainIds, tronNile };
19788
20031
  //# sourceMappingURL=index.js.map
19789
20032
  //# sourceMappingURL=index.js.map