@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.
@@ -2,7 +2,7 @@ import { readFileSync } from 'fs';
2
2
  import { join } from 'path';
3
3
  import { TextDecoder as TextDecoder$1, TextEncoder as TextEncoder$1 } from 'util';
4
4
  import { createConsola, LogLevels } from 'consola';
5
- 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';
5
+ 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';
6
6
  import { baseSepolia, optimismSepolia, arbitrumSepolia, soneium, gnosis, optimism, polygonAmoy, unichain, polygon, base, arbitrum, bsc, mainnet, sepolia, gnosisChiado, bscTestnet, tron } from 'viem/chains';
7
7
  import { TronWeb } from 'tronweb';
8
8
  import { flatten, zip, capitalize, maxBy, isNil } from 'lodash-es';
@@ -7844,15 +7844,24 @@ function postRequestCommitment(post) {
7844
7844
  };
7845
7845
  }
7846
7846
  function bytes32ToBytes20(bytes32Address) {
7847
+ if (bytes32Address.length === 42) {
7848
+ return bytes32Address;
7849
+ }
7847
7850
  if (bytes32Address === ADDRESS_ZERO2) {
7848
7851
  return ADDRESS_ZERO2;
7849
7852
  }
7853
+ if (bytes32Address.length !== 66) {
7854
+ throw new Error(`Expected a 20-byte or 32-byte hex value, got ${bytes32Address.length} characters`);
7855
+ }
7850
7856
  const bytes = hexToBytes(bytes32Address);
7851
7857
  const addressBytes = bytes.slice(12);
7852
7858
  return bytesToHex(addressBytes);
7853
7859
  }
7854
7860
  function bytes20ToBytes32(bytes20Address) {
7855
7861
  if (bytes20Address.length === 66) return bytes20Address;
7862
+ if (bytes20Address.length !== 42) {
7863
+ throw new Error(`Expected a 20-byte or 32-byte hex value, got ${bytes20Address.length} characters`);
7864
+ }
7856
7865
  return `0x${bytes20Address.slice(2).padStart(64, "0")}`;
7857
7866
  }
7858
7867
  function hexToString(hex) {
@@ -7863,6 +7872,33 @@ function hexToString(hex) {
7863
7872
  }
7864
7873
  return new TextDecoder().decode(bytes);
7865
7874
  }
7875
+ function normalizeStateMachineId(stateMachineId) {
7876
+ return isHex(stateMachineId) ? hexToString(stateMachineId) : stateMachineId;
7877
+ }
7878
+ function normalizeEvmChainId(chainId) {
7879
+ if (typeof chainId === "number") {
7880
+ if (!Number.isInteger(chainId) || chainId <= 0) {
7881
+ throw new Error(`Invalid EVM chain ID: ${chainId}. Expected a positive integer.`);
7882
+ }
7883
+ return { chainId, stateMachineId: `EVM-${chainId}` };
7884
+ }
7885
+ const stateMachineId = normalizeStateMachineId(chainId);
7886
+ const { stateId } = parseStateMachineId(stateMachineId);
7887
+ if (!stateId.Evm) {
7888
+ throw new Error(`Unsupported chainId format: ${chainId}. Expected a number or EVM state machine ID.`);
7889
+ }
7890
+ return { chainId: stateId.Evm, stateMachineId };
7891
+ }
7892
+ function encodeStateMachineId(stateMachineId) {
7893
+ return isHex(stateMachineId) ? stateMachineId : toHex(stateMachineId);
7894
+ }
7895
+ function normalizeAddressForEvmBytes32(address) {
7896
+ if (address.length === 66) return address;
7897
+ return bytes20ToBytes32(address);
7898
+ }
7899
+ function normalizeAddressForStateMachine(address, stateMachineId) {
7900
+ return isEvmChain(normalizeStateMachineId(stateMachineId)) ? normalizeAddressForEvmBytes32(address) : address;
7901
+ }
7866
7902
  var DEFAULT_LOGGER = createConsola({
7867
7903
  level: LogLevels.silent
7868
7904
  });
