@hyperbridge/sdk 2.8.17 → 2.8.19

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.
@@ -18264,6 +18264,16 @@ var NO_BUNDLER_FILL_GAS_BASE = 700000n;
18264
18264
  var NO_BUNDLER_FILL_GAS_PER_OUTPUT = 150000n;
18265
18265
  var NO_BUNDLER_PAYMASTER_VERIFICATION_GAS = 250000n;
18266
18266
  var NO_BUNDLER_PAYMASTER_POST_OP_GAS = 100000n;
18267
+ var BID_PVG_ESTIMATION_ACCOUNT_CODE = "0x60003560e01c631626ba7e1460145760206000f35b631626ba7e60e01b60005260206000f3";
18268
+ var SELECTED_BID_SIGNATURE_BYTES = 32 + 65 + 65;
18269
+ var BID_PVG_HEADROOM_PERCENT = 10n;
18270
+ var ESCROW_MAPPING_SLOT = 9n;
18271
+ function escrowSlot(commitment, leg) {
18272
+ const byCommitment = viem.keccak256(
18273
+ viem.encodeAbiParameters([{ type: "bytes32" }, { type: "uint256" }], [commitment, ESCROW_MAPPING_SLOT])
18274
+ );
18275
+ return viem.keccak256(viem.encodeAbiParameters([{ type: "uint256" }, { type: "bytes32" }], [BigInt(leg), byCommitment]));
18276
+ }
18267
18277
  var GasEstimator = class {
18268
18278
  /**
18269
18279
  * @param ctx - Shared IntentsV2 context providing the source and destination
@@ -18342,6 +18352,7 @@ var GasEstimator = class {
18342
18352
  assetsForOverrides.push({ token: feeTokenAsBytes32, amount: 0n });
18343
18353
  }
18344
18354
  const isSameChain = souceStateMachineId === destStateMachineId;
18355
+ const commitment = orderCommitment(order);
18345
18356
  const [stateOverridesResult, crossChainFees] = await Promise.all([
18346
18357
  this.ctx.bundlerUrl ? this.buildStateOverride({
18347
18358
  accountAddress: solverAccountAddress,
@@ -18349,7 +18360,16 @@ var GasEstimator = class {
18349
18360
  outputAssets: assetsForOverrides,
18350
18361
  spenderAddress: intentGatewayV2Address,
18351
18362
  intentGatewayV2Address,
18352
- entryPointAddress
18363
+ entryPointAddress,
18364
+ // A fee quote runs before the order is placed, so nothing is escrowed under
18365
+ // its commitment yet. Cross-chain fills release escrow on the source chain.
18366
+ escrow: isSameChain ? {
18367
+ commitment,
18368
+ inputs: order.inputs.map((input) => ({
18369
+ token: normalizeAddressForEvmBytes32(input.token),
18370
+ amount: input.amount
18371
+ }))
18372
+ } : void 0
18353
18373
  }) : Promise.resolve({ viem: [], bundler: {} }),
18354
18374
  isSameChain ? Promise.resolve({ postRequestFee: 0n, relayerFeeInSourceFeeToken: 0n }) : this.estimateCrossChainFees(
18355
18375
  sourceFeeToken,
@@ -18378,10 +18398,8 @@ var GasEstimator = class {
18378
18398
  const maxFeeBumpPercent = params.maxFeePerGasBumpPercent ?? 10;
18379
18399
  let maxPriorityFeePerGas = gasPrice + gasPrice * BigInt(priorityFeeBumpPercent) / 100n;
18380
18400
  let maxFeePerGas = gasPrice + gasPrice * BigInt(maxFeeBumpPercent) / 100n;
18381
- const orderForEstimation = { ...order, session: solverAccountAddress };
18382
- const commitment = orderCommitment(orderForEstimation);
18383
18401
  await assertGatewayRelease(this.ctx.dest.client, intentGatewayV2Address);
18384
- const fillOrderCalldata = encodeFillOrder(transformOrderForContract(orderForEstimation), fillOptions);
18402
+ const fillOrderCalldata = encodeFillOrder(transformOrderForContract(order), fillOptions);
18385
18403
  let callGasLimit = 500000n;
18386
18404
  let verificationGasLimit = 100000n;
18387
18405
  let preVerificationGas = 100000n;
@@ -18393,7 +18411,7 @@ var GasEstimator = class {
18393
18411
  ...params.prependCalls ?? [],
18394
18412
  { target: intentGatewayV2Address, value: totalNativeValue, data: fillOrderCalldata }
18395
18413
  ]);
18396
- const accountGasLimits = CryptoUtils.packGasLimits(100000n, callGasLimit);
18414
+ const accountGasLimits = CryptoUtils.packGasLimits(0n, 0n);
18397
18415
  const gasFees = CryptoUtils.packGasFees(maxPriorityFeePerGas, maxFeePerGas);
18398
18416
  const nonce = 0n;
18399
18417
  const preliminaryUserOp = {
@@ -18402,7 +18420,7 @@ var GasEstimator = class {
18402
18420
  initCode: "0x",
18403
18421
  callData,
18404
18422
  accountGasLimits,
18405
- preVerificationGas: 100000n,
18423
+ preVerificationGas: 0n,
18406
18424
  gasFees,
18407
18425
  paymasterAndData: "0x",
18408
18426
  signature: "0x"
@@ -18532,6 +18550,53 @@ var GasEstimator = class {
18532
18550
  inputs
18533
18551
  };
18534
18552
  }
18553
+ /**
18554
+ * Asks the bundler for the `preVerificationGas` of the bid UserOperation that will
18555
+ * actually be signed, with every funding call, approval and signature byte in it.
18556
+ *
18557
+ * On an L2, `preVerificationGas` also pays the L1 data fee for the op's bytes, a fixed
18558
+ * amount of wei that the bundler converts to gas at the price the op pays. A bundler
18559
+ * admits an op priced at its `maxFeePerGas`, but bundles it at the base fee plus its
18560
+ * priority fee, where the same wei costs more gas. An op sized only for admission is
18561
+ * accepted and then skipped in every bundle until it expires. The estimate is taken
18562
+ * at the bundle's price: the latest base fee plus the op's priority fee, capped at its
18563
+ * `maxFeePerGas`.
18564
+ *
18565
+ * The solver account's code is overridden with {@link BID_PVG_ESTIMATION_ACCOUNT_CODE}
18566
+ * for the call, so only the bytes are priced and the fill itself is not simulated.
18567
+ *
18568
+ * @param params - The bid's fields as they will be signed.
18569
+ * @returns The `preVerificationGas` to sign, with {@link BID_PVG_HEADROOM_PERCENT} added.
18570
+ * @throws If no bundler is configured or the bundler rejects the estimate.
18571
+ */
18572
+ async estimateBidPreVerificationGas(params) {
18573
+ const { solverAccount, maxFeePerGas, maxPriorityFeePerGas } = params;
18574
+ const latestBlock = await this.ctx.dest.client.getBlock({ blockTag: "latest" });
18575
+ const baseFeePerGas = latestBlock.baseFeePerGas;
18576
+ const bundlePrice = baseFeePerGas == null || baseFeePerGas + maxPriorityFeePerGas > maxFeePerGas ? maxFeePerGas : baseFeePerGas + maxPriorityFeePerGas;
18577
+ const priorityFee = maxPriorityFeePerGas < bundlePrice ? maxPriorityFeePerGas : bundlePrice;
18578
+ const userOp = {
18579
+ sender: solverAccount,
18580
+ nonce: params.nonce,
18581
+ initCode: "0x",
18582
+ callData: params.callData,
18583
+ accountGasLimits: CryptoUtils.packGasLimits(params.verificationGasLimit, params.callGasLimit),
18584
+ // Bundlers return a non-zero preVerificationGas as given rather than estimating it.
18585
+ preVerificationGas: 0n,
18586
+ gasFees: CryptoUtils.packGasFees(priorityFee, bundlePrice),
18587
+ paymasterAndData: params.paymasterAndData ?? "0x",
18588
+ signature: `0x${"ff".repeat(SELECTED_BID_SIGNATURE_BYTES)}`
18589
+ };
18590
+ const estimate = await this.crypto.sendBundler(
18591
+ BundlerMethod.ETH_ESTIMATE_USER_OPERATION_GAS,
18592
+ [
18593
+ CryptoUtils.prepareBundlerCall(userOp),
18594
+ params.entryPointAddress,
18595
+ { [solverAccount]: { code: BID_PVG_ESTIMATION_ACCOUNT_CODE } }
18596
+ ]
18597
+ );
18598
+ return BigInt(estimate.preVerificationGas) * (100n + BID_PVG_HEADROOM_PERCENT) / 100n;
18599
+ }
18535
18600
  /**
18536
18601
  * Estimates the cross-chain ISMP POST request fee (the relayer fee for the
18537
18602
  * RedeemEscrow message), in both the source and destination fee tokens.
@@ -18584,20 +18649,38 @@ var GasEstimator = class {
18584
18649
  * @returns An object with `viem` and `bundler` state-override collections.
18585
18650
  */
18586
18651
  async buildStateOverride(params) {
18587
- const { accountAddress, chain, outputAssets, spenderAddress, intentGatewayV2Address, entryPointAddress } = params;
18588
- const testValue = viem.toHex(viem.maxUint256 / 2n, { size: 32 });
18652
+ const {
18653
+ accountAddress,
18654
+ chain,
18655
+ outputAssets,
18656
+ spenderAddress,
18657
+ intentGatewayV2Address,
18658
+ entryPointAddress,
18659
+ escrow
18660
+ } = params;
18661
+ const testValue = viem.toHex(2n ** 128n, { size: 32 });
18589
18662
  const viemOverrides = [];
18590
18663
  const bundlerOverrides = {};
18591
18664
  if (intentGatewayV2Address) {
18592
18665
  const paramsSlot5 = viem.pad(viem.toHex(5n), { size: 32 });
18593
18666
  const dispatcherAddress = this.ctx.dest.configService.getCalldispatcherAddress(chain);
18594
18667
  const newSlot5Value = "0x" + "0".repeat(22) + "00" + dispatcherAddress.slice(2).toLowerCase();
18668
+ const gatewayDiffs = [{ slot: paramsSlot5, value: newSlot5Value }];
18669
+ for (const [leg, input] of (escrow?.inputs ?? []).entries()) {
18670
+ gatewayDiffs.push({
18671
+ slot: escrowSlot(escrow.commitment, leg),
18672
+ value: viem.toHex(input.amount, { size: 32 })
18673
+ });
18674
+ }
18675
+ const releasesNative = escrow?.inputs.some((input) => bytes32ToBytes20(input.token) === ADDRESS_ZERO2);
18595
18676
  viemOverrides.push({
18596
18677
  address: intentGatewayV2Address,
18597
- stateDiff: [{ slot: paramsSlot5, value: newSlot5Value }]
18678
+ ...releasesNative ? { balance: 2n ** 128n } : {},
18679
+ stateDiff: gatewayDiffs
18598
18680
  });
18599
18681
  bundlerOverrides[intentGatewayV2Address] = {
18600
- stateDiff: { [paramsSlot5]: newSlot5Value }
18682
+ ...releasesNative ? { balance: testValue } : {},
18683
+ stateDiff: Object.fromEntries(gatewayDiffs.map(({ slot, value }) => [slot, value]))
18601
18684
  };
18602
18685
  }
18603
18686
  if (entryPointAddress) {
@@ -18628,6 +18711,25 @@ var GasEstimator = class {
18628
18711
  bundlerOverrides[result.address] = { stateDiff: result.bundlerStateDiffs };
18629
18712
  }
18630
18713
  }
18714
+ if (intentGatewayV2Address && escrow) {
18715
+ const gatewayBalances = await Promise.all(
18716
+ escrow.inputs.map((input) => this.tokenBalanceSlot(input.token, intentGatewayV2Address, chain))
18717
+ );
18718
+ for (const override of gatewayBalances) {
18719
+ if (!override) continue;
18720
+ const existing = viemOverrides.find((entry) => entry.address === override.address && entry.stateDiff);
18721
+ if (existing) existing.stateDiff.push({ slot: override.slot, value: testValue });
18722
+ else
18723
+ viemOverrides.push({
18724
+ address: override.address,
18725
+ stateDiff: [{ slot: override.slot, value: testValue }]
18726
+ });
18727
+ bundlerOverrides[override.address] = {
18728
+ ...bundlerOverrides[override.address],
18729
+ stateDiff: { ...bundlerOverrides[override.address]?.stateDiff, [override.slot]: testValue }
18730
+ };
18731
+ }
18732
+ }
18631
18733
  const solverAccountContract = this.ctx.dest.configService.getSolverAccountAddress(chain);
18632
18734
  if (solverAccountContract) {
18633
18735
  try {
@@ -18650,6 +18752,21 @@ var GasEstimator = class {
18650
18752
  }
18651
18753
  return { viem: viemOverrides, bundler: bundlerOverrides };
18652
18754
  }
18755
+ /**
18756
+ * The balance slot of `holder` in an ERC-20 token, for overriding. `null` for the native
18757
+ * token or when the slot cannot be discovered.
18758
+ */
18759
+ async tokenBalanceSlot(tokenHex, holder, chain) {
18760
+ const tokenAddress = bytes32ToBytes20(tokenHex);
18761
+ if (tokenAddress === ADDRESS_ZERO2) return null;
18762
+ try {
18763
+ const balanceData = "0x70a08231" /* BALANCE_OF */ + bytes20ToBytes32(holder).slice(2);
18764
+ const slot = await getOrFetchStorageSlot(this.ctx.dest.client, chain, tokenAddress, balanceData);
18765
+ return slot ? { address: tokenAddress, slot } : null;
18766
+ } catch {
18767
+ return null;
18768
+ }
18769
+ }
18653
18770
  /**
18654
18771
  * Resolves the balance and allowance storage slot overrides for a single
18655
18772
  * ERC-20 token in parallel. Returns `null` for native-ETH tokens or when
@@ -18961,18 +19078,6 @@ var OrderbookQuoteNotConvergedError = class extends Error {
18961
19078
  rounds;
18962
19079
  lastAmountIn;
18963
19080
  };
18964
- var InsufficientOrderbookLiquidityError = class extends Error {
18965
- constructor(route, maxFillableIn) {
18966
- super(
18967
- `The HyperFX orderbook cannot fill ${route.tokenIn} -> ${route.tokenOut} on ${route.sourceChain} -> ${route.destinationChain}; max fillable input is ${maxFillableIn} raw units`
18968
- );
18969
- this.route = route;
18970
- this.maxFillableIn = maxFillableIn;
18971
- this.name = "InsufficientOrderbookLiquidityError";
18972
- }
18973
- route;
18974
- maxFillableIn;
18975
- };
18976
19081
 
18977
19082
  // src/protocols/intents/orderbook/market.ts
18978
19083
  var MAX_EXACT_OUTPUT_ROUNDS = 16;
@@ -19028,8 +19133,9 @@ var OrderbookMarket = class {
19028
19133
  };
19029
19134
  }
19030
19135
  /**
19031
- * The fillable quote for an exact input, or for the input found to deliver an
19032
- * exact output, with the assets it trades.
19136
+ * The orderbook's quote for an exact input, or for the input found to deliver
19137
+ * an exact output, with the assets it trades. A route that cannot fill the
19138
+ * trade answers with an unfillable quote rather than an error.
19033
19139
  */
19034
19140
  async priceIntent(params, sourceChain, destinationChain, price, totals) {
19035
19141
  validateQuoteParams(params);
@@ -19038,10 +19144,7 @@ var OrderbookMarket = class {
19038
19144
  const route = toRoute(tokenIn, tokenOut);
19039
19145
  if (params.amountIn !== void 0) {
19040
19146
  const quote2 = await price(route, toOrderbookAmount(params.amountIn, tokenIn.decimals));
19041
- const { fillable, amountOut, maxFillableIn } = totals(quote2);
19042
- if (!fillable || fromOrderbookAmount(amountOut, tokenOut.decimals) === 0n) {
19043
- throw this.insufficient(route, maxFillableIn, tokenIn);
19044
- }
19147
+ totals(quote2);
19045
19148
  return { quote: quote2, tokenIn, tokenOut };
19046
19149
  }
19047
19150
  const targetOut = toOrderbookAmount(params.amountOut, tokenOut.decimals);
@@ -19103,18 +19206,21 @@ var OrderbookMarket = class {
19103
19206
  * filled better than its worst rate and re-pricing the rest of `targetOut` at
19104
19207
  * the input-to-output ratio that part filled at, until a quote delivers it.
19105
19208
  * That ratio is the orderbook's own, with the protocol fee already taken off.
19209
+ *
19210
+ * An output the route cannot deliver is answered by quoting an input past its
19211
+ * `maxFillableIn`, which the orderbook serves as unfillable: the smallest such
19212
+ * input guessed from the best rate, or one raw unit when no order serves it.
19106
19213
  */
19107
19214
  async quoteExactOutput(route, targetOut, tokenIn, price, totals) {
19108
19215
  const liquidity = await this.orderbook().routeLiquidity(route);
19109
- if (liquidity.bestRate === null) throw this.insufficient(route, 0n, tokenIn);
19110
19216
  const inputUnit = toOrderbookAmount(1n, tokenIn.decimals);
19111
- let amountIn = roundUpTo(requiredInput(liquidity.side, targetOut, liquidity.bestRate), inputUnit);
19217
+ let amountIn = liquidity.bestRate === null ? inputUnit : roundUpTo(requiredInput(liquidity.side, targetOut, liquidity.bestRate), inputUnit);
19112
19218
  let lastAmountIn = amountIn;
19113
19219
  for (let round = 0; round < MAX_EXACT_OUTPUT_ROUNDS; round++) {
19114
- if (amountIn > liquidity.maxFillableIn) throw this.insufficient(route, liquidity.maxFillableIn, tokenIn);
19115
19220
  const served = await price(route, amountIn);
19116
19221
  const quote = totals(served);
19117
19222
  if (quote.fillable && quote.amountOut >= targetOut) return served;
19223
+ if (!quote.fillable && amountIn > liquidity.maxFillableIn) return served;
19118
19224
  lastAmountIn = amountIn;
19119
19225
  const betterIn = quote.amountIn - quote.worstIn;
19120
19226
  const betterOut = quote.amountOut - quote.worstOut;
@@ -19127,9 +19233,6 @@ var OrderbookMarket = class {
19127
19233
  fromOrderbookAmount(lastAmountIn, tokenIn.decimals)
19128
19234
  );
19129
19235
  }
19130
- insufficient(route, maxFillableIn, tokenIn) {
19131
- return new InsufficientOrderbookLiquidityError(route, fromOrderbookAmount(maxFillableIn, tokenIn.decimals));
19132
- }
19133
19236
  assetByAddress(chain, address) {
19134
19237
  const resolvedChain = resolveChain(chain);
19135
19238
  return withDecimals(
@@ -19777,6 +19880,16 @@ var IntentGateway = class _IntentGateway {
19777
19880
  async estimateFillOrder(params) {
19778
19881
  return this.gasEstimator.estimateFillOrder(params);
19779
19882
  }
19883
+ /**
19884
+ * Asks the bundler for the `preVerificationGas` of a bid as it will be signed, priced at
19885
+ * the gas price its bundle pays. Call it with the final calldata and `paymasterAndData`,
19886
+ * before {@link prepareSubmitBid} signs the op.
19887
+ *
19888
+ * Delegates to {@link GasEstimator.estimateBidPreVerificationGas}.
19889
+ */
19890
+ async estimateBidPreVerificationGas(params) {
19891
+ return this.gasEstimator.estimateBidPreVerificationGas(params);
19892
+ }
19780
19893
  /**
19781
19894
  * Quotes the solver fee for an order using the same policy {@link execute} /
19782
19895
  * {@link executeBest} apply when `order.fees` is `0n`.
@@ -24680,7 +24793,6 @@ exports.HyperFungibleToken = HyperFungibleToken;
24680
24793
  exports.HyperFungibleTokenABI = HyperFungibleTokenABI;
24681
24794
  exports.HyperFxOrderbook = HyperFxOrderbook;
24682
24795
  exports.INCLUSION_TIMEOUT_MS = INCLUSION_TIMEOUT_MS;
24683
- exports.InsufficientOrderbookLiquidityError = InsufficientOrderbookLiquidityError;
24684
24796
  exports.IntentGateway = IntentGateway;
24685
24797
  exports.IntentGatewayABI = ABI3;
24686
24798
  exports.IntentOrderStatus = IntentOrderStatus;