@hyperbridge/sdk 2.6.1 → 2.8.0

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.
@@ -7,7 +7,7 @@ import { match } from 'ts-pattern';
7
7
  import { WsProvider, ApiPromise, Keyring } from '@polkadot/api';
8
8
  import { Struct, Vector, u8, Bytes, Enum, Tuple, _void, u64, u32, Option, bool, u128 } from 'scale-ts';
9
9
  import { keccakAsU8a, decodeAddress, keccakAsHex, xxhashAsU8a, blake2AsU8a } from '@polkadot/util-crypto';
10
- import { hexToU8a, u8aToHex, u8aConcat } from '@polkadot/util';
10
+ import { hexToU8a, u8aToHex, u8aConcat, stringToU8a, isHex as isHex$1, u8aToString } from '@polkadot/util';
11
11
  import PQueue from 'p-queue';
12
12
  import { hasWindow, isNode, env } from 'std-env';
13
13
  import mergeRace from '@async-generator/merge-race';
@@ -2732,7 +2732,8 @@ var chainConfigs = {
2732
2732
  ZARP: "0xb755506531786C8aC63B756BaB1ac387bACB0C04",
2733
2733
  EURC: "0x1aBaEA1f7C830bD89Acc67eC4af516284b1bC33c",
2734
2734
  XSGD: "0x70e8dE73cE538DA2bEEd35d14187F6959a8ecA96",
2735
- TRYB: "0x2C537E5624e4af88A7ae4060C022609376C8D0EB"
2735
+ TRYB: "0x2C537E5624e4af88A7ae4060C022609376C8D0EB",
2736
+ USDR: "0x9623DfB044D5612Ce0c0F1606973CCAEFd03CD05"
2736
2737
  },