@@ -8009,7 +8045,10 @@ function encodeWithdrawalRequest(order, beneficiary) {
8009
8045
  {
8010
8046
  commitment: order.id,
8011
8047
  beneficiary: bytes20ToBytes32(beneficiary),
8012
- tokens: order.inputs
8048
+ tokens: order.inputs.map((token) => ({
8049
+ ...token,
8050
+ token: normalizeAddressForEvmBytes32(token.token)
8051
+ }))
8013
8052
  }
8014
8053
  ]
8015
8054
  );
@@ -11372,13 +11411,200 @@ var PERMIT2_ABI = [
11372
11411
  type: "function"
11373
11412
  }
11374
11413
  ];
11414
+ var UniswapQuoteEngine = class {
11415
+ constructor(adapter, chainConfigService = new ChainConfigService()) {
11416
+ this.adapter = adapter;
11417
+ this.chainConfigService = chainConfigService;
11418
+ }
11419
+ adapter;
11420
+ chainConfigService;
11421
+ async quote(params, options = {}) {
11422
+ this.validateQuoteParams(params);
11423
+ const protocols = this.getQuoteProtocols(params.protocols);
11424
+ const { chainId, stateMachineId: evmChainID } = normalizeEvmChainId(params.chainId);
11425
+ const client = options.client ?? this.resolveClient(params.chainId);
11426
+ const quotes = [];
11427
+ for (const protocol of protocols) {
11428
+ const quote = params.tradeType === "EXACT_INPUT" ? await this.quoteExactInputForProtocol(params, client, protocol, chainId, evmChainID) : await this.quoteExactOutputForProtocol(params, client, protocol, chainId, evmChainID);
11429
+ if (quote) quotes.push(quote);
11430
+ }
11431
+ return { bestQuote: this.selectBestQuote(quotes, params.tradeType), quotes };
11432
+ }
11433
+ resolveClient(chainId) {
11434
+ const { stateMachineId: evmChainID } = normalizeEvmChainId(chainId);
11435
+ const rpcUrl = this.chainConfigService.getRpcUrl(evmChainID);
11436
+ if (!rpcUrl) {
11437
+ throw new Error(`No RPC URL configured for chain ${evmChainID}`);
11438
+ }
11439
+ return createPublicClient({ transport: http(rpcUrl) });
11440
+ }
11441
+ getQuoteProtocols(protocols) {
11442
+ return protocols?.length ? protocols : ["v2", "v3", "v4"];
11443
+ }
11444
+ validateQuoteParams(params) {
11445
+ if (params.tradeType === "EXACT_INPUT" && params.amountIn === void 0) {
11446
+ throw new Error("amountIn is required for EXACT_INPUT quotes");
11447
+ }
11448
+ if (params.tradeType === "EXACT_OUTPUT" && params.amountOut === void 0) {
11449
+ throw new Error("amountOut is required for EXACT_OUTPUT quotes");
11450
+ }
11451
+ if (params.slippageBps !== void 0 && (params.slippageBps < 0 || params.slippageBps > 1e4)) {
11452
+ throw new Error("slippageBps must be between 0 and 10000");
11453
+ }
11454
+ }
11455
+ applySlippageToAmountOut(amountOut, slippageBps) {
11456
+ return amountOut * BigInt(1e4 - slippageBps) / 10000n;
11457
+ }
11458
+ applySlippageToAmountIn(amountIn, slippageBps) {
11459
+ const numerator = amountIn * BigInt(1e4 + slippageBps);
11460
+ return (numerator + 9999n) / 10000n;
11461
+ }
11462
+ selectBestQuote(quotes, tradeType) {
11463
+ if (quotes.length === 0) return null;
11464
+ if (tradeType === "EXACT_INPUT") {
11465
+ return quotes.reduce((best, current) => {
11466
+ return current.amountOut > best.amountOut ? current : best;
11467
+ });
11468
+ }
11469
+ return quotes.reduce((best, current) => {
11470
+ return current.amountIn < best.amountIn ? current : best;
11471
+ });
11472
+ }
11473
+ createExactInputTransactions(protocol, params, minAmountOut, fee, evmChainID) {
11474
+ const amountIn = params.amountIn;
11475
+ const recipient = params.recipient;
11476
+ const path = [params.tokenIn.address, params.tokenOut.address];
11477
+ switch (protocol) {
11478
+ case "v2":
11479
+ return this.adapter.createV2SwapCalldataExactIn(path, amountIn, minAmountOut, recipient, evmChainID);
11480
+ case "v3":
11481
+ return this.adapter.createV3SwapCalldataExactIn(
11482
+ path,
11483
+ amountIn,
11484
+ minAmountOut,
11485
+ [fee],
11486
+ recipient,
11487
+ evmChainID
11488
+ );
11489
+ case "v4":
11490
+ return this.adapter.createV4SwapCalldataExactIn(
11491
+ params.tokenIn.address,
11492
+ params.tokenOut.address,
11493
+ amountIn,
11494
+ minAmountOut,
11495
+ fee,
11496
+ evmChainID
11497
+ );
11498
+ }
11499
+ }
11500
+ createExactOutputTransactions(protocol, params, maxAmountIn, fee, evmChainID) {
11501
+ const amountOut = params.amountOut;
11502
+ const recipient = params.recipient;
11503
+ const path = [params.tokenIn.address, params.tokenOut.address];
11504
+ switch (protocol) {
11505
+ case "v2":
11506
+ return this.adapter.createV2SwapCalldataExactOut(path, amountOut, maxAmountIn, recipient, evmChainID);
11507
+ case "v3":
11508
+ return this.adapter.createV3SwapCalldataExactOut(
11509
+ path,
11510
+ amountOut,
11511
+ maxAmountIn,
11512
+ [fee],
11513
+ recipient,
11514
+ evmChainID
11515
+ );
11516
+ case "v4":
11517
+ return this.adapter.createV4SwapCalldataExactOut(
11518
+ params.tokenIn.address,
11519
+ params.tokenOut.address,
11520
+ amountOut,
11521
+ maxAmountIn,
11522
+ fee,
11523
+ evmChainID
11524
+ );
11525
+ }
11526
+ }
11527
+ async quoteExactInputForProtocol(params, client, protocol, chainId, evmChainID) {
11528
+ const generateCalldata = !!params.recipient;
11529
+ const result = await this.adapter.findBestProtocolWithAmountIn(
11530
+ client,
11531
+ params.tokenIn.address,
11532
+ params.tokenOut.address,
11533
+ params.amountIn,
11534
+ evmChainID,
11535
+ {
11536
+ selectedProtocol: protocol,
11537
+ generateCalldata,
11538
+ recipient: params.recipient
11539
+ }
11540
+ );
11541
+ if (result.protocol === null || result.amountOut === 0n) return null;
11542
+ let transactions = result.transactions;
11543
+ const slippageBps = params.slippageBps ?? 0;
11544
+ if (generateCalldata && slippageBps > 0) {
11545
+ const minAmountOut = this.applySlippageToAmountOut(result.amountOut, slippageBps);
11546
+ transactions = this.createExactInputTransactions(protocol, params, minAmountOut, result.fee, evmChainID);
11547
+ }
11548
+ return {
11549
+ protocol,
11550
+ tradeType: params.tradeType,
11551
+ chainId,
11552
+ tokenIn: params.tokenIn,
11553
+ tokenOut: params.tokenOut,
11554
+ amountIn: params.amountIn,
11555
+ amountOut: result.amountOut,
11556
+ fee: result.fee,
11557
+ route: { tokens: [params.tokenIn.address, params.tokenOut.address] },
11558
+ transactions
11559
+ };
11560
+ }
11561
+ async quoteExactOutputForProtocol(params, client, protocol, chainId, evmChainID) {
11562
+ const generateCalldata = !!params.recipient;
11563
+ const result = await this.adapter.findBestProtocolWithAmountOut(
11564
+ client,
11565
+ params.tokenIn.address,
11566
+ params.tokenOut.address,
11567
+ params.amountOut,
11568
+ evmChainID,
11569
+ {
11570
+ selectedProtocol: protocol,
11571
+ generateCalldata,
11572
+ recipient: params.recipient
11573
+ }
11574
+ );
11575
+ if (result.protocol === null || result.amountIn === maxUint256) return null;
11576
+ let transactions = result.transactions;
11577
+ const slippageBps = params.slippageBps ?? 0;
11578
+ if (generateCalldata && slippageBps > 0) {
11579
+ const maxAmountIn = this.applySlippageToAmountIn(result.amountIn, slippageBps);
11580
+ transactions = this.createExactOutputTransactions(protocol, params, maxAmountIn, result.fee, evmChainID);
11581
+ }
11582
+ return {
11583
+ protocol,
11584
+ tradeType: params.tradeType,
11585
+ chainId,
11586
+ tokenIn: params.tokenIn,
11587
+ tokenOut: params.tokenOut,
11588
+ amountIn: result.amountIn,
11589
+ amountOut: params.amountOut,
11590
+ fee: result.fee,
11591
+ route: { tokens: [params.tokenIn.address, params.tokenOut.address] },
11592
+ transactions
11593
+ };
11594
+ }
11595
+ };
11375
11596
 
