@hyperbridge/sdk 2.8.18 → 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.
@@ -3696,6 +3696,11 @@ interface SubmitBidOptions {
3696
3696
  */
3697
3697
  paymasterAndData?: HexString$1;
3698
3698
  }
3699
+ /**
3700
+ * The fields of a bid UserOperation that decide its `preVerificationGas`: everything the
3701
+ * solver signs except the signature and the `preVerificationGas` itself.
3702
+ */
3703
+ type BidPreVerificationGasParams = Pick<SubmitBidOptions, "solverAccount" | "nonce" | "entryPointAddress" | "callGasLimit" | "verificationGasLimit" | "maxFeePerGas" | "maxPriorityFeePerGas" | "callData" | "paymasterAndData">;
3699
3704
  interface EstimateFillOrderParams {
3700
3705
  order: Order;
3701
3706
  /** Positional input takes. Required with custom outputs; otherwise estimates a full fill at the order's rate. */
@@ -5680,6 +5685,14 @@ declare class IntentGateway {
5680
5685
  * @returns A {@link FillOrderEstimate} with all gas components.
5681
5686
  */
5682
5687
  estimateFillOrder(params: EstimateFillOrderParams): Promise<FillOrderEstimate>;
5688
+ /**
5689
+ * Asks the bundler for the `preVerificationGas` of a bid as it will be signed, priced at
5690
+ * the gas price its bundle pays. Call it with the final calldata and `paymasterAndData`,
5691
+ * before {@link prepareSubmitBid} signs the op.
5692
+ *
5693
+ * Delegates to {@link GasEstimator.estimateBidPreVerificationGas}.
5694
+ */
5695
+ estimateBidPreVerificationGas(params: BidPreVerificationGasParams): Promise<bigint>;
5683
5696
  /**
5684
5697
  * Quotes the solver fee for an order using the same policy {@link execute} /
5685
5698
  * {@link executeBest} apply when `order.fees` is `0n`.
@@ -11558,4 +11571,4 @@ declare function teleport(teleport_param: {
11558
11571
  extrinsics?: Array<SubmittableExtrinsic<"promise", ISubmittableResult>>;
11559
11572
  }): Promise<ReadableStream<HyperbridgeTxEvents>>;
11560
11573
 
11561
- export { ADDRESS_ZERO, type AllStatusKey, type AssetTeleported, type AssetTeleportedResponse, type AvailableLiquidity, type Bid, type BidStorageEntry, type BidSubmissionResult, type BlockMetadata, type BridgeParams, type BridgeStep, type BundlerGasEstimate, BundlerMethod, type BuyAndSellRates, type BytesLikeHex, CONTRACT_VERSION_ABI, type CancelEvent, type CancelOptions, type CancelOrderOptions, type CancelQuote, type ChainConfig, type ChainConfigData, ChainConfigService, Chains, type ClientConfig, type ConfiguredAssetSymbol, type ConfiguredAssetSymbolInput, CryptoUtils, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DOMAIN_TYPEHASH, DUMMY_PRIVATE_KEY, type DecodedFillOrder, type DecodedOrderPlacedLog, type DecodedPostRequestEvent, type DecodedPostResponseEvent, type Deployment, type DispatchGet, type DispatchInfo, type DispatchPost, ERC20Method, type ERC7821Call, ERC7821_BATCH_MODE, type Erc4626VaultConfigData, type EstimateFillOrderParams, type EstimateGasCallData, EvmChain, type EvmChainParams, ABI as EvmHostABI, EvmLanguage, type ExecuteIntentOrderOptions, type ExecutionResult, FILL_ORDER_SELECTOR, type FillOptions, type FillOrderEstimate, type FillerBid, type FillerConfig, type GetRequestResponse, type GetRequestWithStatus, type GetResponseByRequestIdResponse, type GetResponseStorageValues, type HexString$1 as HexString, type HostParams, HyperClientStatus, HyperFungibleToken, HyperFungibleTokenABI, HyperFxOrderbook, type HyperbridgeTxEvents, type IBatchConsensusAndGetResponseMessage, type IBatchConsensusAndPostRequestMessage, type IChain, type IConfig, type IConsensusMessage, type IEvmChain, type IEvmConfig, type IGetRequest, type IGetRequestMessage, type IGetResponse, type IGetResponseMessage, type IHyperbridgeConfig, type IIsmpMessage, type IMessage, INCLUSION_TIMEOUT_MS, type IPharosConfig, type IPolkadotHubConfig, type IPostRequest, type IPostResponse, type IProof, type IRequestMessage, type ISubstrateConfig, type ITimeoutPostRequestMessage, type IndexerQueryClient, IntentGateway, ABI$1 as IntentGatewayABI, type IntentGatewayContext, type IntentGatewayParams, IntentOrderStatus, type IntentOrderStatusKey, type IntentOrderStatusUpdate, type IntentQuoteLeg, IntentsCoprocessor, IsmpClient, type IsmpRequest, MAX_DECLARED_ENTRIES, MOCK_ADDRESS, ORDERBOOK_DECIMALS, ORDERBOOK_QUERIES, ORDERBOOK_URLS, ORDER_V2_PARAM_TYPE, type Order, type OrderFeesQuote, type OrderResponse, OrderStatus, OrderStatusChecker, type OrderStatusMetadata, type OrderWithStatus, type OrderbookBook, type OrderbookLevelQuote, type OrderbookQuoteFill, OrderbookQuoteNotConvergedError, type OrderbookRate, OrderbookRequestError, type OrderbookRoute, type OrderbookRouteKind, type OrderbookRouteLiquidity, type OrderbookSide, type OrderbookSwapQuote, type OrderbookTopOfBook, PACKED_USEROP_TYPEHASH, PERMIT2_SPONSORSHIP_BYTES, PLACE_ORDER_SELECTOR, type PackedUserOperation, type Params, type PaymentInfo, type PessimisticQuoteIntentResult, type PhantomBidDeclaration, type PhantomBidPaymasterAndData, type PhantomBidSponsorship, PharosChain, type PharosChainParams, PolkadotHubChain, type PolkadotHubChainParams, type PostRequestStatus, type PostRequestTimeoutStatus, type PostRequestWithStatus, type QueryBuyAndSellRatesParams, type QuoteIntentParams, type QuoteIntentResult, type QuoteNativeResult, type QuoteResult, type QuoteUniswapParams, type QuoteUniswapResult, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, type RateFillPreview, type RequestBody, type RequestCommitment, RequestKind, type RequestResponse, RequestStatus, type RequestStatusKey, type RequestStatusWithMetadata, type ResponseCommitmentWithValues, type ResumeIntentOrderOptions, type RetryConfig, type RpcBidInfo, SELECT_SOLVER_TYPEHASH, STATE_COMMITMENTS_SLOT, SUPPORTED_INTENTS_VERSION, type SelectBidResult, type SelectOptions, type SigningAccount, type StateMachineHeight, type StateMachineId, type StateMachineIdParams, type StateMachineResponse, type StateMachineUpdate, type StorageFacade, type SubmitBidOptions, SubstrateChain, Swap, TESTNET_CHAINS, type TeleportParams, TeleportStatus, TimeoutStatus, type TimeoutStatusKey, TokenGateway, type TokenGatewayAssetTeleportedResponse, type TokenGatewayAssetTeleportedWithStatus, type TokenInfo, type TokenPrice, type TokenPricesResponse, type Transaction, TronChain, type TronChainParams, USE_ETHERSCAN_CHAINS, type UniswapProtocol, type UniswapQuote, type UniswapQuoteToken, type UniswapTradeType, UnsupportedLiquidityAssetError, UnsupportedLiquidityChainError, WrappedHyperFungibleTokenABI, type XcmGatewayParams, __test, adjustDecimals, assertGatewayRelease, bytes20ToBytes32, bytes32ToBytes20, calculateAllowanceMappingLocation, calculateBalanceMappingLocation, chainConfigs, constructRedeemEscrowRequestBody, constructRefundEscrowRequestBody, convertCodecToIGetRequest, convertCodecToIProof, convertIGetRequestToCodec, convertIProofToCodec, convertStateIdToStateMachineId, convertStateMachineEnumToString, convertStateMachineIdToEnum, createEvmChain, createQueryClient, decodeAcceptedSourceChains, decodeERC7821ExecuteBatch, decodeFillOrder, decodePhantomBidDeclaration, decodePhantomBidPaymasterAndData, decodeUserOpScale, deriveHttpUrl, encodeAcceptedSourceChains, encodeERC7821ExecuteBatch, encodeFillOrder, encodeISMPMessage, encodePhantomBidDeclaration, encodePhantomBidPaymasterAndData, encodeStateMachineId, encodeUserOpScale, encodeWithdrawalRequest, estimateGasForPost, fetchPrice, fetchSourceProof, generateRootWithProof, getChainId, getConfigByStateMachineId, getContractCallInput, getContractCallInputs, getGasPriceFromEtherscan, getOrFetchStorageSlot, getOrderPlacedFromTx, getPostRequestEventFromTx, getPostResponseEventFromTx, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, getViemChain, hexToString, hyperbridgeAddress, isCanonicalEvmToken, maxBigInt, normalizeAddressForEvmBytes32, normalizeAddressForStateMachine, normalizeEvmAddress, normalizeEvmChainId, normalizeStateMachineId, orderCommitment, orderbookUrlFor, parseStateMachineId, pharosAtlantic, pharosMainnet, polkadotAssetHubPaseo, polkadotHubMainnet, poolSlug, postRequestCommitment, previewRateFill, queryAssetTeleported, queryGetRequest, queryPostRequest, quoteUniswap, readLegEscrow, readLegPartialFill, requestCommitmentKey, responseCommitmentKey, retryPromise, sortPoolSymbols, supportsRateFills, teleport, teleportDot, transformOrderForContract, tronChainIds, tronNile };
11574
+ export { ADDRESS_ZERO, type AllStatusKey, type AssetTeleported, type AssetTeleportedResponse, type AvailableLiquidity, type Bid, type BidPreVerificationGasParams, type BidStorageEntry, type BidSubmissionResult, type BlockMetadata, type BridgeParams, type BridgeStep, type BundlerGasEstimate, BundlerMethod, type BuyAndSellRates, type BytesLikeHex, CONTRACT_VERSION_ABI, type CancelEvent, type CancelOptions, type CancelOrderOptions, type CancelQuote, type ChainConfig, type ChainConfigData, ChainConfigService, Chains, type ClientConfig, type ConfiguredAssetSymbol, type ConfiguredAssetSymbolInput, CryptoUtils, DEFAULT_ADDRESS, DEFAULT_GRAFFITI, DOMAIN_TYPEHASH, DUMMY_PRIVATE_KEY, type DecodedFillOrder, type DecodedOrderPlacedLog, type DecodedPostRequestEvent, type DecodedPostResponseEvent, type Deployment, type DispatchGet, type DispatchInfo, type DispatchPost, ERC20Method, type ERC7821Call, ERC7821_BATCH_MODE, type Erc4626VaultConfigData, type EstimateFillOrderParams, type EstimateGasCallData, EvmChain, type EvmChainParams, ABI as EvmHostABI, EvmLanguage, type ExecuteIntentOrderOptions, type ExecutionResult, FILL_ORDER_SELECTOR, type FillOptions, type FillOrderEstimate, type FillerBid, type FillerConfig, type GetRequestResponse, type GetRequestWithStatus, type GetResponseByRequestIdResponse, type GetResponseStorageValues, type HexString$1 as HexString, type HostParams, HyperClientStatus, HyperFungibleToken, HyperFungibleTokenABI, HyperFxOrderbook, type HyperbridgeTxEvents, type IBatchConsensusAndGetResponseMessage, type IBatchConsensusAndPostRequestMessage, type IChain, type IConfig, type IConsensusMessage, type IEvmChain, type IEvmConfig, type IGetRequest, type IGetRequestMessage, type IGetResponse, type IGetResponseMessage, type IHyperbridgeConfig, type IIsmpMessage, type IMessage, INCLUSION_TIMEOUT_MS, type IPharosConfig, type IPolkadotHubConfig, type IPostRequest, type IPostResponse, type IProof, type IRequestMessage, type ISubstrateConfig, type ITimeoutPostRequestMessage, type IndexerQueryClient, IntentGateway, ABI$1 as IntentGatewayABI, type IntentGatewayContext, type IntentGatewayParams, IntentOrderStatus, type IntentOrderStatusKey, type IntentOrderStatusUpdate, type IntentQuoteLeg, IntentsCoprocessor, IsmpClient, type IsmpRequest, MAX_DECLARED_ENTRIES, MOCK_ADDRESS, ORDERBOOK_DECIMALS, ORDERBOOK_QUERIES, ORDERBOOK_URLS, ORDER_V2_PARAM_TYPE, type Order, type OrderFeesQuote, type OrderResponse, OrderStatus, OrderStatusChecker, type OrderStatusMetadata, type OrderWithStatus, type OrderbookBook, type OrderbookLevelQuote, type OrderbookQuoteFill, OrderbookQuoteNotConvergedError, type OrderbookRate, OrderbookRequestError, type OrderbookRoute, type OrderbookRouteKind, type OrderbookRouteLiquidity, type OrderbookSide, type OrderbookSwapQuote, type OrderbookTopOfBook, PACKED_USEROP_TYPEHASH, PERMIT2_SPONSORSHIP_BYTES, PLACE_ORDER_SELECTOR, type PackedUserOperation, type Params, type PaymentInfo, type PessimisticQuoteIntentResult, type PhantomBidDeclaration, type PhantomBidPaymasterAndData, type PhantomBidSponsorship, PharosChain, type PharosChainParams, PolkadotHubChain, type PolkadotHubChainParams, type PostRequestStatus, type PostRequestTimeoutStatus, type PostRequestWithStatus, type QueryBuyAndSellRatesParams, type QuoteIntentParams, type QuoteIntentResult, type QuoteNativeResult, type QuoteResult, type QuoteUniswapParams, type QuoteUniswapResult, REQUEST_COMMITMENTS_SLOT, REQUEST_RECEIPTS_SLOT, RESPONSE_COMMITMENTS_SLOT, RESPONSE_RECEIPTS_SLOT, type RateFillPreview, type RequestBody, type RequestCommitment, RequestKind, type RequestResponse, RequestStatus, type RequestStatusKey, type RequestStatusWithMetadata, type ResponseCommitmentWithValues, type ResumeIntentOrderOptions, type RetryConfig, type RpcBidInfo, SELECT_SOLVER_TYPEHASH, STATE_COMMITMENTS_SLOT, SUPPORTED_INTENTS_VERSION, type SelectBidResult, type SelectOptions, type SigningAccount, type StateMachineHeight, type StateMachineId, type StateMachineIdParams, type StateMachineResponse, type StateMachineUpdate, type StorageFacade, type SubmitBidOptions, SubstrateChain, Swap, TESTNET_CHAINS, type TeleportParams, TeleportStatus, TimeoutStatus, type TimeoutStatusKey, TokenGateway, type TokenGatewayAssetTeleportedResponse, type TokenGatewayAssetTeleportedWithStatus, type TokenInfo, type TokenPrice, type TokenPricesResponse, type Transaction, TronChain, type TronChainParams, USE_ETHERSCAN_CHAINS, type UniswapProtocol, type UniswapQuote, type UniswapQuoteToken, type UniswapTradeType, UnsupportedLiquidityAssetError, UnsupportedLiquidityChainError, WrappedHyperFungibleTokenABI, type XcmGatewayParams, __test, adjustDecimals, assertGatewayRelease, bytes20ToBytes32, bytes32ToBytes20, calculateAllowanceMappingLocation, calculateBalanceMappingLocation, chainConfigs, constructRedeemEscrowRequestBody, constructRefundEscrowRequestBody, convertCodecToIGetRequest, convertCodecToIProof, convertIGetRequestToCodec, convertIProofToCodec, convertStateIdToStateMachineId, convertStateMachineEnumToString, convertStateMachineIdToEnum, createEvmChain, createQueryClient, decodeAcceptedSourceChains, decodeERC7821ExecuteBatch, decodeFillOrder, decodePhantomBidDeclaration, decodePhantomBidPaymasterAndData, decodeUserOpScale, deriveHttpUrl, encodeAcceptedSourceChains, encodeERC7821ExecuteBatch, encodeFillOrder, encodeISMPMessage, encodePhantomBidDeclaration, encodePhantomBidPaymasterAndData, encodeStateMachineId, encodeUserOpScale, encodeWithdrawalRequest, estimateGasForPost, fetchPrice, fetchSourceProof, generateRootWithProof, getChainId, getConfigByStateMachineId, getContractCallInput, getContractCallInputs, getGasPriceFromEtherscan, getOrFetchStorageSlot, getOrderPlacedFromTx, getPostRequestEventFromTx, getPostResponseEventFromTx, getRequestCommitment, getStateCommitmentFieldSlot, getStateCommitmentSlot, getStorageSlot, getViemChain, hexToString, hyperbridgeAddress, isCanonicalEvmToken, maxBigInt, normalizeAddressForEvmBytes32, normalizeAddressForStateMachine, normalizeEvmAddress, normalizeEvmChainId, normalizeStateMachineId, orderCommitment, orderbookUrlFor, parseStateMachineId, pharosAtlantic, pharosMainnet, polkadotAssetHubPaseo, polkadotHubMainnet, poolSlug, postRequestCommitment, previewRateFill, queryAssetTeleported, queryGetRequest, queryPostRequest, quoteUniswap, readLegEscrow, readLegPartialFill, requestCommitmentKey, responseCommitmentKey, retryPromise, sortPoolSymbols, supportsRateFills, teleport, teleportDot, transformOrderForContract, tronChainIds, tronNile };
@@ -18313,6 +18313,16 @@ var NO_BUNDLER_FILL_GAS_BASE = 700000n;
18313
18313
  var NO_BUNDLER_FILL_GAS_PER_OUTPUT = 150000n;
18314
18314
  var NO_BUNDLER_PAYMASTER_VERIFICATION_GAS = 250000n;
18315
18315
  var NO_BUNDLER_PAYMASTER_POST_OP_GAS = 100000n;
18316
+ var BID_PVG_ESTIMATION_ACCOUNT_CODE = "0x60003560e01c631626ba7e1460145760206000f35b631626ba7e60e01b60005260206000f3";
18317
+ var SELECTED_BID_SIGNATURE_BYTES = 32 + 65 + 65;
18318
+ var BID_PVG_HEADROOM_PERCENT = 10n;
18319
+ var ESCROW_MAPPING_SLOT = 9n;
18320
+ function escrowSlot(commitment, leg) {
18321
+ const byCommitment = keccak256(
18322
+ encodeAbiParameters([{ type: "bytes32" }, { type: "uint256" }], [commitment, ESCROW_MAPPING_SLOT])
18323
+ );
18324
+ return keccak256(encodeAbiParameters([{ type: "uint256" }, { type: "bytes32" }], [BigInt(leg), byCommitment]));
18325
+ }
18316
18326
  var GasEstimator = class {
18317
18327
  /**
18318
18328
  * @param ctx - Shared IntentsV2 context providing the source and destination
@@ -18391,6 +18401,7 @@ var GasEstimator = class {
18391
18401
  assetsForOverrides.push({ token: feeTokenAsBytes32, amount: 0n });
18392
18402
  }
18393
18403
  const isSameChain = souceStateMachineId === destStateMachineId;
18404
+ const commitment = orderCommitment(order);
18394
18405
  const [stateOverridesResult, crossChainFees] = await Promise.all([
18395
18406
  this.ctx.bundlerUrl ? this.buildStateOverride({
18396
18407
  accountAddress: solverAccountAddress,
@@ -18398,7 +18409,16 @@ var GasEstimator = class {
18398
18409
  outputAssets: assetsForOverrides,
18399
18410
  spenderAddress: intentGatewayV2Address,
18400
18411
  intentGatewayV2Address,
18401
- entryPointAddress
18412
+ entryPointAddress,
18413
+ // A fee quote runs before the order is placed, so nothing is escrowed under
18414
+ // its commitment yet. Cross-chain fills release escrow on the source chain.
18415
+ escrow: isSameChain ? {
18416
+ commitment,
18417
+ inputs: order.inputs.map((input) => ({
18418
+ token: normalizeAddressForEvmBytes32(input.token),
18419
+ amount: input.amount
18420
+ }))
18421
+ } : void 0
18402
18422
  }) : Promise.resolve({ viem: [], bundler: {} }),
18403
18423
  isSameChain ? Promise.resolve({ postRequestFee: 0n, relayerFeeInSourceFeeToken: 0n }) : this.estimateCrossChainFees(
18404
18424
  sourceFeeToken,
@@ -18427,10 +18447,8 @@ var GasEstimator = class {
18427
18447
  const maxFeeBumpPercent = params.maxFeePerGasBumpPercent ?? 10;
18428
18448
  let maxPriorityFeePerGas = gasPrice + gasPrice * BigInt(priorityFeeBumpPercent) / 100n;
18429
18449
  let maxFeePerGas = gasPrice + gasPrice * BigInt(maxFeeBumpPercent) / 100n;
18430
- const orderForEstimation = { ...order, session: solverAccountAddress };
18431
- const commitment = orderCommitment(orderForEstimation);
18432
18450
  await assertGatewayRelease(this.ctx.dest.client, intentGatewayV2Address);
18433
- const fillOrderCalldata = encodeFillOrder(transformOrderForContract(orderForEstimation), fillOptions);
18451
+ const fillOrderCalldata = encodeFillOrder(transformOrderForContract(order), fillOptions);
18434
18452
  let callGasLimit = 500000n;
18435
18453
  let verificationGasLimit = 100000n;
18436
18454
  let preVerificationGas = 100000n;
@@ -18442,7 +18460,7 @@ var GasEstimator = class {
18442
18460
  ...params.prependCalls ?? [],
18443
18461
  { target: intentGatewayV2Address, value: totalNativeValue, data: fillOrderCalldata }
18444
18462
  ]);
18445
- const accountGasLimits = CryptoUtils.packGasLimits(100000n, callGasLimit);
18463
+ const accountGasLimits = CryptoUtils.packGasLimits(0n, 0n);
18446
18464
  const gasFees = CryptoUtils.packGasFees(maxPriorityFeePerGas, maxFeePerGas);
18447
18465
  const nonce = 0n;
18448
18466
  const preliminaryUserOp = {
@@ -18451,7 +18469,7 @@ var GasEstimator = class {
18451
18469
  initCode: "0x",
18452
18470
  callData,
18453
18471
  accountGasLimits,
18454
- preVerificationGas: 100000n,
18472
+ preVerificationGas: 0n,
18455
18473
  gasFees,
18456
18474
  paymasterAndData: "0x",
18457
18475
  signature: "0x"
@@ -18581,6 +18599,53 @@ var GasEstimator = class {
18581
18599
  inputs
18582
18600
  };
18583
18601
  }
18602
+ /**
18603
+ * Asks the bundler for the `preVerificationGas` of the bid UserOperation that will
18604
+ * actually be signed, with every funding call, approval and signature byte in it.
18605
+ *
18606
+ * On an L2, `preVerificationGas` also pays the L1 data fee for the op's bytes, a fixed
18607
+ * amount of wei that the bundler converts to gas at the price the op pays. A bundler
18608
+ * admits an op priced at its `maxFeePerGas`, but bundles it at the base fee plus its
18609
+ * priority fee, where the same wei costs more gas. An op sized only for admission is
18610
+ * accepted and then skipped in every bundle until it expires. The estimate is taken
18611
+ * at the bundle's price: the latest base fee plus the op's priority fee, capped at its
18612
+ * `maxFeePerGas`.
18613
+ *
18614
+ * The solver account's code is overridden with {@link BID_PVG_ESTIMATION_ACCOUNT_CODE}
18615
+ * for the call, so only the bytes are priced and the fill itself is not simulated.
18616
+ *
18617
+ * @param params - The bid's fields as they will be signed.
18618
+ * @returns The `preVerificationGas` to sign, with {@link BID_PVG_HEADROOM_PERCENT} added.
18619
+ * @throws If no bundler is configured or the bundler rejects the estimate.
18620
+ */
18621
+ async estimateBidPreVerificationGas(params) {
18622
+ const { solverAccount, maxFeePerGas, maxPriorityFeePerGas } = params;
18623
+ const latestBlock = await this.ctx.dest.client.getBlock({ blockTag: "latest" });
18624
+ const baseFeePerGas = latestBlock.baseFeePerGas;
18625
+ const bundlePrice = baseFeePerGas == null || baseFeePerGas + maxPriorityFeePerGas > maxFeePerGas ? maxFeePerGas : baseFeePerGas + maxPriorityFeePerGas;
18626
+ const priorityFee = maxPriorityFeePerGas < bundlePrice ? maxPriorityFeePerGas : bundlePrice;
18627
+ const userOp = {
18628
+ sender: solverAccount,
18629
+ nonce: params.nonce,
18630
+ initCode: "0x",
18631
+ callData: params.callData,
18632
+ accountGasLimits: CryptoUtils.packGasLimits(params.verificationGasLimit, params.callGasLimit),
18633
+ // Bundlers return a non-zero preVerificationGas as given rather than estimating it.
18634
+ preVerificationGas: 0n,
18635
+ gasFees: CryptoUtils.packGasFees(priorityFee, bundlePrice),
18636
+ paymasterAndData: params.paymasterAndData ?? "0x",
18637
+ signature: `0x${"ff".repeat(SELECTED_BID_SIGNATURE_BYTES)}`
18638
+ };
18639
+ const estimate = await this.crypto.sendBundler(
18640
+ BundlerMethod.ETH_ESTIMATE_USER_OPERATION_GAS,
18641
+ [
18642
+ CryptoUtils.prepareBundlerCall(userOp),
18643
+ params.entryPointAddress,
18644
+ { [solverAccount]: { code: BID_PVG_ESTIMATION_ACCOUNT_CODE } }
18645
+ ]
18646
+ );
18647
+ return BigInt(estimate.preVerificationGas) * (100n + BID_PVG_HEADROOM_PERCENT) / 100n;
18648
+ }
18584
18649
  /**
18585
18650
  * Estimates the cross-chain ISMP POST request fee (the relayer fee for the
18586
18651
  * RedeemEscrow message), in both the source and destination fee tokens.
@@ -18633,20 +18698,38 @@ var GasEstimator = class {
18633
18698
  * @returns An object with `viem` and `bundler` state-override collections.
18634
18699
  */
18635
18700
  async buildStateOverride(params) {
18636
- const { accountAddress, chain, outputAssets, spenderAddress, intentGatewayV2Address, entryPointAddress } = params;
18637
- const testValue = toHex(maxUint256 / 2n, { size: 32 });
18701
+ const {
18702
+ accountAddress,
18703
+ chain,
18704
+ outputAssets,
18705
+ spenderAddress,
18706
+ intentGatewayV2Address,
18707
+ entryPointAddress,
18708
+ escrow
18709
+ } = params;
18710
+ const testValue = toHex(2n ** 128n, { size: 32 });
18638
18711
  const viemOverrides = [];
18639
18712
  const bundlerOverrides = {};
18640
18713
  if (intentGatewayV2Address) {
18641
18714
  const paramsSlot5 = pad(toHex(5n), { size: 32 });
18642
18715
  const dispatcherAddress = this.ctx.dest.configService.getCalldispatcherAddress(chain);
18643
18716
  const newSlot5Value = "0x" + "0".repeat(22) + "00" + dispatcherAddress.slice(2).toLowerCase();
18717
+ const gatewayDiffs = [{ slot: paramsSlot5, value: newSlot5Value }];
18718
+ for (const [leg, input] of (escrow?.inputs ?? []).entries()) {
18719
+ gatewayDiffs.push({
18720
+ slot: escrowSlot(escrow.commitment, leg),
18721
+ value: toHex(input.amount, { size: 32 })
18722
+ });
18723
+ }
18724
+ const releasesNative = escrow?.inputs.some((input) => bytes32ToBytes20(input.token) === ADDRESS_ZERO2);
18644
18725
  viemOverrides.push({
18645
18726
  address: intentGatewayV2Address,
18646
- stateDiff: [{ slot: paramsSlot5, value: newSlot5Value }]
18727
+ ...releasesNative ? { balance: 2n ** 128n } : {},
18728
+ stateDiff: gatewayDiffs
18647
18729
  });
18648
18730
  bundlerOverrides[intentGatewayV2Address] = {
18649
- stateDiff: { [paramsSlot5]: newSlot5Value }
18731
+ ...releasesNative ? { balance: testValue } : {},
18732
+ stateDiff: Object.fromEntries(gatewayDiffs.map(({ slot, value }) => [slot, value]))
18650
18733
  };
18651
18734
  }
18652
18735
  if (entryPointAddress) {
@@ -18677,6 +18760,25 @@ var GasEstimator = class {
18677
18760
  bundlerOverrides[result.address] = { stateDiff: result.bundlerStateDiffs };
18678
18761
  }
18679
18762
  }
18763
+ if (intentGatewayV2Address && escrow) {
18764
+ const gatewayBalances = await Promise.all(
18765
+ escrow.inputs.map((input) => this.tokenBalanceSlot(input.token, intentGatewayV2Address, chain))
18766
+ );
18767
+ for (const override of gatewayBalances) {
18768
+ if (!override) continue;
18769
+ const existing = viemOverrides.find((entry) => entry.address === override.address && entry.stateDiff);
18770
+ if (existing) existing.stateDiff.push({ slot: override.slot, value: testValue });
18771
+ else
18772
+ viemOverrides.push({
18773
+ address: override.address,
18774
+ stateDiff: [{ slot: override.slot, value: testValue }]
18775
+ });
18776
+ bundlerOverrides[override.address] = {
18777
+ ...bundlerOverrides[override.address],
18778
+ stateDiff: { ...bundlerOverrides[override.address]?.stateDiff, [override.slot]: testValue }
18779
+ };
18780
+ }
18781
+ }
18680
18782
  const solverAccountContract = this.ctx.dest.configService.getSolverAccountAddress(chain);
18681
18783
  if (solverAccountContract) {
18682
18784
  try {
@@ -18699,6 +18801,21 @@ var GasEstimator = class {
18699
18801
  }
18700
18802
  return { viem: viemOverrides, bundler: bundlerOverrides };
18701
18803
  }
18804
+ /**
18805
+ * The balance slot of `holder` in an ERC-20 token, for overriding. `null` for the native
18806
+ * token or when the slot cannot be discovered.
18807
+ */
18808
+ async tokenBalanceSlot(tokenHex, holder, chain) {
18809
+ const tokenAddress = bytes32ToBytes20(tokenHex);
18810
+ if (tokenAddress === ADDRESS_ZERO2) return null;
18811
+ try {
18812
+ const balanceData = "0x70a08231" /* BALANCE_OF */ + bytes20ToBytes32(holder).slice(2);
18813
+ const slot = await getOrFetchStorageSlot(this.ctx.dest.client, chain, tokenAddress, balanceData);
18814
+ return slot ? { address: tokenAddress, slot } : null;
18815
+ } catch {
18816
+ return null;
18817
+ }
18818
+ }
18702
18819
  /**
18703
18820
  * Resolves the balance and allowance storage slot overrides for a single
18704
18821
  * ERC-20 token in parallel. Returns `null` for native-ETH tokens or when
@@ -19812,6 +19929,16 @@ var IntentGateway = class _IntentGateway {
19812
19929
  async estimateFillOrder(params) {
19813
19930
  return this.gasEstimator.estimateFillOrder(params);
19814
19931
  }
19932
+ /**
19933
+ * Asks the bundler for the `preVerificationGas` of a bid as it will be signed, priced at
19934
+ * the gas price its bundle pays. Call it with the final calldata and `paymasterAndData`,
19935
+ * before {@link prepareSubmitBid} signs the op.
19936
+ *
19937
+ * Delegates to {@link GasEstimator.estimateBidPreVerificationGas}.
19938
+ */
19939
+ async estimateBidPreVerificationGas(params) {
19940
+ return this.gasEstimator.estimateBidPreVerificationGas(params);
19941
+ }
19815
19942
  /**
19816
19943
  * Quotes the solver fee for an order using the same policy {@link execute} /
19817
19944
  * {@link executeBest} apply when `order.fees` is `0n`.