2737
2738
  tokenDecimals: {
2738
2739
  USDC: 6,
@@ -2771,6 +2772,10 @@ var chainConfigs = {
2771
2772
  consensusStateId: "ETH0",
2772
2773
  coingeckoId: "ethereum",
2773
2774
  layerZeroEid: 30101,
2775
+ erc4626Vaults: [
2776
+ { label: "Aave stataUSDC", address: "0xD4fa2D31b7968E448877f69A96DE69f5de8cD23E", asset: "USDC" },
2777
+ { label: "Aave stataUSDT", address: "0x7Bc3485026Ac48b6cf9BaF0A377477Fff5703Af8", asset: "USDT" }
2778
+ ],
2774
2779
  popularTokens: [
2775
2780
  "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
2776
2781
  "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
@@ -2825,6 +2830,10 @@ var chainConfigs = {
2825
2830
  defaultRpcUrl: "https://binance.llamarpc.com",
2826
2831
  consensusStateId: "BSC0",
2827
2832
  coingeckoId: "binance-smart-chain",
2833
+ erc4626Vaults: [
2834
+ { label: "Aave stataUSDC", address: "0x3906cDdfb781f02B21f21BD81ed7Fd8DC37075E1", asset: "USDC" },
2835
+ { label: "Aave stataUSDT", address: "0x0471D185cc7Be61E154277cAB2396cD397663da6", asset: "USDT" }
2836
+ ],
2828
2837
  popularTokens: [
2829
2838
  "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82",
2830
2839
  "0x000Ae314E2A2172a039B26378814C252734f556A",
@@ -2884,6 +2893,10 @@ var chainConfigs = {
2884
2893
  consensusStateId: "ETH0",
2885
2894
  coingeckoId: "arbitrum-one",
2886
2895
  layerZeroEid: 30110,
2896
+ erc4626Vaults: [
2897
+ { label: "Aave stataUSDC", address: "0x7F6501d3B98eE91f9b9535E4b0ac710Fb0f9e0bc", asset: "USDC" },
2898
+ { label: "Aave stataUSDT", address: "0xa6D12574eFB239FC1D2099732bd8b5dC6306897F", asset: "USDT" }
2899
+ ],
2887
2900
  popularTokens: [
2888
2901
  "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
2889
2902
  "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
@@ -2904,7 +2917,8 @@ var chainConfigs = {
2904
2917
  EXT: "0x0e668E5127087e236578893a0e01E41837A28469",
2905
2918
  cNGN: "0x46C85152bFe9f96829aA94755D9f915F9B10EF5F",
2906
2919
  ZARP: "0xb755506531786C8aC63B756BaB1ac387bACB0C04",
2907
- EURC: "0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42"
2920
+ EURC: "0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42",
2921
+ USDR: "0x3B5F2810fB2168FfA9C73160F97BF9f2461fFa5c"
2908
2922
  },
2909
2923
  tokenDecimals: {
2910
2924
  USDC: 6,
@@ -2946,6 +2960,10 @@ var chainConfigs = {
2946
2960
  coingeckoId: "base",
2947
2961
  layerZeroEid: 30184,
2948
2962
  uniswapV4Pools: [{ tokens: ["USDC", "cNGN"], fee: 1500, tickSpacing: 30 }],
2963
+ erc4626Vaults: [
2964
+ { label: "Aave stataUSDC", address: "0xC768c589647798a6EE01A91FdE98EF2ed046DBD6", asset: "USDC" },
2965
+ { label: "Yield Bearing cNGN", address: "0xa82A3531021317240Fb32E67f9c7bC091F737D3b", asset: "cNGN" }
2966
+ ],
2949
2967
  popularTokens: [
2950
2968
  "0x4200000000000000000000000000000000000006",
2951
2969
  "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
@@ -2966,7 +2984,8 @@ var chainConfigs = {
2966
2984
  EXT: "0x7C8c11ADb8EF7cd3CFa718008Ea048445C6E7209",
2967
2985
  cNGN: "0x52828daa48C1a9A06F37500882b42daf0bE04C3B",
2968
2986
  ZARP: "0xb755506531786C8aC63B756BaB1ac387bACB0C04",
2969
- XSGD: "0xDC3326e71D45186F113a2F448984CA0e8D201995"
2987
+ XSGD: "0xDC3326e71D45186F113a2F448984CA0e8D201995",
2988
+ USDR: "0x3B5F2810fB2168FfA9C73160F97BF9f2461fFa5c"
2970
2989
  },
2971
2990
  tokenDecimals: {
2972
2991
  USDC: 6,
@@ -3006,6 +3025,10 @@ var chainConfigs = {
3006
3025
  consensusStateId: "POLY",
3007
3026
  coingeckoId: "polygon-pos",
3008
3027
  layerZeroEid: 30109,
3028
+ erc4626Vaults: [
3029
+ { label: "Aave stataUSDC", address: "0x79261231698B26Ed9085b59ae89d59843Ae925a8", asset: "USDC" },
3030
+ { label: "Aave stataUSDT", address: "0x2eaD203C5C1C00612B1DdbBb20e4180dA822d6ff", asset: "USDT" }
3031
+ ],
3009
3032
  popularTokens: [
3010
3033
  "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
3011
3034
  "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
@@ -3052,7 +3075,7 @@ var chainConfigs = {
3052
3075
  WETH: "0x360ad4f9a9A8EFe9A8DCB5f461c4Cc1047E1Dcf9",
3053
3076
  //wmatic, change it to wpol
3054
3077
  DAI: "0x0000000000000000000000000000000000000000",
3055
- USDC: "0x693b854d6965ffeaae21c74049dea644b56fcacb",
3078
+ USDC: "0xBE97E73126D66188d72fbF99029126D0340a7f18",
3056
3079
  USDT: "0x0000000000000000000000000000000000000000"
3057
3080
  },
3058
3081
  tokenDecimals: {
@@ -3061,7 +3084,7 @@ var chainConfigs = {
3061
3084
  },
3062
3085
  tokenStorageSlots: {
3063
3086
  USDT: { balanceSlot: 0, allowanceSlot: 1 },
3064
- USDC: { balanceSlot: 1, allowanceSlot: 2 }
3087
+ USDC: { balanceSlot: 0, allowanceSlot: 1 }
3065
3088
  },
3066
3089
  addresses: {
3067
3090
  IntentGateway: "0x6CF42FA9BecbC5b6a26884964956b113530f7cFA",
@@ -4868,6 +4891,24 @@ var ABI3 = [
4868
4891
  internalType: "uint256"
4869
4892
  }
4870
4893
  ]
4894
+ },
4895
+ {
4896
+ name: "predispatchCall",
4897
+ type: "bytes",
4898
+ indexed: false,
4899
+ internalType: "bytes"
4900
+ },
4901
+ {
4902
+ name: "outputCall",
4903
+ type: "bytes",
4904
+ indexed: false,
4905
+ internalType: "bytes"
4906
+ },
4907
+ {
4908
+ name: "graffiti",
4909
+ type: "bytes32",
4910
+ indexed: false,
4911
+ internalType: "bytes32"
4871
4912
  }
4872
4913
  ],
4873
4914
  anonymous: false
@@ -5227,6 +5268,19 @@ var ChainConfigService = class {
5227
5268
  getExtDecimals(chain) {
5228
5269
  return this.getConfig(chain)?.tokenDecimals?.EXT;
5229
5270
  }
5271
+ /** Configured exotic (non-USD) tokens on a chain, for selection UIs. EXT is a test asset and is not offered. */
5272
+ getKnownExoticTokens(chain) {
5273
+ const config = this.getConfig(chain);
5274
+ const tokens = [];
5275
+ if (config?.assets?.cNGN) {
5276
+ tokens.push({ symbol: "cNGN", address: config.assets.cNGN, decimals: config.tokenDecimals?.cNGN });
5277
+ }
5278
+ return tokens;
5279
+ }
5280
+ /** Known ERC-4626 treasury vaults on a chain, for selection UIs. */
5281
+ getKnownVaults(chain) {
5282
+ return this.getConfig(chain)?.erc4626Vaults ?? [];
5283
+ }
5230
5284
  getChainId(chain) {
5231
5285
  return this.getConfig(chain)?.chainId ?? 0;
5232
5286
  }
@@ -7516,17 +7570,30 @@ var SubstrateChain = class _SubstrateChain {
7516
7570
  rotationMap.set(BigInt(setId.toString()), BigInt(height.toString()));
7517
7571
  }
7518
7572
  const proofs = [];
7519
- let epoch = currentEpoch - 1n;
7573
+ let epoch = currentEpoch + 1n;
7520
7574
  while (rotationMap.has(epoch)) {
7521
- const height = rotationMap.get(epoch);
7522
- const key = beefyOffchainKey(height);
7523
- const proof = await this.rpcClient.call("offchain_localStorageGet", ["PERSISTENT", key]);
7575
+ const key = rotationOffchainKey(epoch);
7576
+ let proof = await this.rpcClient.call("offchain_localStorageGet", ["PERSISTENT", key]);
7577
+ if (!proof) {
7578
+ const legacyKey = messagingOffchainKey(rotationMap.get(epoch));
7579
+ proof = await this.rpcClient.call("offchain_localStorageGet", ["PERSISTENT", legacyKey]);
7580
+ }
7524
7581
  if (!proof) return void 0;
7525
7582
  proofs.push(proof);
7526
7583
  epoch++;
7527
7584
  }
7528
- const messagingKey = beefyOffchainKey(lastProvenHeight);
7529
- const messagingProof = await this.rpcClient.call("offchain_localStorageGet", ["PERSISTENT", messagingKey]);
7585
+ const messagingKey = messagingOffchainKey(lastProvenHeight);
7586
+ let messagingProof = await this.rpcClient.call("offchain_localStorageGet", ["PERSISTENT", messagingKey]);
7587
+ if (!messagingProof) {
7588
+ for (const [setId, height] of rotationMap) {
7589
+ if (height !== lastProvenHeight) continue;
7590
+ messagingProof = await this.rpcClient.call("offchain_localStorageGet", [
7591
+ "PERSISTENT",
7592
+ rotationOffchainKey(setId)
7593
+ ]);
7594
+ break;
7595
+ }
7596
+ }
7530
7597
  if (!messagingProof) return void 0;
7531
7598
  proofs.push(messagingProof);
7532
7599
  return { proofs, provenHeight: lastProvenHeight };
@@ -7543,11 +7610,17 @@ var SubstrateChain = class _SubstrateChain {
7543
7610
  throw new Error(`${name} not found in runtime`);
7544
7611
  }
7545
7612
  };
7546
- function beefyOffchainKey(provenHeight) {
7547
- const prefix = new TextEncoder().encode("beefy_consensus_proofs::");
7548
- const heightBytes = new Uint8Array(8);
7549
- new DataView(heightBytes.buffer).setBigUint64(0, provenHeight, false);
7550
- return toHex(new Uint8Array([...prefix, ...heightBytes]));
7613
+ function beefyOffchainKey(prefix, id) {
7614
+ const prefixBytes = new TextEncoder().encode(prefix);
7615
+ const idBytes = new Uint8Array(8);
7616
+ new DataView(idBytes.buffer).setBigUint64(0, id, false);
7617
+ return toHex(new Uint8Array([...prefixBytes, ...idBytes]));
7618
+ }
7619
+ function messagingOffchainKey(provenHeight) {
7620
+ return beefyOffchainKey("beefy_consensus_proofs::", provenHeight);
7621
+ }
7622
+ function rotationOffchainKey(setId) {
7623
+ return beefyOffchainKey("beefy_consensus_proofs::rotation::", setId);
7551
7624
  }
7552
7625
  function requestCommitmentStorageKey(key) {
7553
7626
  const prefix = new TextEncoder().encode("RequestCommitments");
@@ -8217,14 +8290,17 @@ var IntentsCoprocessor = class _IntentsCoprocessor {
8217
8290
  const orders = [];
8218
8291
  for (const { event } of records) {
8219
8292
  if (event.section !== "intentsCoprocessor" || event.method !== "PhantomOrderRegistered") continue;
8220
- const [commitment, chain, createdAt, tokenA, tokenB, standardAmount] = event.data;
8293
+ const [commitment, chain, createdAt, legs] = event.data;
8221
8294
  orders.push({
8222
8295
  commitment: commitment.toHex(),
8223
8296
  chain: new TextDecoder().decode(hexToU8a(chain.toHex())),
8224
8297
  createdAt: createdAt.toNumber(),
8225
- tokenA: tokenA.toHex(),
8226
- tokenB: tokenB.toHex(),
8227
- standardAmount: BigInt(standardAmount.toString())
8298
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
8299
+ legs: legs.map((leg) => ({
8300
+ tokenA: leg.tokenA.toHex(),
8301
+ tokenB: leg.tokenB.toHex(),
8302
+ standardAmount: BigInt(leg.standardAmount.toString())
8303
+ }))
8228
8304
  });
8229
8305
  }
8230
8306
  return orders;
@@ -15445,14 +15521,21 @@ function orderCommitment(order) {
15445
15521
  const encoded = encodeAbiParameters([orderType], [transformOrderForContract(order)]);
15446
15522
  return keccak256(encoded);
15447
15523
  }
15448
- async function convertGasToFeeToken(ctx, gasEstimate, gasEstimateIn, evmChainID, gasPriceOverride) {
15524
+ function bumpGasPrice(gasPrice, bumpPercent) {
15525
+ if (bumpPercent < 0n) {
15526
+ throw new Error("Gas price bump percent cannot be negative");
15527
+ }
15528
+ return (gasPrice * (100n + bumpPercent) + 99n) / 100n;
15529
+ }
15530
+ async function convertGasToFeeToken(ctx, gasEstimate, gasEstimateIn, evmChainID, gasPriceOverride, gasPriceBumpPercent = 0n) {
15449
15531
  if (TESTNET_CHAINS.has(evmChainID)) return 1n;
15450
15532
  const chain = ctx[gasEstimateIn];
15451
15533
  const client = chain.client;
15452
- const gasPrice = gasPriceOverride ?? await retryPromise(() => client.getGasPrice(), {
15534
+ const baseGasPrice = gasPriceOverride ?? await retryPromise(() => client.getGasPrice(), {
15453
15535
  maxRetries: 3,
15454
15536
  backoffMs: 250
15455
15537
  });
15538
+ const gasPrice = bumpGasPrice(baseGasPrice, gasPriceBumpPercent);
15456
15539
  const gasCostInWei = gasEstimate * gasPrice;
15457
15540
  const wethAddr = chain.configService.getWrappedNativeAssetWithDecimals(evmChainID).asset;
15458
15541
  const feeToken = await getFeeToken(ctx, evmChainID, chain);
@@ -15523,13 +15606,13 @@ function deriveCanonicalPlacedOrder(order, args) {
15523
15606
  session: args.session,
15524
15607
  predispatch: {
15525
15608
  assets: args.predispatch.map((asset) => ({ ...asset })),
15526
- call: order.predispatch.call
15609
+ call: args.predispatchCall ?? order.predispatch.call
15527
15610
  },
15528
15611
  inputs: args.inputs.map((asset) => ({ ...asset })),
15529
15612
  output: {
15530
15613
  beneficiary: args.beneficiary,
15531
15614
  assets: args.outputs.map((asset) => ({ ...asset })),
15532
- call: order.output.call
15615
+ call: args.outputCall ?? order.output.call
15533
15616
  }
15534
15617
  };
15535
15618
  return { ...canonicalOrder, id: orderCommitment(canonicalOrder) };
@@ -15953,6 +16036,12 @@ var OrderCanceller = class _OrderCanceller {
15953
16036
  static DEFAULT_MAX_RECOVERY_RESTARTS = 1;
15954
16037
  static PROOF_FRESHNESS_MAX_RETRIES = 3;
15955
16038
  static PROOF_FRESHNESS_BACKOFF_MS = 500;
16039
+ /**
16040
+ * Gas budget used to size the relayer fee for a cross-chain cancellation
16041
+ * message (the GET response or RefundEscrow POST executed on the source
16042
+ * chain), priced at the source chain's gas price.
16043
+ */
16044
+ static CANCEL_MESSAGE_GAS = 800000n;
15956
16045
  logger = createConsola({
15957
16046
  level: LogLevels.info,
15958
16047
  formatOptions: { columns: 80, colors: true, compact: true, date: false }
@@ -16011,9 +16100,14 @@ var OrderCanceller = class _OrderCanceller {
16011
16100
  timeoutTimestamp: 0n,
16012
16101
  context
16013
16102
  };
16014
- const feeInSourceFeeToken = await convertGasToFeeToken(this.ctx, 400000n, "source", sourceStateMachine);
16103
+ const feeInSourceFeeToken = await convertGasToFeeToken(
16104
+ this.ctx,
16105
+ _OrderCanceller.CANCEL_MESSAGE_GAS,
16106
+ "source",
16107
+ sourceStateMachine
16108
+ );
16015
16109
  const relayerFee = feeInSourceFeeToken * 1005n / 1000n;
16016
- const nativeValue = await this.ctx.source.quoteNative(getRequest, relayerFee);
16110
+ const nativeValue = await this.ctx.source.quoteNative(getRequest, relayerFee) * 101n / 100n;
16017
16111
  return { nativeValue, relayerFee };
16018
16112
  }
16019
16113
  /**
@@ -16272,7 +16366,7 @@ var OrderCanceller = class _OrderCanceller {
16272
16366
  body,
16273
16367
  timeoutTimestamp: 0n
16274
16368
  };
16275
- const nativeValue = await this.ctx.dest.quoteNative(postRequest, relayerFee);
16369
+ const nativeValue = await this.ctx.dest.quoteNative(postRequest, relayerFee) * 101n / 100n;
16276
16370
  return { nativeValue, relayerFee };
16277
16371
  }
16278
16372
  /**
@@ -16602,8 +16696,12 @@ var OrderCanceller = class _OrderCanceller {
16602
16696
  * Converts estimated gas on the source chain into the dest chain's fee token.
16603
16697
  */
16604
16698
  async estimateRelayerFee(sourceChainId, destChainId) {
16605
- const POST_REQUEST_GAS = 400000n;
16606
- const feeInSourceFeeToken = await convertGasToFeeToken(this.ctx, POST_REQUEST_GAS, "source", sourceChainId);
16699
+ const feeInSourceFeeToken = await convertGasToFeeToken(
16700
+ this.ctx,
16701
+ _OrderCanceller.CANCEL_MESSAGE_GAS,
16702
+ "source",
16703
+ sourceChainId
16704
+ );
16607
16705
  const sourceFeeToken = await getFeeToken(this.ctx, sourceChainId, this.ctx.source);
16608
16706
  const destFeeToken = await getFeeToken(this.ctx, destChainId, this.ctx.dest);
16609
16707
  const feeInDestFeeToken = adjustDecimals(feeInSourceFeeToken, sourceFeeToken.decimals, destFeeToken.decimals);
@@ -17362,12 +17460,15 @@ var GasEstimator = class {
17362
17460
  *
17363
17461
  * @param params - Parameters including the order to estimate and optional
17364
17462
  * percentage bumps for `maxPriorityFeePerGas` and `maxFeePerGas`.
17463
+ * @param pricingOptions - Internal fee-pricing policy. Direct estimates use
17464
+ * the default zero gas-price bump; SDK order-fee quotes opt into headroom.
17365
17465
  * @returns A {@link FillOrderEstimate} containing all gas components,
17366
17466
  * EIP-1559 fee values, total cost in wei, and total cost in the source
17367
17467
  * chain's fee token.
17368
17468
  */
17369
- async estimateFillOrder(params) {
17469
+ async estimateFillOrder(params, pricingOptions = {}) {
17370
17470
  const { order } = params;
17471
+ const orderFeeGasPriceBumpPercent = pricingOptions.orderFeeGasPriceBumpPercent ?? 0n;
17371
17472
  const solverPrivateKey = generatePrivateKey();
17372
17473
  const solverAccountAddress = privateKeyToAddress(solverPrivateKey);
17373
17474
  const souceStateMachineId = isHex(order.source) ? hexToString$1(order.source) : order.source;
@@ -17398,7 +17499,12 @@ var GasEstimator = class {
17398
17499
  intentGatewayV2Address,
17399
17500
  entryPointAddress
17400
17501
  }),
17401
- isSameChain ? Promise.resolve({ postRequestFee: 0n, relayerFeeInSourceFeeToken: 0n }) : this.estimateCrossChainFees(sourceFeeToken, destFeeToken, souceStateMachineId)
17502
+ isSameChain ? Promise.resolve({ postRequestFee: 0n, relayerFeeInSourceFeeToken: 0n }) : this.estimateCrossChainFees(
17503
+ sourceFeeToken,
17504
+ destFeeToken,
17505
+ souceStateMachineId,
17506
+ orderFeeGasPriceBumpPercent
17507
+ )
17402
17508
  ]);
17403
17509
  const { viem: stateOverrides, bundler: bundlerStateOverrides } = stateOverridesResult;
17404
17510
  const fillOptions = {
@@ -17563,7 +17669,8 @@ var GasEstimator = class {
17563
17669
  totalGas,
17564
17670
  "dest",
17565
17671
  destStateMachineId,
17566
- gasPrice
17672
+ gasPrice,
17673
+ orderFeeGasPriceBumpPercent
17567
17674
  );
17568
17675
  const totalGasInSourceFeeToken = isSameChain ? totalGasInDestFeeToken : adjustDecimals(totalGasInDestFeeToken, destFeeToken.decimals, sourceFeeToken.decimals);
17569
17676
  const totalGasCostWei = isSameChain ? rawTotalGasCostWei : await convertFeeTokenToWei(this.ctx, totalGasInSourceFeeToken, "source", souceStateMachineId);
@@ -17587,12 +17694,14 @@ var GasEstimator = class {
17587
17694
  * The dispatch is always paid in the fee token — the native rail was
17588
17695
  * removed because it silently drew on a native balance nothing guarantees.
17589
17696
  */
17590
- async estimateCrossChainFees(sourceFeeToken, destFeeToken, sourceChainId) {
17697
+ async estimateCrossChainFees(sourceFeeToken, destFeeToken, sourceChainId, orderFeeGasPriceBumpPercent) {
17591
17698
  const postRequestFeeInSourceFeeToken = await convertGasToFeeToken(
17592
17699
  this.ctx,
17593
17700
  RELAYER_MESSAGE_GAS,
17594
17701
  "source",
17595
- sourceChainId
17702
+ sourceChainId,
17703
+ void 0,
17704
+ orderFeeGasPriceBumpPercent
17596
17705
  );
17597
17706
  const postRequestFeeInDestFeeToken = adjustDecimals(
17598
17707
  postRequestFeeInSourceFeeToken,
@@ -18362,6 +18471,7 @@ function isConfiguredAddress(address) {
18362
18471
  }
18363
18472
 
18364
18473
  // src/protocols/intents/IntentGateway.ts
18474
+ var CROSS_CHAIN_ORDER_FEE_GAS_PRICE_BUMP_PERCENT = 10n;
18365
18475
  var IntentGateway = class _IntentGateway {
18366
18476
  /** EVM chain on which orders are placed and escrowed. */
18367
18477
  source;
@@ -18548,14 +18658,22 @@ var IntentGateway = class _IntentGateway {
18548
18658
  * placement, fee estimation, bid collection, and execution.
18549
18659
  *
18550
18660
  * **Yield/receive protocol:**
18551
- * 1. If `order.fees` is unset or zero, estimates gas on an internal copy and
18552
- * sets same-chain fees to twice the estimate. Cross-chain orders attach
18553
- * (fill gas + a settlement-message uplift of `RELAYER_MESSAGE_GAS`, the
18554
- * same gas budget the solver's relayer fee uses) with a 5% buffer over
18555
- * the whole sum — strictly above the solver's unpadded requirement. The
18556
- * wei cost used for the `value` field receives a 2% buffer.
18557
- * 2. Yields `AWAITING_PLACE_ORDER` with `{ to, data, value, sessionPrivateKey }`.
18558
- * The caller must sign the transaction and pass it back via `gen.next(signedTx)`.
18661
+ * 1. If `order.fees` is unset or zero, prices the fee on an internal copy
18662
+ * via {@link quoteOrderFees}: same-chain fees are twice the fill-gas
18663
+ * estimate without a gas-price bump; cross-chain gas is priced 10% above
18664
+ * the live price before attaching (fill gas + the settlement relayer fee)
18665
+ * with a further 5% buffer over the whole sum — strictly above the solver's
18666
+ * unpadded requirement. Direct solver estimates remain unbumped. The wei
18667
+ * cost used for the `value` field receives a 2% buffer.
18668
+ * 2. Yields `AWAITING_PLACE_ORDER` with `{ to, data, value, nativeFee,
18669
+ * feeTokenAmount, feeTokenAddress, sessionPrivateKey }`. `value` carries
18670
+ * only the order's native-token input amounts; `nativeFee` is the native
18671
+ * amount that funds `order.fees` (`0n` when the caller set `order.fees`);
18672
+ * `feeTokenAmount`/`feeTokenAddress` are the exact fee encoded in `data`
18673
+ * and the source-chain token it is charged in. To pay the fee in native
18674
+ * token, sign the transaction with `value + nativeFee`; with a fee-token
18675
+ * allowance, `value` alone. Pass the signed transaction back via
18676
+ * `gen.next(signedTx)`.
18559
18677
  * 3. Yields `ORDER_PLACED` with the finalised order and transaction hash once
18560
18678
  * the `OrderPlaced` event is confirmed.
18561
18679
  * 4. Delegates to {@link OrderExecutor.executeOrder} and forwards all
@@ -18576,33 +18694,33 @@ var IntentGateway = class _IntentGateway {
18576
18694
  */
18577
18695
  async *execute(order, graffiti = DEFAULT_GRAFFITI, options) {
18578
18696
  const executionOrder = { ...order };
18579
- let value;
18697
+ let nativeFee = 0n;
18580
18698
  if (!executionOrder.fees || executionOrder.fees === 0n) {
18581
- const estimate = await this.gasEstimator.estimateFillOrder({
18582
- order: executionOrder,
18699
+ const feesQuote = await this.quoteOrderFees(executionOrder, {
18583
18700
  maxPriorityFeePerGasBumpPercent: options?.maxPriorityFeePerGasBumpPercent,
18584
18701
  maxFeePerGasBumpPercent: options?.maxFeePerGasBumpPercent
18585
18702
  });
18586
- if (estimate.totalGasCostWei === 0n || estimate.totalGasInFeeToken === 0n) {
18587
- throw new Error("Gas estimation failed");
18588
- }
18589
- const isSameChain = this.source.config.stateMachineId === this.dest.config.stateMachineId;
18590
- value = estimate.totalGasCostWei + estimate.totalGasCostWei * 2n / 100n;
18591
- const crossChainFeeBump = isSameChain ? 0n : await convertGasToFeeToken(
18592
- this.ctx,
18593
- RELAYER_MESSAGE_GAS,
18594
- "source",
18595
- this.source.config.stateMachineId
18596
- );
18597
- executionOrder.fees = isSameChain ? estimate.totalGasInFeeToken * 2n : (estimate.totalGasInFeeToken + crossChainFeeBump) * 105n / 100n;
18703
+ nativeFee = feesQuote.nativeValue;
18704
+ executionOrder.fees = feesQuote.fees;
18598
18705
  }
18706
+ const value = executionOrder.inputs.filter((input) => bytes32ToBytes20(input.token) === ADDRESS_ZERO2).reduce((sum, input) => sum + input.amount, 0n);
18599
18707
  const placeOrderGen = this.orderPlacer.placeOrder(executionOrder, graffiti);
18600
18708
  const placeOrderFirst = await placeOrderGen.next();
18601
18709
  if (placeOrderFirst.done) {
18602
18710
  throw new Error("placeOrder generator completed without yielding");
18603
18711
  }
18604
18712
  const { to, data, sessionPrivateKey } = placeOrderFirst.value;
18605
- const signedTransaction = yield { status: "AWAITING_PLACE_ORDER", to, data, value, sessionPrivateKey };
18713
+ const { address: feeTokenAddress } = await getFeeToken(this.ctx, this.source.config.stateMachineId, this.source);
18714
+ const signedTransaction = yield {
18715
+ status: "AWAITING_PLACE_ORDER",
18716
+ to,
18717
+ data,
18718
+ value,
18719
+ nativeFee,
18720
+ sessionPrivateKey,
18721
+ feeTokenAmount: executionOrder.fees,
18722
+ feeTokenAddress
18723
+ };
18606
18724
  const placeOrderSecond = await placeOrderGen.next(signedTransaction);
18607
18725
  if (placeOrderSecond.done === false) {
18608
18726
  throw new Error("placeOrder generator yielded unexpectedly after signing");
@@ -18902,6 +19020,50 @@ var IntentGateway = class _IntentGateway {
18902
19020
  async estimateFillOrder(params) {
18903
19021
  return this.gasEstimator.estimateFillOrder(params);
18904
19022
  }
19023
+ /**
19024
+ * Quotes the solver fee for an order using the same policy {@link execute} /
19025
+ * {@link executeBest} apply when `order.fees` is `0n`.
19026
+ *
19027
+ * Use this before placing to display the fee, or to check what the user can
19028
+ * afford: pay `fees` in the source-chain fee token (check balance and
19029
+ * allowance, then set `order.fees` and submit with `value: 0`), or leave
19030
+ * `order.fees` at `0n` and let the SDK attach `nativeValue` to the placement
19031
+ * transaction (check the native balance).
19032
+ *
19033
+ * @param order - The order to quote. `order.fees` is ignored and not mutated.
19034
+ * Gas prices used to derive cross-chain `fees` receive 10% SDK-only headroom.
19035
+ * Same-chain quotes and direct calls to {@link estimateFillOrder}, including
19036
+ * Simplex solver estimates, remain unbumped.
19037
+ *
19038
+ * @param options - Optional transaction gas-price bump percentages, as in {@link execute}.
19039
+ * @returns An {@link OrderFeesQuote} with the fee-token amount, the native
19040
+ * value for the native rail, and the underlying estimate.
19041
+ * @throws If gas estimation returns zero.
19042
+ */
19043
+ async quoteOrderFees(order, options) {
19044
+ const isSameChain = this.source.config.stateMachineId === this.dest.config.stateMachineId;
19045
+ const estimate = await this.gasEstimator.estimateFillOrder(
19046
+ {
19047
+ order,
19048
+ maxPriorityFeePerGasBumpPercent: options?.maxPriorityFeePerGasBumpPercent,
19049
+ maxFeePerGasBumpPercent: options?.maxFeePerGasBumpPercent
19050
+ },
19051
+ {
19052
+ orderFeeGasPriceBumpPercent: isSameChain ? 0n : CROSS_CHAIN_ORDER_FEE_GAS_PRICE_BUMP_PERCENT
19053
+ }
19054
+ );
19055
+ if (estimate.totalGasCostWei === 0n || estimate.totalGasInFeeToken === 0n) {
19056
+ throw new Error("Gas estimation failed");
19057
+ }
19058
+ const fees = isSameChain ? estimate.totalGasInFeeToken * 2n : (estimate.totalGasInFeeToken + estimate.relayerFeeInSourceFeeToken) * 105n / 100n;
19059
+ const { address: feeToken } = await this.source.getFeeTokenWithDecimals();
19060
+ return {
19061
+ fees,
19062
+ nativeValue: estimate.totalGasCostWei + estimate.totalGasCostWei * 2n / 100n,
19063
+ feeToken,
19064
+ estimate
19065
+ };
19066
+ }
18905
19067
  /**
18906
19068
  * Encodes a list of calls into ERC-7821 `execute` calldata using
18907
19069
  * single-batch mode.
@@ -19028,6 +19190,44 @@ var IntentGateway = class _IntentGateway {
19028
19190
  }
19029
19191
  }
19030
19192
  };
19193
+ var FILL_ORDER_ABI = IntentGatewayV2_default.ABI;
19194
+ var DECLARATION_VERSION = 1;
19195
+ var MAX_DECLARED_CHAINS = 255;
19196
+ function encodeAcceptedSourceChains(chains2) {
19197
+ if (chains2.length > MAX_DECLARED_CHAINS) {
19198
+ throw new Error(`Cannot declare more than ${MAX_DECLARED_CHAINS} source chains`);
19199
+ }
19200
+ const bytes = [DECLARATION_VERSION, chains2.length];
19201
+ for (const chain of chains2) {
19202
+ const encoded = stringToU8a(chain);
19203
+ if (encoded.length === 0 || encoded.length > 255) {
19204
+ throw new Error(`Invalid state machine id in source chain declaration: ${chain}`);
19205
+ }
19206
+ bytes.push(encoded.length, ...encoded);
19207
+ }
19208
+ return u8aToHex(new Uint8Array(bytes));
19209
+ }
19210
+ function decodeAcceptedSourceChains(paymasterAndData) {
19211
+ if (!paymasterAndData || !isHex$1(paymasterAndData)) return null;
19212
+ const bytes = hexToU8a(paymasterAndData);
19213
+ if (bytes.length < 2 || bytes[0] !== DECLARATION_VERSION) return null;
19214
+ const count = bytes[1];
19215
+ const chains2 = [];
19216
+ let offset = 2;
19217
+ for (let entry = 0; entry < count; entry++) {
19218
+ if (offset >= bytes.length) return null;
19219
+ const length = bytes[offset];
19220
+ offset += 1;
19221
+ if (length === 0 || offset + length > bytes.length) return null;
19222
+ chains2.push(u8aToString(bytes.subarray(offset, offset + length)));
19223
+ offset += length;
19224
+ }
19225
+ if (offset !== bytes.length) return null;
19226
+ return chains2;
19227
+ }
19228
+ FILL_ORDER_ABI.find(
19229
+ (item) => item?.type === "function" && item?.name === "fillOrder"
19230
+ )?.inputs?.[0];
19031
19231
  var TokenGateway = class {
19032
19232
  source;
19033
19233
  dest;
@@ -23498,6 +23698,6 @@ async function teleportDot(param_) {
23498
23698
  return stream;
23499
23699
  }
23500
23700
 
23501
- 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, HyperFungibleToken, HyperFungibleTokenABI, IntentGateway, ABI3 as IntentGatewayABI, IntentOrderStatus, IntentsCoprocessor, InvalidPhantomSnapshotError, IsmpClient, MOCK_ADDRESS, ORDER_V2_PARAM_TYPE, OrderStatus, OrderStatusChecker, PACKED_USEROP_TYPEHASH, PLACE_ORDER_SELECTOR, PhantomSnapshotUnavailableError, 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, UnsupportedIntentQuotePairError, UnsupportedIntentQuoteStrategyError, WrappedHyperFungibleTokenABI, __test, adjustDecimals, bytes20ToBytes32, bytes32ToBytes20, calculateAllowanceMappingLocation, calculateBalanceMappingLocation, chainConfigs, constructRedeemEscrowRequestBody, constructRefundEscrowRequestBody, convertCodecToIGetRequest, convertCodecToIProof, convertIGetRequestToCodec, convertIProofToCodec, convertStateIdToStateMachineId, convertStateMachineEnumToString, convertStateMachineIdToEnum, createEvmChain, createQueryClient, decodeERC7821ExecuteBatch, decodeUserOpScale, encodeERC7821ExecuteBatch, encodeISMPMessage, encodeStateMachineId, encodeUserOpScale, encodeWithdrawalRequest, estimateGasForPost, fetchPrice, fetchSourceProof, generateRootWithProof, getChainId, getConfigByStateMachineId, getContractCallInput, getContractCallInputs, getGasPriceFromEtherscan, getOrFetchStorageSlot, getOrderPlacedFromTx, getPostRequestEventFromTx, getPostResponseEventFromTx, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, getViemChain, hexToString, hyperbridgeAddress, maxBigInt, normalizeAddressForEvmBytes32, normalizeAddressForStateMachine, normalizeEvmAddress, normalizeEvmChainId, normalizeStateMachineId, orderCommitment, parseStateMachineId, pharosAtlantic, pharosMainnet, polkadotAssetHubPaseo, polkadotHubMainnet, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, quoteUniswap, requestCommitmentKey, responseCommitmentKey, retryPromise, teleport, teleportDot, transformOrderForContract, tronChainIds, tronNile };
23701
+ 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, HyperFungibleToken, HyperFungibleTokenABI, IntentGateway, ABI3 as IntentGatewayABI, IntentOrderStatus, IntentsCoprocessor, InvalidPhantomSnapshotError, IsmpClient, MOCK_ADDRESS, ORDER_V2_PARAM_TYPE, OrderStatus, OrderStatusChecker, PACKED_USEROP_TYPEHASH, PLACE_ORDER_SELECTOR, PhantomSnapshotUnavailableError, 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, UnsupportedIntentQuotePairError, UnsupportedIntentQuoteStrategyError, WrappedHyperFungibleTokenABI, __test, adjustDecimals, bytes20ToBytes32, bytes32ToBytes20, calculateAllowanceMappingLocation, calculateBalanceMappingLocation, chainConfigs, constructRedeemEscrowRequestBody, constructRefundEscrowRequestBody, convertCodecToIGetRequest, convertCodecToIProof, convertIGetRequestToCodec, convertIProofToCodec, convertStateIdToStateMachineId, convertStateMachineEnumToString, convertStateMachineIdToEnum, createEvmChain, createQueryClient, decodeAcceptedSourceChains, decodeERC7821ExecuteBatch, decodeUserOpScale, encodeAcceptedSourceChains, encodeERC7821ExecuteBatch, encodeISMPMessage, encodeStateMachineId, encodeUserOpScale, encodeWithdrawalRequest, estimateGasForPost, fetchPrice, fetchSourceProof, generateRootWithProof, getChainId, getConfigByStateMachineId, getContractCallInput, getContractCallInputs, getGasPriceFromEtherscan, getOrFetchStorageSlot, getOrderPlacedFromTx, getPostRequestEventFromTx, getPostResponseEventFromTx, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, getViemChain, hexToString, hyperbridgeAddress, maxBigInt, normalizeAddressForEvmBytes32, normalizeAddressForStateMachine, normalizeEvmAddress, normalizeEvmChainId, normalizeStateMachineId, orderCommitment, parseStateMachineId, pharosAtlantic, pharosMainnet, polkadotAssetHubPaseo, polkadotHubMainnet, postRequestCommitment, queryAssetTeleported, queryGetRequest, queryPostRequest, quoteUniswap, requestCommitmentKey, responseCommitmentKey, retryPromise, teleport, teleportDot, transformOrderForContract, tronChainIds, tronNile };
23502
23702
  //# sourceMappingURL=index.js.map
23503
23703
  //# sourceMappingURL=index.js.map