11376
11597
  // src/utils/swap.ts
11377
11598
  var COMMON_FEE_TIERS = [100, 500, 2500, 3e3, 1e4];
11378
11599
  var Swap = class {
11379
11600
  chainConfigService;
11601
+ uniswapQuoteEngine;
11380
11602
  constructor() {
11381
11603
  this.chainConfigService = new ChainConfigService();
11604
+ this.uniswapQuoteEngine = new UniswapQuoteEngine(this, this.chainConfigService);
11605
+ }
11606
+ async quoteUniswap(params) {
11607
+ return this.uniswapQuoteEngine.quote(params);
11382
11608
  }
11383
11609
  /**
11384
11610
  * Gets V2 quote for exact output swap.
@@ -12717,6 +12943,9 @@ var Swap = class {
12717
12943
  }
12718
12944
  }
12719
12945
  };
12946
+ async function quoteUniswap(params) {
12947
+ return new Swap().quoteUniswap(params);
12948
+ }
12720
12949
 
12721
12950
  // src/abis/erc7281.ts
12722
12951
  var ABI6 = [
@@ -15221,17 +15450,18 @@ function transformOrderForContract(order) {
15221
15450
  const { id: _id, ...contractOrder } = order;
15222
15451
  return {
15223
15452
  ...contractOrder,
15224
- source: order.source.startsWith("0x") ? order.source : toHex(order.source),
15225
- destination: order.destination.startsWith("0x") ? order.destination : toHex(order.destination),
15226
- inputs: order.inputs.map((t) => ({ ...t, token: bytes20ToBytes32(t.token) })),
15453
+ source: encodeStateMachineId(order.source),
15454
+ destination: encodeStateMachineId(order.destination),
15455
+ user: normalizeAddressForEvmBytes32(order.user),
15456
+ inputs: order.inputs.map((t) => ({ ...t, token: normalizeAddressForEvmBytes32(t.token) })),
15227
15457
  predispatch: {
15228
15458
  ...order.predispatch,
15229
- assets: order.predispatch.assets.map((t) => ({ ...t, token: bytes20ToBytes32(t.token) }))
15459
+ assets: order.predispatch.assets.map((t) => ({ ...t, token: normalizeAddressForEvmBytes32(t.token) }))
15230
15460
  },
15231
15461
  output: {
15232
15462
  ...order.output,
15233
- beneficiary: bytes20ToBytes32(order.output.beneficiary),
15234
- assets: order.output.assets.map((t) => ({ ...t, token: bytes20ToBytes32(t.token) }))
15463
+ beneficiary: normalizeAddressForEvmBytes32(order.output.beneficiary),
15464
+ assets: order.output.assets.map((t) => ({ ...t, token: normalizeAddressForEvmBytes32(t.token) }))
15235
15465
  }
15236
15466
  };
15237
15467
  }
@@ -15361,7 +15591,7 @@ var OrderPlacer = class {
15361
15591
  args: [transformOrderForContract(order), graffiti]
15362
15592
  });
15363
15593
  const intentGatewayAddress = this.ctx.source.configService.getIntentGatewayV2Address(
15364
- hexToString(order.source)
15594
+ normalizeStateMachineId(order.source)
15365
15595
  );
15366
15596
  const signedTransaction = yield {
15367
15597
  to: intentGatewayAddress,
@@ -15451,7 +15681,9 @@ var OrderExecutor = class {
15451
15681
  * UserOperation, pre-bound to the order's destination chain and entry point.
15452
15682
  */
15453
15683
  createUserOpHasher(order) {
15454
- const entryPointAddress = this.ctx.dest.configService.getEntryPointV08Address(hexToString(order.destination));
15684
+ const entryPointAddress = this.ctx.dest.configService.getEntryPointV08Address(
15685
+ normalizeStateMachineId(order.destination)
15686
+ );
15455
15687
  const chainId = BigInt(
15456
15688
  this.ctx.dest.client.chain?.id ?? Number.parseInt(this.ctx.dest.config.stateMachineId.split("-")[1])
15457
15689
  );
@@ -15736,12 +15968,12 @@ var OrderCanceller = class {
15736
15968
  * submitting the cancel transaction.
15737
15969
  *
15738
15970
  * @param order - The order to quote.
15739
- * @param fromDest - If `true`, quotes the destination-initiated path.
15971
+ * @param options - Choose the initiation side. Defaults to source-side cancellation.
15740
15972
  * @returns `{ nativeValue }` — native token amount (wei) to send as `value`;
15741
15973
  * `{ relayerFee }` — relayer incentive denominated in the chain's fee token.
15742
15974
  */
15743
- async quoteCancelOrder(order, fromDest = false) {
15744
- if (fromDest) {
15975
+ async quoteCancelOrder(order, options = {}) {
15976
+ if (options.from === "destination") {
15745
15977
  return this.quoteCancelFromDest(order);
15746
15978
  }
15747
15979
  return this.quoteCancelFromSource(order);
@@ -15758,10 +15990,10 @@ var OrderCanceller = class {
15758
15990
  */
15759
15991
  async quoteCancelFromSource(order) {
15760
15992
  if (order.source === order.destination) return { nativeValue: 0n, relayerFee: 0n };
15761
- const sourceStateMachine = order.source.startsWith("0x") ? hexToString(order.source) : order.source;
15993
+ const sourceStateMachine = normalizeStateMachineId(order.source);
15762
15994
  const height = order.deadline + 1n;
15763
15995
  const destIntentGateway = this.ctx.dest.configService.getIntentGatewayV2Address(
15764
- hexToString(order.destination)
15996
+ normalizeStateMachineId(order.destination)
15765
15997
  );
15766
15998
  const slotHash = await this.ctx.dest.client.readContract({
15767
15999
  abi: ABI7,
@@ -15773,8 +16005,8 @@ var OrderCanceller = class {
15773
16005
  const context = encodeWithdrawalRequest(order, order.user);
15774
16006
  const getRequest = {
15775
16007
  source: sourceStateMachine,
15776
- dest: order.destination.startsWith("0x") ? hexToString(order.destination) : order.destination,
15777
- from: this.ctx.source.configService.getIntentGatewayV2Address(hexToString(order.destination)),
16008
+ dest: normalizeStateMachineId(order.destination),
16009
+ from: this.ctx.source.configService.getIntentGatewayV2Address(normalizeStateMachineId(order.destination)),
15778
16010
  nonce: await this.ctx.source.getHostNonce(),
15779
16011
  height,
15780
16012
  keys: [key],
@@ -15796,13 +16028,13 @@ var OrderCanceller = class {
15796
16028
  * @param order - The order to cancel.
15797
16029
  * @param indexerClient - Indexer client used to stream ISMP request status
15798
16030
  * updates and query state-machine heights.
15799
- * @param fromDest - If `true`, initiates cancellation from the destination chain.
15800
- * Defaults to `false` (source-side cancellation).
16031
+ * @param options - Choose the initiation side. Defaults to source-side cancellation.
15801
16032
  * @yields {@link CancelEvent} objects describing each stage of the
15802
16033
  * cancellation lifecycle.
15803
16034
  */
15804
- async *cancelOrder(order, indexerClient, fromDest = false) {
15805
- if (fromDest) {
16035
+ async *cancelOrder(order, indexerClient, options = {}) {
16036
+ const isSameChain = order.source === order.destination;
16037
+ if (options.from === "destination" && !isSameChain) {
15806
16038
  yield* this.cancelOrderFromDest(order, indexerClient);
15807
16039
  return;
15808
16040
  }
@@ -15835,7 +16067,7 @@ var OrderCanceller = class {
15835
16067
  const orderId = order.id;
15836
16068
  const isSameChain = order.source === order.destination;
15837
16069
  const intentGatewayAddress = this.ctx.source.configService.getIntentGatewayV2Address(
15838
- hexToString(order.source)
16070
+ normalizeStateMachineId(order.source)
15839
16071
  );
15840
16072
  if (isSameChain) {
15841
16073
  const data = encodeFunctionData({
@@ -15866,7 +16098,7 @@ var OrderCanceller = class {
15866
16098
  return;
15867
16099
  }
15868
16100
  const hyperbridge = indexerClient.hyperbridge;
15869
- const sourceStateMachine = hexToString(order.source);
16101
+ const sourceStateMachine = normalizeStateMachineId(order.source);
15870
16102
  const sourceConsensusStateId = this.ctx.source.configService.getConsensusStateId(sourceStateMachine);
15871
16103
  let destIProof = await this.ctx.cancellationStorage.getItem(STORAGE_KEYS.destProof(orderId));
15872
16104
  if (!destIProof) {
@@ -15976,8 +16208,8 @@ var OrderCanceller = class {
15976
16208
  */
15977
16209
  async quoteCancelFromDest(order) {
15978
16210
  if (order.source === order.destination) return { nativeValue: 0n, relayerFee: 0n };
15979
- const destStateMachine = order.destination.startsWith("0x") ? hexToString(order.destination) : order.destination;
15980
- const sourceStateMachine = order.source.startsWith("0x") ? hexToString(order.source) : order.source;
16211
+ const destStateMachine = normalizeStateMachineId(order.destination);
16212
+ const sourceStateMachine = normalizeStateMachineId(order.source);
15981
16213
  const destIntentGateway = this.ctx.dest.configService.getIntentGatewayV2Address(destStateMachine);
15982
16214
  const sourceIntentGateway = this.ctx.source.configService.getIntentGatewayV2Address(sourceStateMachine);
15983
16215
  const relayerFee = await this.estimateRelayerFee(sourceStateMachine, destStateMachine);
@@ -15998,7 +16230,8 @@ var OrderCanceller = class {
15998
16230
  * Async generator that cancels an order by initiating from the destination
15999
16231
  * chain and streaming status updates until the source-chain escrow is refunded.
16000
16232
  *
16001
- * Throws if called with a same-chain order (use source-side cancellation instead).
16233
+ * Same-chain requests are handled by the top-level router and fall back to
16234
+ * the direct source-side cancellation path.
16002
16235
  *
16003
16236
  * **Steps:**
16004
16237
  * 1. Yields `AWAITING_CANCEL_TRANSACTION` so the caller can sign and submit
@@ -16011,15 +16244,11 @@ var OrderCanceller = class {
16011
16244
  * @param order - The cross-chain order to cancel.
16012
16245
  * @param indexerClient - Used to stream POST request status updates.
16013
16246
  * @yields {@link CancelEvent} at each lifecycle stage.
16014
- * @throws If the order is same-chain, or if the cancel transaction does not
16015
- * contain a `PostRequestEvent`.
16247
+ * @throws If the cancel transaction does not contain a `PostRequestEvent`.
16016
16248
  */
16017
16249
  async *cancelOrderFromDest(order, indexerClient) {
16018
16250
  const orderId = order.id;
16019
- if (order.source === order.destination) {
16020
- throw new Error("Cannot cancel same-chain order from destination; use cancelOrder instead");
16021
- }
16022
- const destStateMachine = order.destination.startsWith("0x") ? hexToString(order.destination) : order.destination;
16251
+ const destStateMachine = normalizeStateMachineId(order.destination);
16023
16252
  const intentGatewayAddress = this.ctx.dest.configService.getIntentGatewayV2Address(destStateMachine);
16024
16253
  let commitment = await this.ctx.cancellationStorage.getItem(
16025
16254
  STORAGE_KEYS.postCommitment(orderId)
@@ -16296,7 +16525,7 @@ var BidManager = class {
16296
16525
  throw new Error("No valid bids found");
16297
16526
  }
16298
16527
  const intentGatewayV2Address = this.ctx.dest.configService.getIntentGatewayV2Address(
16299
- hexToString(order.destination)
16528
+ normalizeStateMachineId(order.destination)
16300
16529
  );
16301
16530
  const domainSeparator = CryptoUtils.getDomainSeparator(
16302
16531
  "IntentGateway",
@@ -16355,7 +16584,7 @@ var BidManager = class {
16355
16584
  signature: finalSignature
16356
16585
  };
16357
16586
  const entryPointAddress = this.ctx.dest.configService.getEntryPointV08Address(
16358
- hexToString(order.destination)
16587
+ normalizeStateMachineId(order.destination)
16359
16588
  );
16360
16589
  BigInt(
16361
16590
  this.ctx.dest.client.chain?.id ?? Number.parseInt(this.ctx.dest.config.stateMachineId.split("-")[1])
@@ -18351,7 +18580,10 @@ var GasEstimator = class {
18351
18580
  const fillOptions = {
18352
18581
  relayerFee: crossChainFees.postRequestFee,
18353
18582
  nativeDispatchFee: crossChainFees.protocolFee,
18354
- outputs: order.output.assets
18583
+ outputs: order.output.assets.map((asset) => ({
18584
+ ...asset,
18585
+ token: normalizeAddressForEvmBytes32(asset.token)
18586
+ }))
18355
18587
  };
18356
18588
  const totalNativeValue = totalEthValue + fillOptions.nativeDispatchFee;
18357
18589
  const priorityFeeBumpPercent = params.maxPriorityFeePerGasBumpPercent ?? 8;
@@ -19003,12 +19235,18 @@ var IntentGateway = class _IntentGateway {
19003
19235
  * Delegates to {@link OrderCanceller.quoteCancelOrder}.
19004
19236
  *
19005
19237
  * @param order - The order to quote cancellation for.
19006
- * @param fromDest - If `true`, quotes the destination-initiated cancellation fee.
19238
+ * @param options - Choose the initiation side. Defaults to source-side cancellation.
19007
19239
  * @returns `{ nativeValue }` — native token amount (wei) to send as `value`;
19008
19240
  * `{ relayerFee }` — relayer incentive denominated in the chain's fee token.
19009
19241
  */
19010
- async quoteCancelOrder(order, fromDest = false) {
19011
- return this.orderCanceller.quoteCancelOrder(order, fromDest);
19242
+ async quoteCancelOrder(order, options = {}) {
19243
+ return this.orderCanceller.quoteCancelOrder(order, options);
19244
+ }
19245
+ async quoteCancelOrderFromSource(order) {
19246
+ return this.orderCanceller.quoteCancelOrder(order, { from: "source" });
19247
+ }
19248
+ async quoteCancelOrderFromDest(order) {
19249
+ return this.orderCanceller.quoteCancelOrder(order, { from: "destination" });
19012
19250
  }
19013
19251
  /**
19014
19252
  * Async generator that cancels an order and streams status events until
@@ -19018,12 +19256,17 @@ var IntentGateway = class _IntentGateway {
19018
19256
  *
19019
19257
  * @param order - The order to cancel.
19020
19258
  * @param indexerClient - Indexer client used for ISMP request status streaming.
19021
- * @param fromDest - If `true`, initiates cancellation from the destination chain.
19022
- * Defaults to `false` (source-side cancellation).
19259
+ * @param options - Choose the initiation side. Defaults to source-side cancellation.
19023
19260
  * @yields {@link CancelEvent} objects describing each cancellation stage.
19024
19261
  */
19025
- async *cancelOrder(order, indexerClient, fromDest = false) {
19026
- yield* this.orderCanceller.cancelOrder(order, indexerClient, fromDest);
19262
+ async *cancelOrder(order, indexerClient, options = {}) {
19263
+ yield* this.orderCanceller.cancelOrder(order, indexerClient, options);
19264
+ }
19265
+ async *cancelOrderFromSource(order, indexerClient) {
19266
+ yield* this.orderCanceller.cancelOrder(order, indexerClient, { from: "source" });
19267
+ }
19268
+ async *cancelOrderFromDest(order, indexerClient) {
19269
+ yield* this.orderCanceller.cancelOrder(order, indexerClient, { from: "destination" });
19027
19270
  }
19028
19271
  /**
19029
19272
  * Constructs a signed `PackedUserOperation` for a solver to submit as a bid.
@@ -19204,7 +19447,7 @@ var TokenGateway = class {
19204
19447
  * @returns The TokenGateway contract address
19205
19448
  */
19206
19449
  getTokenGatewayAddress(chain) {
19207
- const chainStr = typeof chain === "string" ? chain : new TextDecoder().decode(chain);
19450
+ const chainStr = normalizeStateMachineId(typeof chain === "string" ? chain : new TextDecoder().decode(chain));
19208
19451
  return this.source.configService.getTokenGatewayAddress(chainStr);
19209
19452
  }
19210
19453
  /**
@@ -19247,10 +19490,13 @@ var TokenGateway = class {
19247
19490
  */
19248
19491
  async quoteNative(params) {
19249
19492
  const dataHex = params.data ? typeof params.data === "string" ? params.data : toHex(params.data) : "0x";
19493
+ const destChainId = normalizeStateMachineId(
19494
+ typeof params.dest === "string" ? params.dest : new TextDecoder().decode(params.dest)
19495
+ );
19496
+ const recipient = normalizeAddressForStateMachine(params.to, destChainId);
19250
19497
  const sourceTokenGatewayAddress = this.getTokenGatewayAddress(this.source.config.stateMachineId);
19251
19498
  const destTokenGatewayAddress = this.getTokenGatewayAddress(params.dest);
19252
19499
  let relayerFee = 0n;
19253
- const destChainId = typeof params.dest === "string" ? params.dest : new TextDecoder().decode(params.dest);
19254
19500
  const isEvmDest = destChainId.startsWith("EVM-") && this.dest instanceof EvmChain;
19255
19501
  if (isEvmDest) {
19256
19502
  const randomHex = "0x" + Array.from({ length: 191 * 2 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
@@ -19277,7 +19523,7 @@ var TokenGateway = class {
19277
19523
  // Use the calculated relayer fee (0 for non-EVM destinations)
19278
19524
  params.assetId,
19279
19525
  params.redeem,
19280
- params.to,
19526
+ recipient,
19281
19527
  dataHex
19282
19528
  ]
19283
19529
  );
@@ -19461,17 +19707,14 @@ async function fetchLocalAssetId(params) {
19461
19707
  }
19462
19708
  async function teleport(teleport_param) {
19463
19709
  const { params, apiPromise, extrinsics = [] } = teleport_param;
19464
- const substrateComplianceAddr = (address, stateMachine) => {
19465
- if (stateMachine.startsWith("EVM-")) return pad(address, { size: 32, dir: "left" });
19466
- return address;
19467
- };
19468
19710
  const assetId = keccakAsU8a(params.symbol);
19469
19711
  const scaleEncodedAssetId = await fetchLocalAssetId({ api: apiPromise, assetId });
19470
19712
  if (scaleEncodedAssetId === null) {
19471
19713
  throw new Error("Unknown asset id provided");
19472
19714
  }
19473
- const destination = convertStateMachineIdToEnum(params.destination);
19474
- const recipient = hexToBytes(substrateComplianceAddr(params.recipient, params.destination));
19715
+ const destinationStateMachine = normalizeStateMachineId(params.destination);
19716
+ const destination = convertStateMachineIdToEnum(destinationStateMachine);
19717
+ const recipient = hexToBytes(normalizeAddressForStateMachine(params.recipient, destinationStateMachine));
19475
19718
  const teleportParams = {
19476
19719
  destination,
19477
19720
  recepient: Array.from(recipient),
@@ -19724,6 +19967,6 @@ async function teleportDot(param_) {
19724
19967
  return stream;
19725
19968
  }
19726
19969
 
19727
- 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 };
19970
+ 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 };
19728
19971
  //# sourceMappingURL=index.js.map
19729
19972
  //# sourceMappingURL=index.js.map