@metamask/transaction-pay-controller 22.8.0 → 23.1.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/dist/strategy/across/across-submit.cjs +2 -1
  3. package/dist/strategy/across/across-submit.cjs.map +1 -1
  4. package/dist/strategy/across/across-submit.d.cts.map +1 -1
  5. package/dist/strategy/across/across-submit.d.mts.map +1 -1
  6. package/dist/strategy/across/across-submit.mjs +2 -1
  7. package/dist/strategy/across/across-submit.mjs.map +1 -1
  8. package/dist/strategy/fiat/fiat-quotes.cjs +2 -4
  9. package/dist/strategy/fiat/fiat-quotes.cjs.map +1 -1
  10. package/dist/strategy/fiat/fiat-quotes.mjs +2 -4
  11. package/dist/strategy/fiat/fiat-quotes.mjs.map +1 -1
  12. package/dist/strategy/relay/relay-submit.cjs +3 -2
  13. package/dist/strategy/relay/relay-submit.cjs.map +1 -1
  14. package/dist/strategy/relay/relay-submit.d.cts.map +1 -1
  15. package/dist/strategy/relay/relay-submit.d.mts.map +1 -1
  16. package/dist/strategy/relay/relay-submit.mjs +3 -2
  17. package/dist/strategy/relay/relay-submit.mjs.map +1 -1
  18. package/dist/tests/messenger-mock.cjs +3 -0
  19. package/dist/tests/messenger-mock.cjs.map +1 -1
  20. package/dist/tests/messenger-mock.d.cts +1 -0
  21. package/dist/tests/messenger-mock.d.cts.map +1 -1
  22. package/dist/tests/messenger-mock.d.mts +1 -0
  23. package/dist/tests/messenger-mock.d.mts.map +1 -1
  24. package/dist/tests/messenger-mock.mjs +3 -0
  25. package/dist/tests/messenger-mock.mjs.map +1 -1
  26. package/dist/types.cjs.map +1 -1
  27. package/dist/types.d.cts +3 -2
  28. package/dist/types.d.cts.map +1 -1
  29. package/dist/types.d.mts +3 -2
  30. package/dist/types.d.mts.map +1 -1
  31. package/dist/types.mjs.map +1 -1
  32. package/dist/utils/gas.cjs +2 -1
  33. package/dist/utils/gas.cjs.map +1 -1
  34. package/dist/utils/gas.d.cts.map +1 -1
  35. package/dist/utils/gas.d.mts.map +1 -1
  36. package/dist/utils/gas.mjs +2 -1
  37. package/dist/utils/gas.mjs.map +1 -1
  38. package/dist/utils/provider.cjs +61 -0
  39. package/dist/utils/provider.cjs.map +1 -0
  40. package/dist/utils/provider.d.cts +59 -0
  41. package/dist/utils/provider.d.cts.map +1 -0
  42. package/dist/utils/provider.d.mts +59 -0
  43. package/dist/utils/provider.d.mts.map +1 -0
  44. package/dist/utils/provider.mjs +56 -0
  45. package/dist/utils/provider.mjs.map +1 -0
  46. package/dist/utils/token.cjs +28 -16
  47. package/dist/utils/token.cjs.map +1 -1
  48. package/dist/utils/token.d.cts +4 -0
  49. package/dist/utils/token.d.cts.map +1 -1
  50. package/dist/utils/token.d.mts +4 -0
  51. package/dist/utils/token.d.mts.map +1 -1
  52. package/dist/utils/token.mjs +28 -16
  53. package/dist/utils/token.mjs.map +1 -1
  54. package/dist/utils/transaction.cjs +28 -20
  55. package/dist/utils/transaction.cjs.map +1 -1
  56. package/dist/utils/transaction.d.cts.map +1 -1
  57. package/dist/utils/transaction.d.mts.map +1 -1
  58. package/dist/utils/transaction.mjs +28 -20
  59. package/dist/utils/transaction.mjs.map +1 -1
  60. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA6MA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type {\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n CurrencyRateStateChange,\n TokenBalancesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type { TokenRatesControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { TokenRatesControllerStateChangeEvent } from '@metamask/assets-controllers';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n} from '@metamask/assets-controllers';\nimport type { AccountTrackerControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { BridgeControllerFetchQuotesAction } from '@metamask/bridge-controller';\nimport type { BridgeStatusControllerStateChangeEvent } from '@metamask/bridge-status-controller';\nimport type {\n BridgeStatusControllerGetStateAction,\n BridgeStatusControllerSubmitTxAction,\n} from '@metamask/bridge-status-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuotesAction,\n RampsControllerGetStateAction,\n RampsControllerSetSelectedTokenAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n BatchTransactionParams,\n TransactionControllerAddTransactionAction,\n TransactionControllerGetGasFeeTokensAction,\n TransactionControllerGetStateAction,\n TransactionControllerStateChangeEvent,\n TransactionControllerUpdateTransactionAction,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n CONTROLLER_NAME,\n PaymentOverride,\n TransactionPayStrategy,\n} from './constants';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types';\n\nexport type AllowedActions =\n | AccountTrackerControllerGetStateAction\n | AssetsControllerGetStateForTransactionPayAction\n | BridgeControllerFetchQuotesAction\n | BridgeStatusControllerGetStateAction\n | BridgeStatusControllerSubmitTxAction\n | CurrencyRateControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuotesAction\n | RampsControllerGetStateAction\n | RampsControllerSetSelectedTokenAction\n | RemoteFeatureFlagControllerGetStateAction\n | TokenBalancesControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | TokensControllerGetStateAction\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | BridgeStatusControllerStateChangeEvent\n | CurrencyRateStateChange\n | TokenRatesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the source of funds is HyperLiquid (HyperCore).\n * When true, the Relay strategy uses the HyperLiquid 2-step withdrawal\n * flow: (1) authorize nonce-mapping, (2) sendAsset to Relay solver.\n */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n */\n isPostQuote?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request. Use this for post-quote flows where the user's funds originate\n * from a smart contract account (e.g. Predict Safe proxy) so that refunds\n * go back to that account rather than the EOA.\n */\n refundTo?: Hex;\n};\n\n/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Request passed to {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataRequest = {\n /** Amount of the source token in human-readable format. */\n amount: string;\n\n /** Metadata of the original transaction. */\n transaction: TransactionMeta;\n\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Response returned by {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataResponse = {\n /** Batch transaction params to prepend to the submit batch. */\n calls: BatchTransactionParams[];\n};\n\n/**\n * Callback invoked during submit when `paymentOverride` is defined.\n * Returns batch transaction params to prepend to the submit batch.\n */\nexport type GetPaymentOverrideDataCallback = (\n request: GetPaymentOverrideDataRequest,\n) => Promise<GetPaymentOverrideDataResponse>;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /**\n * Optional callback invoked during quote execution when `paymentOverride` is defined.\n * Returns additional transactions to be submitted alongside the quote batch.\n */\n getPaymentOverrideData?: GetPaymentOverrideDataCallback;\n\n /** Callback to select the PayStrategy for a transaction. */\n getStrategy?: (transaction: TransactionMeta) => TransactionPayStrategy;\n\n /** Callback to select ordered PayStrategies for a transaction. */\n getStrategies?: (transaction: TransactionMeta) => TransactionPayStrategy[];\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Callbacks for the Polymarket relayer; required only for the Polymarket deposit-wallet flow. */\n polymarket?: PolymarketCallbacks;\n\n /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /** Fiat payment method state. */\n fiatPayment?: TransactionFiatPayment;\n\n /** Whether quotes are currently being retrieved. */\n isLoading: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n * Used when funds need to be moved after a transaction completes\n * (e.g., bridging output to a different token/chain).\n */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /**\n * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */\n caipAssetId?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n}: {\n transaction: TransactionMeta;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** Client-supplied callbacks for the Polymarket relayer protocol. */\nexport type PolymarketCallbacks = {\n /** Derive the deposit-wallet address (CREATE2) for the given EOA. */\n getDepositWalletAddress: (params: { eoa: Hex }) => Promise<Hex>;\n\n /** Sign and broadcast a deposit-wallet batch, returning the source hash. */\n submitDepositWalletBatch: (params: {\n eoa: Hex;\n depositWallet: Hex;\n calls: { target: Hex; data: Hex; value: string }[];\n }) => Promise<{ sourceHash: Hex }>;\n};\n\n/** Single amount in alternate formats. */\nexport type Amount = FiatValue & {\n /** Amount in human-readable format factoring token decimals. */\n human: string;\n\n /** Amount in atomic format without factoring token decimals. */\n raw: string;\n};\n"]}
1
+ {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA2MA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type {\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n CurrencyRateStateChange,\n TokenBalancesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type { TokenRatesControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { TokenRatesControllerStateChangeEvent } from '@metamask/assets-controllers';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n} from '@metamask/assets-controllers';\nimport type { AccountTrackerControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { BridgeControllerFetchQuotesAction } from '@metamask/bridge-controller';\nimport type { BridgeStatusControllerStateChangeEvent } from '@metamask/bridge-status-controller';\nimport type {\n BridgeStatusControllerGetStateAction,\n BridgeStatusControllerSubmitTxAction,\n} from '@metamask/bridge-status-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkConfigurationByChainIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuotesAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n BatchTransactionParams,\n TransactionControllerAddTransactionAction,\n TransactionControllerGetGasFeeTokensAction,\n TransactionControllerGetStateAction,\n TransactionControllerStateChangeEvent,\n TransactionControllerUpdateTransactionAction,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n CONTROLLER_NAME,\n PaymentOverride,\n TransactionPayStrategy,\n} from './constants';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types';\n\nexport type AllowedActions =\n | AccountTrackerControllerGetStateAction\n | AssetsControllerGetStateForTransactionPayAction\n | BridgeControllerFetchQuotesAction\n | BridgeStatusControllerGetStateAction\n | BridgeStatusControllerSubmitTxAction\n | CurrencyRateControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByChainIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuotesAction\n | RemoteFeatureFlagControllerGetStateAction\n | TokenBalancesControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | TokensControllerGetStateAction\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | BridgeStatusControllerStateChangeEvent\n | CurrencyRateStateChange\n | TokenRatesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the source of funds is HyperLiquid (HyperCore).\n * When true, the Relay strategy uses the HyperLiquid 2-step withdrawal\n * flow: (1) authorize nonce-mapping, (2) sendAsset to Relay solver.\n */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n */\n isPostQuote?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request. Use this for post-quote flows where the user's funds originate\n * from a smart contract account (e.g. Predict Safe proxy) so that refunds\n * go back to that account rather than the EOA.\n */\n refundTo?: Hex;\n};\n\n/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Request passed to {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataRequest = {\n /** Amount of the source token in human-readable format. */\n amount: string;\n\n /** Metadata of the original transaction. */\n transaction: TransactionMeta;\n\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Response returned by {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataResponse = {\n /** Batch transaction params to prepend to the submit batch. */\n calls: BatchTransactionParams[];\n};\n\n/**\n * Callback invoked during submit when `paymentOverride` is defined.\n * Returns batch transaction params to prepend to the submit batch.\n */\nexport type GetPaymentOverrideDataCallback = (\n request: GetPaymentOverrideDataRequest,\n) => Promise<GetPaymentOverrideDataResponse>;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /**\n * Optional callback invoked during quote execution when `paymentOverride` is defined.\n * Returns additional transactions to be submitted alongside the quote batch.\n */\n getPaymentOverrideData?: GetPaymentOverrideDataCallback;\n\n /** Callback to select the PayStrategy for a transaction. */\n getStrategy?: (transaction: TransactionMeta) => TransactionPayStrategy;\n\n /** Callback to select ordered PayStrategies for a transaction. */\n getStrategies?: (transaction: TransactionMeta) => TransactionPayStrategy[];\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Callbacks for the Polymarket relayer; required only for the Polymarket deposit-wallet flow. */\n polymarket?: PolymarketCallbacks;\n\n /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /** Fiat payment method state. */\n fiatPayment?: TransactionFiatPayment;\n\n /** Whether quotes are currently being retrieved. */\n isLoading: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n * Used when funds need to be moved after a transaction completes\n * (e.g., bridging output to a different token/chain).\n */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /**\n * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */\n caipAssetId?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n}: {\n transaction: TransactionMeta;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** Client-supplied callbacks for the Polymarket relayer protocol. */\nexport type PolymarketCallbacks = {\n /** Derive the deposit-wallet address (CREATE2) for the given EOA. */\n getDepositWalletAddress: (params: { eoa: Hex }) => Promise<Hex>;\n\n /** Sign and broadcast a deposit-wallet batch, returning the source hash. */\n submitDepositWalletBatch: (params: {\n eoa: Hex;\n depositWallet: Hex;\n calls: { target: Hex; data: Hex; value: string }[];\n }) => Promise<{ sourceHash: Hex }>;\n};\n\n/** Single amount in alternate formats. */\nexport type Amount = FiatValue & {\n /** Amount in human-readable format factoring token decimals. */\n human: string;\n\n /** Amount in atomic format without factoring token decimals. */\n raw: string;\n};\n"]}
@@ -5,6 +5,7 @@ const controller_utils_1 = require("@metamask/controller-utils");
5
5
  const bignumber_js_1 = require("bignumber.js");
6
6
  const logger_1 = require("../logger.cjs");
7
7
  const feature_flags_1 = require("./feature-flags.cjs");
8
+ const provider_1 = require("./provider.cjs");
8
9
  const token_1 = require("./token.cjs");
9
10
  const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'gas');
10
11
  /**
@@ -122,7 +123,7 @@ function calculateGasFeeTokenCost({ chainId, gasFeeToken, messenger, }) {
122
123
  exports.calculateGasFeeTokenCost = calculateGasFeeTokenCost;
123
124
  async function estimateGasLimit({ chainId, data, fallbackGas, fallbackOnSimulationFailure = false, from, messenger, to, value, }) {
124
125
  const gasBuffer = (0, feature_flags_1.getGasBuffer)(messenger, chainId);
125
- const networkClientId = messenger.call('NetworkController:findNetworkClientIdByChainId', chainId);
126
+ const networkClientId = (0, provider_1.getNetworkClientId)(messenger, chainId);
126
127
  let estimateGasError;
127
128
  let simulationError;
128
129
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"gas.cjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";;;AAAA,iEAAmD;AAOnD,+CAAyC;AAGzC,0CAA8D;AAE9D,uDAA+D;AAC/D,uCAA4E;AAE5E,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,KAAK,CAAC,CAAC;AAErD;;;;;;;;;GASG;AACH,SAAgB,2BAA2B,CACzC,WAA4B,EAC5B,SAA4C,EAC5C,EAAE,KAAK,KAA0B,EAAE;IAEnC,MAAM,EACJ,OAAO,EACP,OAAO,EAAE,eAAe,EACxB,gBAAgB,EAChB,QAAQ,GACT,GAAG,WAAW,CAAC;IAEhB,MAAM,EAAE,IAAI,EAAE,GAA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AC,QAAQ,EAAE,IAAI,SAAS,CAAC,KAAK,EAAE,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CAAC,kCAAkC,QAAQ,EAAE,CAAC,CAAC;IAChE,CAAC;IAED,OAAO,SAAS,CAAC,QAAQ,EAAE,CAAC;AAC9B,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,mCAAmC,CAAC,EAC3C,UAAU,EACV,SAAS,EACT,WAAW,GAKZ;IACC,MAAM,EACJ,OAAO,EACP,YAAY,EACZ,6BAA6B,EAC7B,mBAAmB,GACpB,GAAG,WAAW,CAAC;IAEhB,IACE,CAAC,YAAY;QACb,CAAC,mBAAmB;QACpB,CAAC,6BAA6B,IAAI,UAAU,CAAC,EAC7C,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,GAAG,CAAC,gCAAgC,EAAE,EAAE,mBAAmB,EAAE,OAAO,EAAE,CAAC,CAAC;IAExE,MAAM,WAAW,GAAG,YAAY,EAAE,IAAI,CACpC,CAAC,iBAAiB,EAAE,EAAE,CACpB,iBAAiB,CAAC,YAAY,CAAC,WAAW,EAAE;QAC5C,mBAAmB,CAAC,WAAW,EAAE,CACpC,CAAC;IAEF,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,GAAG,CAAC,yBAAyB,EAAE;YAC7B,YAAY;YACZ,mBAAmB;SACpB,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,wBAAwB,CAAC;QAC9B,OAAO;QACP,WAAW;QACX,SAAS;KACV,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { toHex } from '@metamask/controller-utils';\nimport type { GasFeeEstimates } from '@metamask/gas-fee-controller';\nimport type {\n GasFeeToken,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport type { TransactionPayControllerMessenger } from '..';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { Amount } from '../types';\nimport { getFallbackGas, getGasBuffer } from './feature-flags';\nimport { getNativeToken, getTokenBalance, getTokenFiatRate } from './token';\n\nconst log = createModuleLogger(projectLogger, 'gas');\n\n/**\n *\n * Calculate the estimated gas cost for a given transaction in fiat.\n *\n * @param transaction - Transaction to calculate gas cost for\n * @param messenger - Controller messenger.\n * @param options - Calculation options.\n * @param options.isMax - Whether to calculate the maximum fee.\n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateTransactionGasCost(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n { isMax }: { isMax?: boolean } = {},\n): Amount & { isGasFeeToken?: boolean } {\n const {\n chainId,\n gasUsed: gasUsedOriginal,\n gasLimitNoBuffer,\n txParams,\n } = transaction;\n\n const { from, gas, maxFeePerGas, maxPriorityFeePerGas } = txParams;\n const gasUsed = isMax ? undefined : gasUsedOriginal;\n const finalGas = gasUsed ?? gasLimitNoBuffer ?? gas ?? '0x0';\n\n const result = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n });\n\n const max = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax: true,\n messenger,\n });\n\n const nativeBalance = getTokenBalance(\n messenger,\n from as Hex,\n chainId,\n getNativeToken(chainId),\n );\n\n const hasBalance = new BigNumber(nativeBalance).gte(max.raw);\n\n const gasFeeTokenCost = calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n });\n\n if (gasFeeTokenCost) {\n return gasFeeTokenCost;\n }\n\n return result;\n}\n\n/**\n * Calculate the gas cost for the specified parameters.\n *\n * @param request - Gas cost calculation parameters.\n * @param request.chainId - ID of the chain.\n * @param request.gas - Amount of gas the transaction will use.\n * @param request.isMax - Whether to calculate the maximum fee.\n * @param request.maxFeePerGas - Max fee to pay per gas.\n * @param request.maxPriorityFeePerGas - Max priority fee to pay per gas.\n * @param request.messenger - Controller messenger.\n \n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateGasCost(request: {\n chainId: number | Hex;\n gas: BigNumber.Value;\n isMax?: boolean;\n maxFeePerGas?: BigNumber.Value;\n maxPriorityFeePerGas?: BigNumber.Value;\n messenger: TransactionPayControllerMessenger;\n}): Amount {\n const {\n chainId: chainIdInput,\n gas,\n isMax,\n maxFeePerGas: maxFeePerGasInput,\n maxPriorityFeePerGas: maxPriorityFeePerGasInput,\n messenger,\n } = request;\n\n const chainId = toHex(chainIdInput);\n\n const {\n estimatedBaseFee,\n maxFeePerGas: maxFeePerGasEstimate,\n maxPriorityFeePerGas: maxPriorityFeePerGasEstimate,\n } = getGasFee(chainId, messenger);\n\n const maxFeePerGas = maxFeePerGasInput ?? maxFeePerGasEstimate;\n\n const maxPriorityFeePerGas =\n maxPriorityFeePerGasInput ?? maxPriorityFeePerGasEstimate;\n\n const feePerGas =\n estimatedBaseFee && maxPriorityFeePerGas && !isMax\n ? new BigNumber(estimatedBaseFee).plus(maxPriorityFeePerGas)\n : new BigNumber(maxFeePerGas ?? '0x0');\n\n const rawValue = new BigNumber(gas).multipliedBy(feePerGas);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-18);\n const human = humanValue.toString(10);\n\n const fiatRate = getTokenFiatRate(\n messenger,\n getNativeToken(chainId),\n chainId,\n );\n\n if (!fiatRate) {\n throw new Error('Could not fetch fiat rate for native token');\n }\n\n const usd = humanValue.multipliedBy(fiatRate.usdRate).toString(10);\n const fiat = humanValue.multipliedBy(fiatRate.fiatRate).toString(10);\n\n return {\n fiat,\n human,\n raw,\n usd,\n };\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.chainId - Chain ID.\n * @param request.gasFeeToken - Gas fee token to calculate cost for.\n * @param request.messenger - Controller messenger.\n * @returns Cost of the gas fee token.\n */\nexport function calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n}: {\n chainId: Hex;\n gasFeeToken: GasFeeToken;\n messenger: TransactionPayControllerMessenger;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const { amount, decimals, tokenAddress } = gasFeeToken;\n\n const tokenFiatRate = getTokenFiatRate(messenger, tokenAddress, chainId);\n\n if (!tokenFiatRate) {\n log('Cannot get gas fee token info');\n return undefined;\n }\n\n const rawValue = new BigNumber(amount);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\n\n const fiat = humanValue.multipliedBy(tokenFiatRate.fiatRate).toString(10);\n const usd = humanValue.multipliedBy(tokenFiatRate.usdRate).toString(10);\n\n return {\n isGasFeeToken: true,\n fiat,\n human,\n raw,\n usd,\n };\n}\n\nexport async function estimateGasLimit({\n chainId,\n data,\n fallbackGas,\n fallbackOnSimulationFailure = false,\n from,\n messenger,\n to,\n value,\n}: {\n chainId: Hex;\n data: Hex;\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure?: boolean;\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n to: Hex;\n value?: Hex;\n}): Promise<{\n estimate: number;\n max: number;\n usedFallback: boolean;\n error?: unknown;\n}> {\n const gasBuffer = getGasBuffer(messenger, chainId);\n const networkClientId = messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n chainId,\n );\n\n let estimateGasError: unknown;\n let simulationError: Error | undefined;\n\n try {\n const { gas: gasHex, simulationFails } = await messenger.call(\n 'TransactionController:estimateGas',\n { from, data, to, value: value ?? '0x0' },\n networkClientId,\n );\n\n if (simulationFails) {\n simulationError = new Error('Gas simulation failed');\n } else {\n const estimatedGas = parseEstimatedGas(gasHex);\n const bufferedGas = Math.ceil(estimatedGas * gasBuffer);\n\n return {\n estimate: bufferedGas,\n max: bufferedGas,\n usedFallback: false,\n };\n }\n } catch (caughtError) {\n estimateGasError = caughtError;\n }\n\n if (simulationError !== undefined && !fallbackOnSimulationFailure) {\n throw simulationError;\n }\n\n const fallbackGasConfig = fallbackGas ?? getFallbackGas(messenger);\n\n return {\n estimate: fallbackGasConfig.estimate,\n max: fallbackGasConfig.max,\n usedFallback: true,\n error: estimateGasError ?? simulationError,\n };\n}\n\n/**\n * Get gas fee estimates for a given chain.\n *\n * @param chainId - Chain ID.\n * @param messenger - Controller messenger.\n * @returns Gas fee estimates for the chain.\n */\nexport function getGasFee(\n chainId: Hex,\n messenger: TransactionPayControllerMessenger,\n): {\n estimatedBaseFee: string | undefined;\n maxFeePerGas: string | undefined;\n maxPriorityFeePerGas: string | undefined;\n} {\n const gasFeeControllerState = messenger.call('GasFeeController:getState');\n\n const chainState = gasFeeControllerState?.gasFeeEstimatesByChainId?.[chainId];\n\n const { estimatedBaseFee: estimatedBaseFeeGwei, medium } =\n (chainState?.gasFeeEstimates as GasFeeEstimates | undefined) ?? {};\n\n const maxFeePerGasGwei = medium?.suggestedMaxFeePerGas;\n const maxPriorityFeePerGasGwei = medium?.suggestedMaxPriorityFeePerGas;\n\n const estimatedBaseFee = estimatedBaseFeeGwei\n ? new BigNumber(estimatedBaseFeeGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxFeePerGas = maxFeePerGasGwei\n ? new BigNumber(maxFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxPriorityFeePerGas = maxPriorityFeePerGasGwei\n ? new BigNumber(maxPriorityFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n return { estimatedBaseFee, maxFeePerGas, maxPriorityFeePerGas };\n}\n\nfunction parseEstimatedGas(gasValue: string): number {\n const parsedGas = gasValue.startsWith('0x')\n ? new BigNumber(gasValue.slice(2), 16)\n : new BigNumber(gasValue);\n\n if (!parsedGas.isFinite() || parsedGas.isNaN()) {\n throw new Error(`Invalid gas estimate returned: ${gasValue}`);\n }\n\n return parsedGas.toNumber();\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.hasBalance - Whether the user has enough balance to cover the gas fee.\n * @param request.messenger - Controller messenger.\n * @param request.transaction - Transaction to calculate gas fee token cost for.\n * @returns Cost of the gas fee token.\n */\nfunction calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n}: {\n hasBalance: boolean;\n messenger: TransactionPayControllerMessenger;\n transaction: TransactionMeta;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const {\n chainId,\n gasFeeTokens,\n isGasFeeTokenIgnoredIfBalance,\n selectedGasFeeToken,\n } = transaction;\n\n if (\n !gasFeeTokens ||\n !selectedGasFeeToken ||\n (isGasFeeTokenIgnoredIfBalance && hasBalance)\n ) {\n return undefined;\n }\n\n log('Calculating gas fee token cost', { selectedGasFeeToken, chainId });\n\n const gasFeeToken = gasFeeTokens?.find(\n (singleGasFeeToken) =>\n singleGasFeeToken.tokenAddress.toLowerCase() ===\n selectedGasFeeToken.toLowerCase(),\n );\n\n if (!gasFeeToken) {\n log('Gas fee token not found', {\n gasFeeTokens,\n selectedGasFeeToken,\n });\n\n return undefined;\n }\n\n return calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n });\n}\n"]}
1
+ {"version":3,"file":"gas.cjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";;;AAAA,iEAAmD;AAOnD,+CAAyC;AAGzC,0CAA8D;AAE9D,uDAA+D;AAC/D,6CAAgD;AAChD,uCAA4E;AAE5E,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,KAAK,CAAC,CAAC;AAErD;;;;;;;;;GASG;AACH,SAAgB,2BAA2B,CACzC,WAA4B,EAC5B,SAA4C,EAC5C,EAAE,KAAK,KAA0B,EAAE;IAEnC,MAAM,EACJ,OAAO,EACP,OAAO,EAAE,eAAe,EACxB,gBAAgB,EAChB,QAAQ,GACT,GAAG,WAAW,CAAC;IAEhB,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,YAAY,EAAE,oBAAoB,EAAE,GAAG,QAAQ,CAAC;IACnE,MAAM,OAAO,GAAG,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,C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ChE,CAAC;IAED,OAAO,SAAS,CAAC,QAAQ,EAAE,CAAC;AAC9B,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,mCAAmC,CAAC,EAC3C,UAAU,EACV,SAAS,EACT,WAAW,GAKZ;IACC,MAAM,EACJ,OAAO,EACP,YAAY,EACZ,6BAA6B,EAC7B,mBAAmB,GACpB,GAAG,WAAW,CAAC;IAEhB,IACE,CAAC,YAAY;QACb,CAAC,mBAAmB;QACpB,CAAC,6BAA6B,IAAI,UAAU,CAAC,EAC7C,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,GAAG,CAAC,gCAAgC,EAAE,EAAE,mBAAmB,EAAE,OAAO,EAAE,CAAC,CAAC;IAExE,MAAM,WAAW,GAAG,YAAY,EAAE,IAAI,CACpC,CAAC,iBAAiB,EAAE,EAAE,CACpB,iBAAiB,CAAC,YAAY,CAAC,WAAW,EAAE;QAC5C,mBAAmB,CAAC,WAAW,EAAE,CACpC,CAAC;IAEF,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,GAAG,CAAC,yBAAyB,EAAE;YAC7B,YAAY;YACZ,mBAAmB;SACpB,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,wBAAwB,CAAC;QAC9B,OAAO;QACP,WAAW;QACX,SAAS;KACV,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { toHex } from '@metamask/controller-utils';\nimport type { GasFeeEstimates } from '@metamask/gas-fee-controller';\nimport type {\n GasFeeToken,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport type { TransactionPayControllerMessenger } from '..';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { Amount } from '../types';\nimport { getFallbackGas, getGasBuffer } from './feature-flags';\nimport { getNetworkClientId } from './provider';\nimport { getNativeToken, getTokenBalance, getTokenFiatRate } from './token';\n\nconst log = createModuleLogger(projectLogger, 'gas');\n\n/**\n *\n * Calculate the estimated gas cost for a given transaction in fiat.\n *\n * @param transaction - Transaction to calculate gas cost for\n * @param messenger - Controller messenger.\n * @param options - Calculation options.\n * @param options.isMax - Whether to calculate the maximum fee.\n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateTransactionGasCost(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n { isMax }: { isMax?: boolean } = {},\n): Amount & { isGasFeeToken?: boolean } {\n const {\n chainId,\n gasUsed: gasUsedOriginal,\n gasLimitNoBuffer,\n txParams,\n } = transaction;\n\n const { from, gas, maxFeePerGas, maxPriorityFeePerGas } = txParams;\n const gasUsed = isMax ? undefined : gasUsedOriginal;\n const finalGas = gasUsed ?? gasLimitNoBuffer ?? gas ?? '0x0';\n\n const result = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n });\n\n const max = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax: true,\n messenger,\n });\n\n const nativeBalance = getTokenBalance(\n messenger,\n from as Hex,\n chainId,\n getNativeToken(chainId),\n );\n\n const hasBalance = new BigNumber(nativeBalance).gte(max.raw);\n\n const gasFeeTokenCost = calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n });\n\n if (gasFeeTokenCost) {\n return gasFeeTokenCost;\n }\n\n return result;\n}\n\n/**\n * Calculate the gas cost for the specified parameters.\n *\n * @param request - Gas cost calculation parameters.\n * @param request.chainId - ID of the chain.\n * @param request.gas - Amount of gas the transaction will use.\n * @param request.isMax - Whether to calculate the maximum fee.\n * @param request.maxFeePerGas - Max fee to pay per gas.\n * @param request.maxPriorityFeePerGas - Max priority fee to pay per gas.\n * @param request.messenger - Controller messenger.\n \n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateGasCost(request: {\n chainId: number | Hex;\n gas: BigNumber.Value;\n isMax?: boolean;\n maxFeePerGas?: BigNumber.Value;\n maxPriorityFeePerGas?: BigNumber.Value;\n messenger: TransactionPayControllerMessenger;\n}): Amount {\n const {\n chainId: chainIdInput,\n gas,\n isMax,\n maxFeePerGas: maxFeePerGasInput,\n maxPriorityFeePerGas: maxPriorityFeePerGasInput,\n messenger,\n } = request;\n\n const chainId = toHex(chainIdInput);\n\n const {\n estimatedBaseFee,\n maxFeePerGas: maxFeePerGasEstimate,\n maxPriorityFeePerGas: maxPriorityFeePerGasEstimate,\n } = getGasFee(chainId, messenger);\n\n const maxFeePerGas = maxFeePerGasInput ?? maxFeePerGasEstimate;\n\n const maxPriorityFeePerGas =\n maxPriorityFeePerGasInput ?? maxPriorityFeePerGasEstimate;\n\n const feePerGas =\n estimatedBaseFee && maxPriorityFeePerGas && !isMax\n ? new BigNumber(estimatedBaseFee).plus(maxPriorityFeePerGas)\n : new BigNumber(maxFeePerGas ?? '0x0');\n\n const rawValue = new BigNumber(gas).multipliedBy(feePerGas);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-18);\n const human = humanValue.toString(10);\n\n const fiatRate = getTokenFiatRate(\n messenger,\n getNativeToken(chainId),\n chainId,\n );\n\n if (!fiatRate) {\n throw new Error('Could not fetch fiat rate for native token');\n }\n\n const usd = humanValue.multipliedBy(fiatRate.usdRate).toString(10);\n const fiat = humanValue.multipliedBy(fiatRate.fiatRate).toString(10);\n\n return {\n fiat,\n human,\n raw,\n usd,\n };\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.chainId - Chain ID.\n * @param request.gasFeeToken - Gas fee token to calculate cost for.\n * @param request.messenger - Controller messenger.\n * @returns Cost of the gas fee token.\n */\nexport function calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n}: {\n chainId: Hex;\n gasFeeToken: GasFeeToken;\n messenger: TransactionPayControllerMessenger;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const { amount, decimals, tokenAddress } = gasFeeToken;\n\n const tokenFiatRate = getTokenFiatRate(messenger, tokenAddress, chainId);\n\n if (!tokenFiatRate) {\n log('Cannot get gas fee token info');\n return undefined;\n }\n\n const rawValue = new BigNumber(amount);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\n\n const fiat = humanValue.multipliedBy(tokenFiatRate.fiatRate).toString(10);\n const usd = humanValue.multipliedBy(tokenFiatRate.usdRate).toString(10);\n\n return {\n isGasFeeToken: true,\n fiat,\n human,\n raw,\n usd,\n };\n}\n\nexport async function estimateGasLimit({\n chainId,\n data,\n fallbackGas,\n fallbackOnSimulationFailure = false,\n from,\n messenger,\n to,\n value,\n}: {\n chainId: Hex;\n data: Hex;\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure?: boolean;\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n to: Hex;\n value?: Hex;\n}): Promise<{\n estimate: number;\n max: number;\n usedFallback: boolean;\n error?: unknown;\n}> {\n const gasBuffer = getGasBuffer(messenger, chainId);\n const networkClientId = getNetworkClientId(messenger, chainId);\n\n let estimateGasError: unknown;\n let simulationError: Error | undefined;\n\n try {\n const { gas: gasHex, simulationFails } = await messenger.call(\n 'TransactionController:estimateGas',\n { from, data, to, value: value ?? '0x0' },\n networkClientId,\n );\n\n if (simulationFails) {\n simulationError = new Error('Gas simulation failed');\n } else {\n const estimatedGas = parseEstimatedGas(gasHex);\n const bufferedGas = Math.ceil(estimatedGas * gasBuffer);\n\n return {\n estimate: bufferedGas,\n max: bufferedGas,\n usedFallback: false,\n };\n }\n } catch (caughtError) {\n estimateGasError = caughtError;\n }\n\n if (simulationError !== undefined && !fallbackOnSimulationFailure) {\n throw simulationError;\n }\n\n const fallbackGasConfig = fallbackGas ?? getFallbackGas(messenger);\n\n return {\n estimate: fallbackGasConfig.estimate,\n max: fallbackGasConfig.max,\n usedFallback: true,\n error: estimateGasError ?? simulationError,\n };\n}\n\n/**\n * Get gas fee estimates for a given chain.\n *\n * @param chainId - Chain ID.\n * @param messenger - Controller messenger.\n * @returns Gas fee estimates for the chain.\n */\nexport function getGasFee(\n chainId: Hex,\n messenger: TransactionPayControllerMessenger,\n): {\n estimatedBaseFee: string | undefined;\n maxFeePerGas: string | undefined;\n maxPriorityFeePerGas: string | undefined;\n} {\n const gasFeeControllerState = messenger.call('GasFeeController:getState');\n\n const chainState = gasFeeControllerState?.gasFeeEstimatesByChainId?.[chainId];\n\n const { estimatedBaseFee: estimatedBaseFeeGwei, medium } =\n (chainState?.gasFeeEstimates as GasFeeEstimates | undefined) ?? {};\n\n const maxFeePerGasGwei = medium?.suggestedMaxFeePerGas;\n const maxPriorityFeePerGasGwei = medium?.suggestedMaxPriorityFeePerGas;\n\n const estimatedBaseFee = estimatedBaseFeeGwei\n ? new BigNumber(estimatedBaseFeeGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxFeePerGas = maxFeePerGasGwei\n ? new BigNumber(maxFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxPriorityFeePerGas = maxPriorityFeePerGasGwei\n ? new BigNumber(maxPriorityFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n return { estimatedBaseFee, maxFeePerGas, maxPriorityFeePerGas };\n}\n\nfunction parseEstimatedGas(gasValue: string): number {\n const parsedGas = gasValue.startsWith('0x')\n ? new BigNumber(gasValue.slice(2), 16)\n : new BigNumber(gasValue);\n\n if (!parsedGas.isFinite() || parsedGas.isNaN()) {\n throw new Error(`Invalid gas estimate returned: ${gasValue}`);\n }\n\n return parsedGas.toNumber();\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.hasBalance - Whether the user has enough balance to cover the gas fee.\n * @param request.messenger - Controller messenger.\n * @param request.transaction - Transaction to calculate gas fee token cost for.\n * @returns Cost of the gas fee token.\n */\nfunction calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n}: {\n hasBalance: boolean;\n messenger: TransactionPayControllerMessenger;\n transaction: TransactionMeta;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const {\n chainId,\n gasFeeTokens,\n isGasFeeTokenIgnoredIfBalance,\n selectedGasFeeToken,\n } = transaction;\n\n if (\n !gasFeeTokens ||\n !selectedGasFeeToken ||\n (isGasFeeTokenIgnoredIfBalance && hasBalance)\n ) {\n return undefined;\n }\n\n log('Calculating gas fee token cost', { selectedGasFeeToken, chainId });\n\n const gasFeeToken = gasFeeTokens?.find(\n (singleGasFeeToken) =>\n singleGasFeeToken.tokenAddress.toLowerCase() ===\n selectedGasFeeToken.toLowerCase(),\n );\n\n if (!gasFeeToken) {\n log('Gas fee token not found', {\n gasFeeTokens,\n selectedGasFeeToken,\n });\n\n return undefined;\n }\n\n return calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"gas.d.cts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,WAAW,EACX,eAAe,EAChB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAC3C,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAW;AAE5D,OAAO,KAAK,EAAE,MAAM,EAAE,qBAAiB;AAMvC;;;;;;;;;GASG;AACH,wBAAgB,2BAA2B,CACzC,WAAW,EAAE,eAAe,EAC5B,SAAS,EAAE,iCAAiC,EAC5C,EAAE,KAAK,EAAE,GAAE;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GAClC,MAAM,GAAG;IAAE,aAAa,CAAC,EAAE,OAAO,CAAA;CAAE,CAgDtC;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE;IACxC,OAAO,EAAE,MAAM,GAAG,GAAG,CAAC;IACtB,GAAG,EAAE,SAAS,CAAC,KAAK,CAAC;IACrB,KAAK,CAAC,EAAE,O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BA"}
@@ -2,6 +2,7 @@ import { toHex } from "@metamask/controller-utils";
2
2
  import { BigNumber } from "bignumber.js";
3
3
  import { createModuleLogger, projectLogger } from "../logger.mjs";
4
4
  import { getFallbackGas, getGasBuffer } from "./feature-flags.mjs";
5
+ import { getNetworkClientId } from "./provider.mjs";
5
6
  import { getNativeToken, getTokenBalance, getTokenFiatRate } from "./token.mjs";
6
7
  const log = createModuleLogger(projectLogger, 'gas');
7
8
  /**
@@ -116,7 +117,7 @@ export function calculateGasFeeTokenCost({ chainId, gasFeeToken, messenger, }) {
116
117
  }
117
118
  export async function estimateGasLimit({ chainId, data, fallbackGas, fallbackOnSimulationFailure = false, from, messenger, to, value, }) {
118
119
  const gasBuffer = getGasBuffer(messenger, chainId);
119
- const networkClientId = messenger.call('NetworkController:findNetworkClientIdByChainId', chainId);
120
+ const networkClientId = getNetworkClientId(messenger, chainId);
120
121
  let estimateGasError;
121
122
  let simulationError;
122
123
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"gas.mjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,mCAAmC;AAOnD,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAGzC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,sBAAkB;AAE9D,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,4BAAwB;AAC/D,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,gBAAgB,EAAE,oBAAgB;AAE5E,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;AAErD;;;;;;;;;GASG;AACH,MAAM,UAAU,2BAA2B,CACzC,WAA4B,EAC5B,SAA4C,EAC5C,EAAE,KAAK,KAA0B,EAAE;IAEnC,MAAM,EACJ,OAAO,EACP,OAAO,EAAE,eAAe,EACxB,gBAAgB,EAChB,QAAQ,GACT,GAAG,WAAW,CAAC;IAEhB,MAAM,EAAE,IAAI,EAAE,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AC,CAAC;IAChE,CAAC;IAED,OAAO,SAAS,CAAC,QAAQ,EAAE,CAAC;AAC9B,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,mCAAmC,CAAC,EAC3C,UAAU,EACV,SAAS,EACT,WAAW,GAKZ;IACC,MAAM,EACJ,OAAO,EACP,YAAY,EACZ,6BAA6B,EAC7B,mBAAmB,GACpB,GAAG,WAAW,CAAC;IAEhB,IACE,CAAC,YAAY;QACb,CAAC,mBAAmB;QACpB,CAAC,6BAA6B,IAAI,UAAU,CAAC,EAC7C,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,GAAG,CAAC,gCAAgC,EAAE,EAAE,mBAAmB,EAAE,OAAO,EAAE,CAAC,CAAC;IAExE,MAAM,WAAW,GAAG,YAAY,EAAE,IAAI,CACpC,CAAC,iBAAiB,EAAE,EAAE,CACpB,iBAAiB,CAAC,YAAY,CAAC,WAAW,EAAE;QAC5C,mBAAmB,CAAC,WAAW,EAAE,CACpC,CAAC;IAEF,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,GAAG,CAAC,yBAAyB,EAAE;YAC7B,YAAY;YACZ,mBAAmB;SACpB,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,wBAAwB,CAAC;QAC9B,OAAO;QACP,WAAW;QACX,SAAS;KACV,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { toHex } from '@metamask/controller-utils';\nimport type { GasFeeEstimates } from '@metamask/gas-fee-controller';\nimport type {\n GasFeeToken,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport type { TransactionPayControllerMessenger } from '..';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { Amount } from '../types';\nimport { getFallbackGas, getGasBuffer } from './feature-flags';\nimport { getNativeToken, getTokenBalance, getTokenFiatRate } from './token';\n\nconst log = createModuleLogger(projectLogger, 'gas');\n\n/**\n *\n * Calculate the estimated gas cost for a given transaction in fiat.\n *\n * @param transaction - Transaction to calculate gas cost for\n * @param messenger - Controller messenger.\n * @param options - Calculation options.\n * @param options.isMax - Whether to calculate the maximum fee.\n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateTransactionGasCost(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n { isMax }: { isMax?: boolean } = {},\n): Amount & { isGasFeeToken?: boolean } {\n const {\n chainId,\n gasUsed: gasUsedOriginal,\n gasLimitNoBuffer,\n txParams,\n } = transaction;\n\n const { from, gas, maxFeePerGas, maxPriorityFeePerGas } = txParams;\n const gasUsed = isMax ? undefined : gasUsedOriginal;\n const finalGas = gasUsed ?? gasLimitNoBuffer ?? gas ?? '0x0';\n\n const result = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n });\n\n const max = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax: true,\n messenger,\n });\n\n const nativeBalance = getTokenBalance(\n messenger,\n from as Hex,\n chainId,\n getNativeToken(chainId),\n );\n\n const hasBalance = new BigNumber(nativeBalance).gte(max.raw);\n\n const gasFeeTokenCost = calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n });\n\n if (gasFeeTokenCost) {\n return gasFeeTokenCost;\n }\n\n return result;\n}\n\n/**\n * Calculate the gas cost for the specified parameters.\n *\n * @param request - Gas cost calculation parameters.\n * @param request.chainId - ID of the chain.\n * @param request.gas - Amount of gas the transaction will use.\n * @param request.isMax - Whether to calculate the maximum fee.\n * @param request.maxFeePerGas - Max fee to pay per gas.\n * @param request.maxPriorityFeePerGas - Max priority fee to pay per gas.\n * @param request.messenger - Controller messenger.\n \n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateGasCost(request: {\n chainId: number | Hex;\n gas: BigNumber.Value;\n isMax?: boolean;\n maxFeePerGas?: BigNumber.Value;\n maxPriorityFeePerGas?: BigNumber.Value;\n messenger: TransactionPayControllerMessenger;\n}): Amount {\n const {\n chainId: chainIdInput,\n gas,\n isMax,\n maxFeePerGas: maxFeePerGasInput,\n maxPriorityFeePerGas: maxPriorityFeePerGasInput,\n messenger,\n } = request;\n\n const chainId = toHex(chainIdInput);\n\n const {\n estimatedBaseFee,\n maxFeePerGas: maxFeePerGasEstimate,\n maxPriorityFeePerGas: maxPriorityFeePerGasEstimate,\n } = getGasFee(chainId, messenger);\n\n const maxFeePerGas = maxFeePerGasInput ?? maxFeePerGasEstimate;\n\n const maxPriorityFeePerGas =\n maxPriorityFeePerGasInput ?? maxPriorityFeePerGasEstimate;\n\n const feePerGas =\n estimatedBaseFee && maxPriorityFeePerGas && !isMax\n ? new BigNumber(estimatedBaseFee).plus(maxPriorityFeePerGas)\n : new BigNumber(maxFeePerGas ?? '0x0');\n\n const rawValue = new BigNumber(gas).multipliedBy(feePerGas);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-18);\n const human = humanValue.toString(10);\n\n const fiatRate = getTokenFiatRate(\n messenger,\n getNativeToken(chainId),\n chainId,\n );\n\n if (!fiatRate) {\n throw new Error('Could not fetch fiat rate for native token');\n }\n\n const usd = humanValue.multipliedBy(fiatRate.usdRate).toString(10);\n const fiat = humanValue.multipliedBy(fiatRate.fiatRate).toString(10);\n\n return {\n fiat,\n human,\n raw,\n usd,\n };\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.chainId - Chain ID.\n * @param request.gasFeeToken - Gas fee token to calculate cost for.\n * @param request.messenger - Controller messenger.\n * @returns Cost of the gas fee token.\n */\nexport function calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n}: {\n chainId: Hex;\n gasFeeToken: GasFeeToken;\n messenger: TransactionPayControllerMessenger;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const { amount, decimals, tokenAddress } = gasFeeToken;\n\n const tokenFiatRate = getTokenFiatRate(messenger, tokenAddress, chainId);\n\n if (!tokenFiatRate) {\n log('Cannot get gas fee token info');\n return undefined;\n }\n\n const rawValue = new BigNumber(amount);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\n\n const fiat = humanValue.multipliedBy(tokenFiatRate.fiatRate).toString(10);\n const usd = humanValue.multipliedBy(tokenFiatRate.usdRate).toString(10);\n\n return {\n isGasFeeToken: true,\n fiat,\n human,\n raw,\n usd,\n };\n}\n\nexport async function estimateGasLimit({\n chainId,\n data,\n fallbackGas,\n fallbackOnSimulationFailure = false,\n from,\n messenger,\n to,\n value,\n}: {\n chainId: Hex;\n data: Hex;\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure?: boolean;\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n to: Hex;\n value?: Hex;\n}): Promise<{\n estimate: number;\n max: number;\n usedFallback: boolean;\n error?: unknown;\n}> {\n const gasBuffer = getGasBuffer(messenger, chainId);\n const networkClientId = messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n chainId,\n );\n\n let estimateGasError: unknown;\n let simulationError: Error | undefined;\n\n try {\n const { gas: gasHex, simulationFails } = await messenger.call(\n 'TransactionController:estimateGas',\n { from, data, to, value: value ?? '0x0' },\n networkClientId,\n );\n\n if (simulationFails) {\n simulationError = new Error('Gas simulation failed');\n } else {\n const estimatedGas = parseEstimatedGas(gasHex);\n const bufferedGas = Math.ceil(estimatedGas * gasBuffer);\n\n return {\n estimate: bufferedGas,\n max: bufferedGas,\n usedFallback: false,\n };\n }\n } catch (caughtError) {\n estimateGasError = caughtError;\n }\n\n if (simulationError !== undefined && !fallbackOnSimulationFailure) {\n throw simulationError;\n }\n\n const fallbackGasConfig = fallbackGas ?? getFallbackGas(messenger);\n\n return {\n estimate: fallbackGasConfig.estimate,\n max: fallbackGasConfig.max,\n usedFallback: true,\n error: estimateGasError ?? simulationError,\n };\n}\n\n/**\n * Get gas fee estimates for a given chain.\n *\n * @param chainId - Chain ID.\n * @param messenger - Controller messenger.\n * @returns Gas fee estimates for the chain.\n */\nexport function getGasFee(\n chainId: Hex,\n messenger: TransactionPayControllerMessenger,\n): {\n estimatedBaseFee: string | undefined;\n maxFeePerGas: string | undefined;\n maxPriorityFeePerGas: string | undefined;\n} {\n const gasFeeControllerState = messenger.call('GasFeeController:getState');\n\n const chainState = gasFeeControllerState?.gasFeeEstimatesByChainId?.[chainId];\n\n const { estimatedBaseFee: estimatedBaseFeeGwei, medium } =\n (chainState?.gasFeeEstimates as GasFeeEstimates | undefined) ?? {};\n\n const maxFeePerGasGwei = medium?.suggestedMaxFeePerGas;\n const maxPriorityFeePerGasGwei = medium?.suggestedMaxPriorityFeePerGas;\n\n const estimatedBaseFee = estimatedBaseFeeGwei\n ? new BigNumber(estimatedBaseFeeGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxFeePerGas = maxFeePerGasGwei\n ? new BigNumber(maxFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxPriorityFeePerGas = maxPriorityFeePerGasGwei\n ? new BigNumber(maxPriorityFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n return { estimatedBaseFee, maxFeePerGas, maxPriorityFeePerGas };\n}\n\nfunction parseEstimatedGas(gasValue: string): number {\n const parsedGas = gasValue.startsWith('0x')\n ? new BigNumber(gasValue.slice(2), 16)\n : new BigNumber(gasValue);\n\n if (!parsedGas.isFinite() || parsedGas.isNaN()) {\n throw new Error(`Invalid gas estimate returned: ${gasValue}`);\n }\n\n return parsedGas.toNumber();\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.hasBalance - Whether the user has enough balance to cover the gas fee.\n * @param request.messenger - Controller messenger.\n * @param request.transaction - Transaction to calculate gas fee token cost for.\n * @returns Cost of the gas fee token.\n */\nfunction calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n}: {\n hasBalance: boolean;\n messenger: TransactionPayControllerMessenger;\n transaction: TransactionMeta;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const {\n chainId,\n gasFeeTokens,\n isGasFeeTokenIgnoredIfBalance,\n selectedGasFeeToken,\n } = transaction;\n\n if (\n !gasFeeTokens ||\n !selectedGasFeeToken ||\n (isGasFeeTokenIgnoredIfBalance && hasBalance)\n ) {\n return undefined;\n }\n\n log('Calculating gas fee token cost', { selectedGasFeeToken, chainId });\n\n const gasFeeToken = gasFeeTokens?.find(\n (singleGasFeeToken) =>\n singleGasFeeToken.tokenAddress.toLowerCase() ===\n selectedGasFeeToken.toLowerCase(),\n );\n\n if (!gasFeeToken) {\n log('Gas fee token not found', {\n gasFeeTokens,\n selectedGasFeeToken,\n });\n\n return undefined;\n }\n\n return calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n });\n}\n"]}
1
+ {"version":3,"file":"gas.mjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,mCAAmC;AAOnD,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAGzC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,sBAAkB;AAE9D,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,4BAAwB;AAC/D,OAAO,EAAE,kBAAkB,EAAE,uBAAmB;AAChD,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,gBAAgB,EAAE,oBAAgB;AAE5E,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;AAErD;;;;;;;;;GASG;AACH,MAAM,UAAU,2BAA2B,CACzC,WAA4B,EAC5B,SAA4C,EAC5C,EAAE,KAAK,KAA0B,EAAE;IAEnC,MAAM,EACJ,OAAO,EACP,OAAO,EAAE,eAAe,EACxB,gBAAgB,EAChB,QAAQ,GACT,GAAG,WAAW,CAAC;IAEhB,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,YAAY,EAAE,oBAAoB,EAAE,GAAG,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AE,CAAC;AAC9B,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,mCAAmC,CAAC,EAC3C,UAAU,EACV,SAAS,EACT,WAAW,GAKZ;IACC,MAAM,EACJ,OAAO,EACP,YAAY,EACZ,6BAA6B,EAC7B,mBAAmB,GACpB,GAAG,WAAW,CAAC;IAEhB,IACE,CAAC,YAAY;QACb,CAAC,mBAAmB;QACpB,CAAC,6BAA6B,IAAI,UAAU,CAAC,EAC7C,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,GAAG,CAAC,gCAAgC,EAAE,EAAE,mBAAmB,EAAE,OAAO,EAAE,CAAC,CAAC;IAExE,MAAM,WAAW,GAAG,YAAY,EAAE,IAAI,CACpC,CAAC,iBAAiB,EAAE,EAAE,CACpB,iBAAiB,CAAC,YAAY,CAAC,WAAW,EAAE;QAC5C,mBAAmB,CAAC,WAAW,EAAE,CACpC,CAAC;IAEF,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,GAAG,CAAC,yBAAyB,EAAE;YAC7B,YAAY;YACZ,mBAAmB;SACpB,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,wBAAwB,CAAC;QAC9B,OAAO;QACP,WAAW;QACX,SAAS;KACV,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { toHex } from '@metamask/controller-utils';\nimport type { GasFeeEstimates } from '@metamask/gas-fee-controller';\nimport type {\n GasFeeToken,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport type { TransactionPayControllerMessenger } from '..';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { Amount } from '../types';\nimport { getFallbackGas, getGasBuffer } from './feature-flags';\nimport { getNetworkClientId } from './provider';\nimport { getNativeToken, getTokenBalance, getTokenFiatRate } from './token';\n\nconst log = createModuleLogger(projectLogger, 'gas');\n\n/**\n *\n * Calculate the estimated gas cost for a given transaction in fiat.\n *\n * @param transaction - Transaction to calculate gas cost for\n * @param messenger - Controller messenger.\n * @param options - Calculation options.\n * @param options.isMax - Whether to calculate the maximum fee.\n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateTransactionGasCost(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n { isMax }: { isMax?: boolean } = {},\n): Amount & { isGasFeeToken?: boolean } {\n const {\n chainId,\n gasUsed: gasUsedOriginal,\n gasLimitNoBuffer,\n txParams,\n } = transaction;\n\n const { from, gas, maxFeePerGas, maxPriorityFeePerGas } = txParams;\n const gasUsed = isMax ? undefined : gasUsedOriginal;\n const finalGas = gasUsed ?? gasLimitNoBuffer ?? gas ?? '0x0';\n\n const result = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n });\n\n const max = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax: true,\n messenger,\n });\n\n const nativeBalance = getTokenBalance(\n messenger,\n from as Hex,\n chainId,\n getNativeToken(chainId),\n );\n\n const hasBalance = new BigNumber(nativeBalance).gte(max.raw);\n\n const gasFeeTokenCost = calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n });\n\n if (gasFeeTokenCost) {\n return gasFeeTokenCost;\n }\n\n return result;\n}\n\n/**\n * Calculate the gas cost for the specified parameters.\n *\n * @param request - Gas cost calculation parameters.\n * @param request.chainId - ID of the chain.\n * @param request.gas - Amount of gas the transaction will use.\n * @param request.isMax - Whether to calculate the maximum fee.\n * @param request.maxFeePerGas - Max fee to pay per gas.\n * @param request.maxPriorityFeePerGas - Max priority fee to pay per gas.\n * @param request.messenger - Controller messenger.\n \n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateGasCost(request: {\n chainId: number | Hex;\n gas: BigNumber.Value;\n isMax?: boolean;\n maxFeePerGas?: BigNumber.Value;\n maxPriorityFeePerGas?: BigNumber.Value;\n messenger: TransactionPayControllerMessenger;\n}): Amount {\n const {\n chainId: chainIdInput,\n gas,\n isMax,\n maxFeePerGas: maxFeePerGasInput,\n maxPriorityFeePerGas: maxPriorityFeePerGasInput,\n messenger,\n } = request;\n\n const chainId = toHex(chainIdInput);\n\n const {\n estimatedBaseFee,\n maxFeePerGas: maxFeePerGasEstimate,\n maxPriorityFeePerGas: maxPriorityFeePerGasEstimate,\n } = getGasFee(chainId, messenger);\n\n const maxFeePerGas = maxFeePerGasInput ?? maxFeePerGasEstimate;\n\n const maxPriorityFeePerGas =\n maxPriorityFeePerGasInput ?? maxPriorityFeePerGasEstimate;\n\n const feePerGas =\n estimatedBaseFee && maxPriorityFeePerGas && !isMax\n ? new BigNumber(estimatedBaseFee).plus(maxPriorityFeePerGas)\n : new BigNumber(maxFeePerGas ?? '0x0');\n\n const rawValue = new BigNumber(gas).multipliedBy(feePerGas);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-18);\n const human = humanValue.toString(10);\n\n const fiatRate = getTokenFiatRate(\n messenger,\n getNativeToken(chainId),\n chainId,\n );\n\n if (!fiatRate) {\n throw new Error('Could not fetch fiat rate for native token');\n }\n\n const usd = humanValue.multipliedBy(fiatRate.usdRate).toString(10);\n const fiat = humanValue.multipliedBy(fiatRate.fiatRate).toString(10);\n\n return {\n fiat,\n human,\n raw,\n usd,\n };\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.chainId - Chain ID.\n * @param request.gasFeeToken - Gas fee token to calculate cost for.\n * @param request.messenger - Controller messenger.\n * @returns Cost of the gas fee token.\n */\nexport function calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n}: {\n chainId: Hex;\n gasFeeToken: GasFeeToken;\n messenger: TransactionPayControllerMessenger;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const { amount, decimals, tokenAddress } = gasFeeToken;\n\n const tokenFiatRate = getTokenFiatRate(messenger, tokenAddress, chainId);\n\n if (!tokenFiatRate) {\n log('Cannot get gas fee token info');\n return undefined;\n }\n\n const rawValue = new BigNumber(amount);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\n\n const fiat = humanValue.multipliedBy(tokenFiatRate.fiatRate).toString(10);\n const usd = humanValue.multipliedBy(tokenFiatRate.usdRate).toString(10);\n\n return {\n isGasFeeToken: true,\n fiat,\n human,\n raw,\n usd,\n };\n}\n\nexport async function estimateGasLimit({\n chainId,\n data,\n fallbackGas,\n fallbackOnSimulationFailure = false,\n from,\n messenger,\n to,\n value,\n}: {\n chainId: Hex;\n data: Hex;\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure?: boolean;\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n to: Hex;\n value?: Hex;\n}): Promise<{\n estimate: number;\n max: number;\n usedFallback: boolean;\n error?: unknown;\n}> {\n const gasBuffer = getGasBuffer(messenger, chainId);\n const networkClientId = getNetworkClientId(messenger, chainId);\n\n let estimateGasError: unknown;\n let simulationError: Error | undefined;\n\n try {\n const { gas: gasHex, simulationFails } = await messenger.call(\n 'TransactionController:estimateGas',\n { from, data, to, value: value ?? '0x0' },\n networkClientId,\n );\n\n if (simulationFails) {\n simulationError = new Error('Gas simulation failed');\n } else {\n const estimatedGas = parseEstimatedGas(gasHex);\n const bufferedGas = Math.ceil(estimatedGas * gasBuffer);\n\n return {\n estimate: bufferedGas,\n max: bufferedGas,\n usedFallback: false,\n };\n }\n } catch (caughtError) {\n estimateGasError = caughtError;\n }\n\n if (simulationError !== undefined && !fallbackOnSimulationFailure) {\n throw simulationError;\n }\n\n const fallbackGasConfig = fallbackGas ?? getFallbackGas(messenger);\n\n return {\n estimate: fallbackGasConfig.estimate,\n max: fallbackGasConfig.max,\n usedFallback: true,\n error: estimateGasError ?? simulationError,\n };\n}\n\n/**\n * Get gas fee estimates for a given chain.\n *\n * @param chainId - Chain ID.\n * @param messenger - Controller messenger.\n * @returns Gas fee estimates for the chain.\n */\nexport function getGasFee(\n chainId: Hex,\n messenger: TransactionPayControllerMessenger,\n): {\n estimatedBaseFee: string | undefined;\n maxFeePerGas: string | undefined;\n maxPriorityFeePerGas: string | undefined;\n} {\n const gasFeeControllerState = messenger.call('GasFeeController:getState');\n\n const chainState = gasFeeControllerState?.gasFeeEstimatesByChainId?.[chainId];\n\n const { estimatedBaseFee: estimatedBaseFeeGwei, medium } =\n (chainState?.gasFeeEstimates as GasFeeEstimates | undefined) ?? {};\n\n const maxFeePerGasGwei = medium?.suggestedMaxFeePerGas;\n const maxPriorityFeePerGasGwei = medium?.suggestedMaxPriorityFeePerGas;\n\n const estimatedBaseFee = estimatedBaseFeeGwei\n ? new BigNumber(estimatedBaseFeeGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxFeePerGas = maxFeePerGasGwei\n ? new BigNumber(maxFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxPriorityFeePerGas = maxPriorityFeePerGasGwei\n ? new BigNumber(maxPriorityFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n return { estimatedBaseFee, maxFeePerGas, maxPriorityFeePerGas };\n}\n\nfunction parseEstimatedGas(gasValue: string): number {\n const parsedGas = gasValue.startsWith('0x')\n ? new BigNumber(gasValue.slice(2), 16)\n : new BigNumber(gasValue);\n\n if (!parsedGas.isFinite() || parsedGas.isNaN()) {\n throw new Error(`Invalid gas estimate returned: ${gasValue}`);\n }\n\n return parsedGas.toNumber();\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.hasBalance - Whether the user has enough balance to cover the gas fee.\n * @param request.messenger - Controller messenger.\n * @param request.transaction - Transaction to calculate gas fee token cost for.\n * @returns Cost of the gas fee token.\n */\nfunction calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n}: {\n hasBalance: boolean;\n messenger: TransactionPayControllerMessenger;\n transaction: TransactionMeta;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const {\n chainId,\n gasFeeTokens,\n isGasFeeTokenIgnoredIfBalance,\n selectedGasFeeToken,\n } = transaction;\n\n if (\n !gasFeeTokens ||\n !selectedGasFeeToken ||\n (isGasFeeTokenIgnoredIfBalance && hasBalance)\n ) {\n return undefined;\n }\n\n log('Calculating gas fee token cost', { selectedGasFeeToken, chainId });\n\n const gasFeeToken = gasFeeTokens?.find(\n (singleGasFeeToken) =>\n singleGasFeeToken.tokenAddress.toLowerCase() ===\n selectedGasFeeToken.toLowerCase(),\n );\n\n if (!gasFeeToken) {\n log('Gas fee token not found', {\n gasFeeTokens,\n selectedGasFeeToken,\n });\n\n return undefined;\n }\n\n return calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n });\n}\n"]}
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.rpcRequest = exports.getNetworkClientId = void 0;
4
+ const network_controller_1 = require("@metamask/network-controller");
5
+ const utils_1 = require("@metamask/utils");
6
+ const logger_1 = require("../logger.cjs");
7
+ const log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'provider');
8
+ /**
9
+ * Resolve the network client ID for a chain.
10
+ *
11
+ * When `preferInfura` is true the method tries to locate an Infura endpoint
12
+ * in the chain's network configuration and returns its `networkClientId`.
13
+ * If no Infura endpoint is configured, or if the configuration lookup throws,
14
+ * it falls back to `findNetworkClientIdByChainId`.
15
+ *
16
+ * @param messenger - The TransactionPayController messenger.
17
+ * @param chainId - The chain ID to resolve.
18
+ * @param options - Resolution options.
19
+ * @param options.preferInfura - Prefer the Infura endpoint when available.
20
+ * @returns The resolved network client ID.
21
+ */
22
+ function getNetworkClientId(messenger, chainId, { preferInfura = false } = {}) {
23
+ if (preferInfura) {
24
+ try {
25
+ const networkConfiguration = messenger.call('NetworkController:getNetworkConfigurationByChainId', chainId);
26
+ const infuraEndpoint = networkConfiguration?.rpcEndpoints.find((endpoint) => endpoint.type === network_controller_1.RpcEndpointType.Infura);
27
+ if (infuraEndpoint) {
28
+ return infuraEndpoint.networkClientId;
29
+ }
30
+ log('No Infura endpoint found for chain', {
31
+ chainId,
32
+ rpcEndpoints: networkConfiguration?.rpcEndpoints,
33
+ });
34
+ }
35
+ catch (error) {
36
+ log('Error looking up Infura endpoint', { chainId, error });
37
+ }
38
+ }
39
+ return messenger.call('NetworkController:findNetworkClientIdByChainId', chainId);
40
+ }
41
+ exports.getNetworkClientId = getNetworkClientId;
42
+ /**
43
+ * Send an RPC request to the network for the specified chain.
44
+ *
45
+ * @param request - Request parameters.
46
+ * @param request.messenger - The TransactionPayController messenger.
47
+ * @param request.chainId - The chain ID to resolve.
48
+ * @param request.method - The JSON-RPC method name.
49
+ * @param request.params - Optional parameters for the RPC call.
50
+ * @param request.options - Resolution options forwarded to {@link getNetworkClientId}.
51
+ * @returns The RPC response typed as `TResponse`.
52
+ */
53
+ async function rpcRequest({ messenger, chainId, method, params, options, }) {
54
+ const networkClientId = getNetworkClientId(messenger, chainId, options);
55
+ const { provider } = messenger.call('NetworkController:getNetworkClientById', networkClientId);
56
+ const response = await provider.request({ method, params });
57
+ log(method, { chainId, networkClientId, params, response });
58
+ return response;
59
+ }
60
+ exports.rpcRequest = rpcRequest;
61
+ //# sourceMappingURL=provider.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.cjs","sourceRoot":"","sources":["../../src/utils/provider.ts"],"names":[],"mappings":";;;AACA,qEAA+D;AAE/D,2CAAqD;AAErD,0CAA0C;AAG1C,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,UAAU,CAAC,CAAC;AAgC1D;;;;;;;;;;;;;GAaG;AACH,SAAgB,kBAAkB,CAChC,SAA4C,EAC5C,OAAY,EACZ,EAAE,YAAY,GAAG,KAAK,KAAgC,EAAE;IAExD,IAAI,YAAY,EAAE,CAAC;QACjB,IAAI,CAAC;YACH,MAAM,oBAAoB,GAAG,SAAS,CAAC,IAAI,CACzC,oDAAoD,EACpD,OAAO,CACR,CAAC;YAEF,MAAM,cAAc,GAAG,oBAAoB,EAAE,YAAY,CAAC,IAAI,CAC5D,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,KAAK,oCAAe,CAAC,MAAM,CACvD,CAAC;YAEF,IAAI,cAAc,EAAE,CAAC;gBACnB,OAAO,cAAc,CAAC,eAAe,CAAC;YACxC,CAAC;YAED,GAAG,CAAC,oCAAoC,EAAE;gBACxC,OAAO;gBACP,YAAY,EAAE,oBAAoB,EAAE,YAAY;aACjD,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,kCAAkC,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC,IAAI,CACnB,gDAAgD,EAChD,OAAO,CACR,CAAC;AACJ,CAAC;AAjCD,gDAiCC;AAED;;;;;;;;;;GAUG;AACI,KAAK,UAAU,UAAU,CAAsB,EACpD,SAAS,EACT,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,GACU;IACjB,MAAM,eAAe,GAAG,kBAAkB,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAExE,MAAM,EAAE,QAAQ,EAAE,GAAG,SAAS,CAAC,IAAI,CACjC,wCAAwC,EACxC,eAAe,CAChB,CAAC;IAEF,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAE5D,GAAG,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;IAE5D,OAAO,QAAqB,CAAC;AAC/B,CAAC;AAnBD,gCAmBC","sourcesContent":["import type { NetworkClientId, Provider } from '@metamask/network-controller';\nimport { RpcEndpointType } from '@metamask/network-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionPayControllerMessenger } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'provider');\n\ntype ProviderRequestParams = Parameters<Provider['request']>[0]['params'];\n\n/**\n * Options for network client resolution.\n */\nexport type GetNetworkClientIdOptions = {\n /**\n * When true, attempts to resolve to an Infura endpoint for the chain before\n * falling back to the default selected endpoint. Useful for calls that use\n * block tags (e.g. `pending`) that may not be supported by custom RPCs.\n */\n preferInfura?: boolean;\n};\n\n/**\n * Parameters for {@link rpcRequest}.\n */\nexport type RpcRequestParams = {\n /** The TransactionPayController messenger. */\n messenger: TransactionPayControllerMessenger;\n /** The chain ID to resolve. */\n chainId: Hex;\n /** The JSON-RPC method name. */\n method: string;\n /** Optional parameters for the RPC call. */\n params?: ProviderRequestParams;\n /** Resolution options forwarded to {@link getNetworkClientId}. */\n options?: GetNetworkClientIdOptions;\n};\n\n/**\n * Resolve the network client ID for a chain.\n *\n * When `preferInfura` is true the method tries to locate an Infura endpoint\n * in the chain's network configuration and returns its `networkClientId`.\n * If no Infura endpoint is configured, or if the configuration lookup throws,\n * it falls back to `findNetworkClientIdByChainId`.\n *\n * @param messenger - The TransactionPayController messenger.\n * @param chainId - The chain ID to resolve.\n * @param options - Resolution options.\n * @param options.preferInfura - Prefer the Infura endpoint when available.\n * @returns The resolved network client ID.\n */\nexport function getNetworkClientId(\n messenger: TransactionPayControllerMessenger,\n chainId: Hex,\n { preferInfura = false }: GetNetworkClientIdOptions = {},\n): NetworkClientId {\n if (preferInfura) {\n try {\n const networkConfiguration = messenger.call(\n 'NetworkController:getNetworkConfigurationByChainId',\n chainId,\n );\n\n const infuraEndpoint = networkConfiguration?.rpcEndpoints.find(\n (endpoint) => endpoint.type === RpcEndpointType.Infura,\n );\n\n if (infuraEndpoint) {\n return infuraEndpoint.networkClientId;\n }\n\n log('No Infura endpoint found for chain', {\n chainId,\n rpcEndpoints: networkConfiguration?.rpcEndpoints,\n });\n } catch (error) {\n log('Error looking up Infura endpoint', { chainId, error });\n }\n }\n\n return messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n chainId,\n );\n}\n\n/**\n * Send an RPC request to the network for the specified chain.\n *\n * @param request - Request parameters.\n * @param request.messenger - The TransactionPayController messenger.\n * @param request.chainId - The chain ID to resolve.\n * @param request.method - The JSON-RPC method name.\n * @param request.params - Optional parameters for the RPC call.\n * @param request.options - Resolution options forwarded to {@link getNetworkClientId}.\n * @returns The RPC response typed as `TResponse`.\n */\nexport async function rpcRequest<TResponse = unknown>({\n messenger,\n chainId,\n method,\n params,\n options,\n}: RpcRequestParams): Promise<TResponse> {\n const networkClientId = getNetworkClientId(messenger, chainId, options);\n\n const { provider } = messenger.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n\n const response = await provider.request({ method, params });\n\n log(method, { chainId, networkClientId, params, response });\n\n return response as TResponse;\n}\n"]}
@@ -0,0 +1,59 @@
1
+ import type { NetworkClientId, Provider } from "@metamask/network-controller";
2
+ import type { Hex } from "@metamask/utils";
3
+ import type { TransactionPayControllerMessenger } from "../types.cjs";
4
+ type ProviderRequestParams = Parameters<Provider['request']>[0]['params'];
5
+ /**
6
+ * Options for network client resolution.
7
+ */
8
+ export type GetNetworkClientIdOptions = {
9
+ /**
10
+ * When true, attempts to resolve to an Infura endpoint for the chain before
11
+ * falling back to the default selected endpoint. Useful for calls that use
12
+ * block tags (e.g. `pending`) that may not be supported by custom RPCs.
13
+ */
14
+ preferInfura?: boolean;
15
+ };
16
+ /**
17
+ * Parameters for {@link rpcRequest}.
18
+ */
19
+ export type RpcRequestParams = {
20
+ /** The TransactionPayController messenger. */
21
+ messenger: TransactionPayControllerMessenger;
22
+ /** The chain ID to resolve. */
23
+ chainId: Hex;
24
+ /** The JSON-RPC method name. */
25
+ method: string;
26
+ /** Optional parameters for the RPC call. */
27
+ params?: ProviderRequestParams;
28
+ /** Resolution options forwarded to {@link getNetworkClientId}. */
29
+ options?: GetNetworkClientIdOptions;
30
+ };
31
+ /**
32
+ * Resolve the network client ID for a chain.
33
+ *
34
+ * When `preferInfura` is true the method tries to locate an Infura endpoint
35
+ * in the chain's network configuration and returns its `networkClientId`.
36
+ * If no Infura endpoint is configured, or if the configuration lookup throws,
37
+ * it falls back to `findNetworkClientIdByChainId`.
38
+ *
39
+ * @param messenger - The TransactionPayController messenger.
40
+ * @param chainId - The chain ID to resolve.
41
+ * @param options - Resolution options.
42
+ * @param options.preferInfura - Prefer the Infura endpoint when available.
43
+ * @returns The resolved network client ID.
44
+ */
45
+ export declare function getNetworkClientId(messenger: TransactionPayControllerMessenger, chainId: Hex, { preferInfura }?: GetNetworkClientIdOptions): NetworkClientId;
46
+ /**
47
+ * Send an RPC request to the network for the specified chain.
48
+ *
49
+ * @param request - Request parameters.
50
+ * @param request.messenger - The TransactionPayController messenger.
51
+ * @param request.chainId - The chain ID to resolve.
52
+ * @param request.method - The JSON-RPC method name.
53
+ * @param request.params - Optional parameters for the RPC call.
54
+ * @param request.options - Resolution options forwarded to {@link getNetworkClientId}.
55
+ * @returns The RPC response typed as `TResponse`.
56
+ */
57
+ export declare function rpcRequest<TResponse = unknown>({ messenger, chainId, method, params, options, }: RpcRequestParams): Promise<TResponse>;
58
+ export {};
59
+ //# sourceMappingURL=provider.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.cts","sourceRoot":"","sources":["../../src/utils/provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,QAAQ,EAAE,qCAAqC;AAE9E,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAI3C,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAiB;AAIlE,KAAK,qBAAqB,GAAG,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;AAE1E;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC;;;;OAIG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,8CAA8C;IAC9C,SAAS,EAAE,iCAAiC,CAAC;IAC7C,+BAA+B;IAC/B,OAAO,EAAE,GAAG,CAAC;IACb,gCAAgC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,4CAA4C;IAC5C,MAAM,CAAC,EAAE,qBAAqB,CAAC;IAC/B,kEAAkE;IAClE,OAAO,CAAC,EAAE,yBAAyB,CAAC;CACrC,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,iCAAiC,EAC5C,OAAO,EAAE,GAAG,EACZ,EAAE,YAAoB,EAAE,GAAE,yBAA8B,GACvD,eAAe,CA6BjB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,UAAU,CAAC,SAAS,GAAG,OAAO,EAAE,EACpD,SAAS,EACT,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,GACR,EAAE,gBAAgB,GAAG,OAAO,CAAC,SAAS,CAAC,CAavC"}
@@ -0,0 +1,59 @@
1
+ import type { NetworkClientId, Provider } from "@metamask/network-controller";
2
+ import type { Hex } from "@metamask/utils";
3
+ import type { TransactionPayControllerMessenger } from "../types.mjs";
4
+ type ProviderRequestParams = Parameters<Provider['request']>[0]['params'];
5
+ /**
6
+ * Options for network client resolution.
7
+ */
8
+ export type GetNetworkClientIdOptions = {
9
+ /**
10
+ * When true, attempts to resolve to an Infura endpoint for the chain before
11
+ * falling back to the default selected endpoint. Useful for calls that use
12
+ * block tags (e.g. `pending`) that may not be supported by custom RPCs.
13
+ */
14
+ preferInfura?: boolean;
15
+ };
16
+ /**
17
+ * Parameters for {@link rpcRequest}.
18
+ */
19
+ export type RpcRequestParams = {
20
+ /** The TransactionPayController messenger. */
21
+ messenger: TransactionPayControllerMessenger;
22
+ /** The chain ID to resolve. */
23
+ chainId: Hex;
24
+ /** The JSON-RPC method name. */
25
+ method: string;
26
+ /** Optional parameters for the RPC call. */
27
+ params?: ProviderRequestParams;
28
+ /** Resolution options forwarded to {@link getNetworkClientId}. */
29
+ options?: GetNetworkClientIdOptions;
30
+ };
31
+ /**
32
+ * Resolve the network client ID for a chain.
33
+ *
34
+ * When `preferInfura` is true the method tries to locate an Infura endpoint
35
+ * in the chain's network configuration and returns its `networkClientId`.
36
+ * If no Infura endpoint is configured, or if the configuration lookup throws,
37
+ * it falls back to `findNetworkClientIdByChainId`.
38
+ *
39
+ * @param messenger - The TransactionPayController messenger.
40
+ * @param chainId - The chain ID to resolve.
41
+ * @param options - Resolution options.
42
+ * @param options.preferInfura - Prefer the Infura endpoint when available.
43
+ * @returns The resolved network client ID.
44
+ */
45
+ export declare function getNetworkClientId(messenger: TransactionPayControllerMessenger, chainId: Hex, { preferInfura }?: GetNetworkClientIdOptions): NetworkClientId;
46
+ /**
47
+ * Send an RPC request to the network for the specified chain.
48
+ *
49
+ * @param request - Request parameters.
50
+ * @param request.messenger - The TransactionPayController messenger.
51
+ * @param request.chainId - The chain ID to resolve.
52
+ * @param request.method - The JSON-RPC method name.
53
+ * @param request.params - Optional parameters for the RPC call.
54
+ * @param request.options - Resolution options forwarded to {@link getNetworkClientId}.
55
+ * @returns The RPC response typed as `TResponse`.
56
+ */
57
+ export declare function rpcRequest<TResponse = unknown>({ messenger, chainId, method, params, options, }: RpcRequestParams): Promise<TResponse>;
58
+ export {};
59
+ //# sourceMappingURL=provider.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.mts","sourceRoot":"","sources":["../../src/utils/provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,QAAQ,EAAE,qCAAqC;AAE9E,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAI3C,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAiB;AAIlE,KAAK,qBAAqB,GAAG,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;AAE1E;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC;;;;OAIG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,8CAA8C;IAC9C,SAAS,EAAE,iCAAiC,CAAC;IAC7C,+BAA+B;IAC/B,OAAO,EAAE,GAAG,CAAC;IACb,gCAAgC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,4CAA4C;IAC5C,MAAM,CAAC,EAAE,qBAAqB,CAAC;IAC/B,kEAAkE;IAClE,OAAO,CAAC,EAAE,yBAAyB,CAAC;CACrC,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,iCAAiC,EAC5C,OAAO,EAAE,GAAG,EACZ,EAAE,YAAoB,EAAE,GAAE,yBAA8B,GACvD,eAAe,CA6BjB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,UAAU,CAAC,SAAS,GAAG,OAAO,EAAE,EACpD,SAAS,EACT,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,GACR,EAAE,gBAAgB,GAAG,OAAO,CAAC,SAAS,CAAC,CAavC"}