@metamask-previews/transaction-pay-controller 29.2.3-preview-e45297452 → 30.0.0-preview-bba5d41
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.
- package/CHANGELOG.md +3 -8
- package/dist/TransactionPayController-method-action-types.d.ts +1 -14
- package/dist/TransactionPayController-method-action-types.d.ts.map +1 -1
- package/dist/TransactionPayController-method-action-types.js.map +1 -1
- package/dist/TransactionPayController.d.ts +2 -12
- package/dist/TransactionPayController.d.ts.map +1 -1
- package/dist/TransactionPayController.js +1 -17
- package/dist/TransactionPayController.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/strategy/relay/relay-quotes.js +3 -7
- package/dist/strategy/relay/relay-quotes.js.map +1 -1
- package/dist/strategy/relay/relay-submit.d.ts.map +1 -1
- package/dist/strategy/relay/relay-submit.js +9 -7
- package/dist/strategy/relay/relay-submit.js.map +1 -1
- package/dist/strategy/relay/types.d.ts +0 -5
- package/dist/strategy/relay/types.d.ts.map +1 -1
- package/dist/strategy/relay/types.js.map +1 -1
- package/dist/types.d.ts +0 -14
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/ma-vault-deposit.js +1 -1
- package/dist/utils/ma-vault-deposit.js.map +1 -1
- package/dist/utils/quotes.d.ts.map +1 -1
- package/dist/utils/quotes.js +17 -1
- package/dist/utils/quotes.js.map +1 -1
- package/package.json +1 -1
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA6PA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type { AccountsControllerGetStateAction } from '@metamask/accounts-controller';\nimport type {\n AssetsControllerGetStateAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringControllerUnlockEvent,\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 RampsControllerGetQuoteWithFeesAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SentinelApiServiceActions } from '@metamask/sentinel-api-service';\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.js';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types.js';\n\nexport type AllowedActions =\n | AccountsControllerGetStateAction\n | AssetsControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByChainIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuoteWithFeesAction\n | RemoteFeatureFlagControllerGetStateAction\n | SentinelApiServiceActions\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | KeyringControllerUnlockEvent\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 target transaction (or `paymentOverride` batch) is executed\n * atomically with the Relay quote. Defaults to `true` (embedded in the quote\n * and executed by the Relay solver). When `false`, Pay does not embed the\n * target/override calls in the quote; the quote only bridges the required\n * asset to `recipient`, and the calls are submitted separately after Relay\n * completion. Used by flows whose second-leg amount is only known after\n * Relay settles (EXACT_INPUT max flows) or that require the second leg to\n * originate from a different signer than the Relay solver.\n * For max deposits enabled by `payStrategies.relay.atomicMaxEnabled`, this\n * is a subsidy hint: atomic quotes are retried non-atomically if not\n * subsidized, and subsidized non-atomic quotes are upgraded to atomic.\n */\n atomic?: boolean;\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 /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\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 /** Optional recipient address for the funding token transfer. */\n recipient?: Hex;\n\n /** Optional EIP-7702 authorization list from delegation. */\n authorizationList?: AuthorizationList;\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\nexport type GetAmountDataRequest = {\n /** Raw token amount (atomic units) to encode into calldata. */\n amount: string;\n\n /** Metadata of the transaction whose nested calls need updating. */\n transaction: TransactionMeta;\n};\n\nexport type GetAmountDataResponse = {\n /** Per-nested-call data updates; empty when no update is needed. */\n updates: { nestedTransactionIndex: number; data: Hex }[];\n};\n\n/**\n * Optional callback that re-encodes nested transaction calldata for a given\n * token amount. Used by transaction types with non-standard nested data\n * (e.g. vault approve + deposit) that cannot be derived from the amount alone\n * without client-side context (vault config, RPC providers, etc.).\n */\nexport type GetAmountDataCallback = (\n request: GetAmountDataRequest,\n) => Promise<GetAmountDataResponse>;\n\n/** Request passed to {@link GetBalanceCallback}. */\nexport type GetBalanceRequest = {\n /** Metadata of the transaction whose source balance is being resolved. */\n transaction: TransactionMeta;\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Balance override returned by {@link GetBalanceCallback}. */\nexport type GetBalanceResponse = {\n /** Balance in atomic format without factoring token decimals. */\n balanceRaw: string;\n};\n\n/**\n * Optional client-supplied callback that overrides the built-in\n * pay-token / required-token balance lookup used for `isMaxAmount`\n * source-amount calculation. Enables alternate balance sources\n * (perps, predict, money-account, post-quote, etc.) without adding\n * conditional branches inside the controller. MUST be synchronous:\n * it runs inside the controller state-update block.\n * Return `undefined` to fall back to the built-in token balance.\n */\nexport type GetBalanceCallback = (\n request: GetBalanceRequest,\n) => GetBalanceResponse | undefined;\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 /** Optional callback to re-encode nested transaction calldata for a given amount. */\n getAmountData?: GetAmountDataCallback;\n\n /** Optional callback to override the source balance used for max-amount calculation. */\n getBalance?: GetBalanceCallback;\n\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** Optional fiat execution configuration. */\n fiatOptions?: TransactionPayFiatOptions;\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 /**\n * Callback to determine whether the gas fee of a transaction is sponsored.\n * Used when quoting and submitting source transactions so both use the same\n * client-owned sponsorship decision. Defaults to not sponsored.\n */\n isGasFeeSponsored?: IsGasFeeSponsoredCallback;\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/** Optional fiat execution configuration. */\nexport type TransactionPayFiatOptions = {\n /** Test funding source used to bypass fiat on-ramp execution during local QA. */\n testFundingSource?: Hex;\n\n /** Optional human amount to transfer from the test funding source. */\n testAmountOverride?: string;\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 /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\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 /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\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 /** Most relevant structured validation error from the latest quote attempt. */\n quoteError?: QuoteErrorInfo;\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/**\n * Machine-readable discriminator for a quote validation failure.\n *\n * Used for analytics and tests. Human-readable copy is carried by `message`\n * and `detail` on {@link QuoteErrorInfo}.\n */\nexport type QuoteErrorReason =\n | 'balance-unavailable'\n | 'insufficient-source-balance'\n | 'insufficient-transfer-balance'\n | 'no-quotes'\n | 'simulation-failed';\n\n/**\n * Structured description of why a quote failed validation.\n *\n * `message` and `detail` are formatted (English) copy ready to display; `reason`\n * is a machine-readable discriminator for analytics and tests.\n */\nexport type QuoteErrorInfo = {\n /** Short, display-ready summary of the failure. */\n message: string;\n\n /** Machine-readable discriminator for the failure. */\n reason: QuoteErrorReason;\n\n /** Optional display-ready detail rows (e.g. Required / Current / Missing). */\n detail?: string[];\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 /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\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 /** Whether this quote is the direct mUSD-to-Money-Account fiat flow. */\n isDirectMusdMoneyAccount?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** Optional recipient address for Relay requests. When set, overrides the default `from` address. */\n recipient?: Hex;\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 /** Whether to skip processTransactions in relay-quotes. Defaults to `isPostQuote`. */\n skipProcessTransactions?: boolean;\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 * One-time HyperLiquid activation fee (USD) reserved from the source amount\n * for an unactivated HyperCore account. The source amount sent to the\n * provider is reduced by this amount so HyperLiquid retains enough balance\n * for the fee, and the amount is surfaced as part of the provider fee.\n */\n hyperliquidActivationFeeUsd?: string;\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 /** Whether fees are subtracted from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Whether the reported fees are already included in the source amount. */\n areFeesIncludedInSourceAmount?: boolean;\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 /**\n * Resolved wallet address for the transaction.\n * This is `accountOverride ?? txParams.from`, pre-computed by the quote\n * orchestrator so that individual strategies do not need to re-derive it.\n */\n from: Hex;\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 /** Whether the selected quotes subtract fees from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\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 determine whether the gas fee of a transaction is sponsored. */\nexport type IsGasFeeSponsoredCallback = (request: {\n /** Metadata of the transaction. */\n transaction: TransactionMeta;\n}) => Promise<{\n /** Whether the gas fee of the transaction is sponsored. */\n isGasFeeSponsored: boolean;\n}>;\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n isSubsidized,\n}: {\n transaction: TransactionMeta;\n isSubsidized?: boolean;\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.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA6PA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type { AccountsControllerGetStateAction } from '@metamask/accounts-controller';\nimport type {\n AssetsControllerGetStateAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringControllerUnlockEvent,\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 RampsControllerGetQuoteWithFeesAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SentinelApiServiceActions } from '@metamask/sentinel-api-service';\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.js';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types.js';\n\nexport type AllowedActions =\n | AccountsControllerGetStateAction\n | AssetsControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByChainIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuoteWithFeesAction\n | RemoteFeatureFlagControllerGetStateAction\n | SentinelApiServiceActions\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | KeyringControllerUnlockEvent\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 target transaction (or `paymentOverride` batch) is executed\n * atomically with the Relay quote. Defaults to `true` (embedded in the quote\n * and executed by the Relay solver). When `false`, Pay does not embed the\n * target/override calls in the quote; the quote only bridges the required\n * asset to `recipient`, and the calls are submitted separately after Relay\n * completion. Used by flows whose second-leg amount is only known after\n * Relay settles (EXACT_INPUT max flows) or that require the second leg to\n * originate from a different signer than the Relay solver.\n * For max deposits enabled by `payStrategies.relay.atomicMaxEnabled`, this\n * is a subsidy hint: atomic quotes are retried non-atomically if not\n * subsidized, and subsidized non-atomic quotes are upgraded to atomic.\n */\n atomic?: boolean;\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 /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\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 /** Optional recipient address for the funding token transfer. */\n recipient?: Hex;\n\n /** Optional EIP-7702 authorization list from delegation. */\n authorizationList?: AuthorizationList;\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\nexport type GetAmountDataRequest = {\n /** Raw token amount (atomic units) to encode into calldata. */\n amount: string;\n\n /** Metadata of the transaction whose nested calls need updating. */\n transaction: TransactionMeta;\n};\n\nexport type GetAmountDataResponse = {\n /** Per-nested-call data updates; empty when no update is needed. */\n updates: { nestedTransactionIndex: number; data: Hex }[];\n};\n\n/**\n * Optional callback that re-encodes nested transaction calldata for a given\n * token amount. Used by transaction types with non-standard nested data\n * (e.g. vault approve + deposit) that cannot be derived from the amount alone\n * without client-side context (vault config, RPC providers, etc.).\n */\nexport type GetAmountDataCallback = (\n request: GetAmountDataRequest,\n) => Promise<GetAmountDataResponse>;\n\n/** Request passed to {@link GetBalanceCallback}. */\nexport type GetBalanceRequest = {\n /** Metadata of the transaction whose source balance is being resolved. */\n transaction: TransactionMeta;\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Balance override returned by {@link GetBalanceCallback}. */\nexport type GetBalanceResponse = {\n /** Balance in atomic format without factoring token decimals. */\n balanceRaw: string;\n};\n\n/**\n * Optional client-supplied callback that overrides the built-in\n * pay-token / required-token balance lookup used for `isMaxAmount`\n * source-amount calculation. Enables alternate balance sources\n * (perps, predict, money-account, post-quote, etc.) without adding\n * conditional branches inside the controller. MUST be synchronous:\n * it runs inside the controller state-update block.\n * Return `undefined` to fall back to the built-in token balance.\n */\nexport type GetBalanceCallback = (\n request: GetBalanceRequest,\n) => GetBalanceResponse | undefined;\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 /** Optional callback to re-encode nested transaction calldata for a given amount. */\n getAmountData?: GetAmountDataCallback;\n\n /** Optional callback to override the source balance used for max-amount calculation. */\n getBalance?: GetBalanceCallback;\n\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** Optional fiat execution configuration. */\n fiatOptions?: TransactionPayFiatOptions;\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/** Optional fiat execution configuration. */\nexport type TransactionPayFiatOptions = {\n /** Test funding source used to bypass fiat on-ramp execution during local QA. */\n testFundingSource?: Hex;\n\n /** Optional human amount to transfer from the test funding source. */\n testAmountOverride?: string;\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 /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\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 /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\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 /** Most relevant structured validation error from the latest quote attempt. */\n quoteError?: QuoteErrorInfo;\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/**\n * Machine-readable discriminator for a quote validation failure.\n *\n * Used for analytics and tests. Human-readable copy is carried by `message`\n * and `detail` on {@link QuoteErrorInfo}.\n */\nexport type QuoteErrorReason =\n | 'balance-unavailable'\n | 'insufficient-source-balance'\n | 'insufficient-transfer-balance'\n | 'no-quotes'\n | 'simulation-failed';\n\n/**\n * Structured description of why a quote failed validation.\n *\n * `message` and `detail` are formatted (English) copy ready to display; `reason`\n * is a machine-readable discriminator for analytics and tests.\n */\nexport type QuoteErrorInfo = {\n /** Short, display-ready summary of the failure. */\n message: string;\n\n /** Machine-readable discriminator for the failure. */\n reason: QuoteErrorReason;\n\n /** Optional display-ready detail rows (e.g. Required / Current / Missing). */\n detail?: string[];\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 /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\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 /** Whether this quote is the direct mUSD-to-Money-Account fiat flow. */\n isDirectMusdMoneyAccount?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** Optional recipient address for Relay requests. When set, overrides the default `from` address. */\n recipient?: Hex;\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 /** Whether to skip processTransactions in relay-quotes. Defaults to `isPostQuote`. */\n skipProcessTransactions?: boolean;\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 * One-time HyperLiquid activation fee (USD) reserved from the source amount\n * for an unactivated HyperCore account. The source amount sent to the\n * provider is reduced by this amount so HyperLiquid retains enough balance\n * for the fee, and the amount is surfaced as part of the provider fee.\n */\n hyperliquidActivationFeeUsd?: string;\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 /** Whether fees are subtracted from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Whether the reported fees are already included in the source amount. */\n areFeesIncludedInSourceAmount?: boolean;\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 /**\n * Resolved wallet address for the transaction.\n * This is `accountOverride ?? txParams.from`, pre-computed by the quote\n * orchestrator so that individual strategies do not need to re-derive it.\n */\n from: Hex;\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 /** Whether the selected quotes subtract fees from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\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 isSubsidized,\n}: {\n transaction: TransactionMeta;\n isSubsidized?: boolean;\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"]}
|
|
@@ -92,8 +92,8 @@ export async function submitMoneyAccountVaultDeposit({ fromBlock, messenger, mon
|
|
|
92
92
|
disableHook: true,
|
|
93
93
|
disableSequential: true,
|
|
94
94
|
disableUpgrade: true,
|
|
95
|
-
forceIsGasFeeSponsored: true,
|
|
96
95
|
from: moneyAccountAddress,
|
|
96
|
+
isGasFeeSponsored: true,
|
|
97
97
|
isInternal: true,
|
|
98
98
|
networkClientId,
|
|
99
99
|
origin: ORIGIN_METAMASK,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ma-vault-deposit.js","sourceRoot":"","sources":["../../src/utils/ma-vault-deposit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAA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AC;IACL,CAAC;IAAC,OAAO,UAAU,EAAE,CAAC;QACpB,GAAG,CAAC,oBAAoB,EAAE,EAAE,UAAU,EAAE,aAAa,EAAE,CAAC,CAAC;QACzD,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["import { ORIGIN_METAMASK } from '@metamask/controller-utils';\nimport type {\n BatchTransactionParams,\n NestedTransactionMetadata,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger.js';\nimport { MUSD_MONAD_FIAT_ASSET } from '../strategy/fiat/constants.js';\nimport type { TransactionPayControllerMessenger } from '../types.js';\nimport { findRecentChompVaultDeposit } from './chomp.js';\nimport { prefixError } from './error-prefix.js';\nimport { getNetworkClientId } from './provider.js';\nimport {\n collectTransactionIds,\n getTransaction,\n updateTransaction,\n waitForTransactionConfirmed,\n} from './transaction.js';\n\nconst log = createModuleLogger(projectLogger, 'ma-vault-deposit');\n\nexport const VAULT_ERROR_PREFIX = 'Vault: ';\n\n/**\n * Submits a Money Account mUSD vault deposit batch on Monad once the source\n * mUSD has settled in the Money Account (fiat on-ramp, Relay bridge, or any\n * other path). Re-encodes the original nested vault calldata with the\n * settled `sourceAmountRaw` via `getAmountData` and submits as a sponsored,\n * internal EIP-7702 batch. Callers decide whether to honour any vault\n * kill-switch by passing `vaultDisabled`.\n *\n * @param options - Submit options.\n * @param options.fromBlock - Block number to start searching for CHOMP deposits.\n * @param options.messenger - Controller messenger.\n * @param options.moneyAccountAddress - Money Account address sending the vault\n * deposit. Defaults to `transaction.txParams.from` (the deposit-flow sender);\n * withdraw flows pass it explicitly since their `from` is the funding EOA.\n * @param options.depositCalls - Pre-built vault-deposit batch for withdraw\n * flows, whose parent transaction carries no vault calls. When omitted the\n * batch is derived from the transaction's own nested calls re-encoded via\n * `getAmountData`.\n * @param options.sourceAmountRaw - Settled mUSD amount in raw units.\n * @param options.transaction - Original Money Account transaction meta.\n * @param options.vaultDisabled - When `true`, skip the vault batch and leave\n * the settled mUSD in the Money Account. Caller-evaluated kill-switch.\n * @returns Hash of the final submitted child transaction, if available.\n */\nexport async function submitMoneyAccountVaultDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress: moneyAccountAddressOverride,\n depositCalls,\n sourceAmountRaw,\n transaction,\n vaultDisabled,\n}: {\n fromBlock?: Hex;\n messenger: TransactionPayControllerMessenger;\n moneyAccountAddress?: Hex;\n depositCalls?: BatchTransactionParams[];\n sourceAmountRaw: string;\n transaction: TransactionMeta;\n vaultDisabled: boolean;\n}): Promise<{ transactionHash?: Hex }> {\n const transactionId = transaction.id;\n const moneyAccountAddress = (moneyAccountAddressOverride ??\n transaction.txParams.from) as Hex | undefined;\n\n if (!moneyAccountAddress) {\n throw new Error('Missing Money Account address');\n }\n\n if (vaultDisabled) {\n log('Skipping vault deposit because vaultDisabled is true', {\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n });\n\n return { transactionHash: '0x' };\n }\n\n const nestedTransactions = await resolveVaultDepositBatch({\n depositCalls,\n messenger,\n sourceAmountRaw,\n transaction,\n transactionId,\n });\n\n // CHOMP pre-check: skip addTransactionBatch entirely if CHOMP has already\n // auto-vaulted the funds during or before the checkout window.\n const preChompHash = await tryFindChompDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n });\n\n if (preChompHash) {\n return { transactionHash: preChompHash };\n }\n\n const networkClientId = getNetworkClientId(\n messenger,\n MUSD_MONAD_FIAT_ASSET.chainId,\n );\n const transactionIds: string[] = [];\n const { end } = collectTransactionIds(\n MUSD_MONAD_FIAT_ASSET.chainId,\n moneyAccountAddress,\n messenger,\n (id) => {\n transactionIds.push(id);\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Add required transaction ID from Money Account vault submission',\n },\n (tx) => {\n tx.requiredTransactionIds ??= [];\n tx.requiredTransactionIds.push(id);\n },\n );\n },\n );\n\n log('Submitting Money Account vault deposit', {\n moneyAccountAddress,\n nestedTransactionCount: nestedTransactions.length,\n networkClientId,\n sourceAmountRaw,\n transactionId,\n });\n\n try {\n await messenger.call('TransactionController:addTransactionBatch', {\n disableHook: true,\n disableSequential: true,\n disableUpgrade: true,\n forceIsGasFeeSponsored: true,\n from: moneyAccountAddress,\n isInternal: true,\n networkClientId,\n origin: ORIGIN_METAMASK,\n requireApproval: false,\n skipInitialGasEstimate: true,\n transactions: nestedTransactions.map((nestedTransaction, index) => ({\n params: {\n data: nestedTransaction.data,\n to: nestedTransaction.to,\n value: nestedTransaction.value ?? '0x0',\n },\n type:\n index === 0\n ? (nestedTransaction.type ?? TransactionType.tokenMethodApprove)\n : TransactionType.contractInteraction,\n })),\n });\n } catch (error) {\n // CHOMP post-check: CHOMP may have won the race between pre-check and\n // submit. Return the CHOMP hash instead of surfacing a Vault-prefixed error.\n const postChompHash = await tryFindChompDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n });\n\n if (postChompHash) {\n return { transactionHash: postChompHash };\n }\n\n throw prefixError(error, VAULT_ERROR_PREFIX);\n } finally {\n end();\n }\n\n log('Submitted Money Account vault deposit', {\n moneyAccountAddress,\n nestedTransactionCount: nestedTransactions.length,\n networkClientId,\n sourceAmountRaw,\n transactionId,\n transactionIds,\n });\n\n if (!transactionIds.length) {\n throw new Error('No transactions submitted');\n }\n\n await Promise.all(\n transactionIds.map((id) => waitForTransactionConfirmed(id, messenger)),\n );\n\n const hash = getTransaction(transactionIds.slice(-1)[0], messenger)?.hash;\n\n if (!hash) {\n throw new Error('Missing transaction hash');\n }\n\n log('Confirmed Money Account vault deposit', {\n hash,\n moneyAccountAddress,\n nestedTransactionCount: nestedTransactions.length,\n networkClientId,\n sourceAmountRaw,\n transactionId,\n transactionIds,\n });\n\n return { transactionHash: hash as Hex };\n}\n\n/**\n * Resolves the vault-deposit batch (approve + teller deposit) to submit.\n *\n * Withdraw flows have no vault calls on their own nested transactions, so the\n * caller supplies a freshly built `depositCalls` batch. Deposit flows re-encode\n * their existing nested vault calldata with the settled amount via\n * `getAmountData` and also mutate the parent transaction so its stored calls\n * and `requiredAssets` reflect the settled amount.\n *\n * @param options - Resolution options.\n * @param options.depositCalls - Pre-built deposit batch for withdraw flows.\n * @param options.messenger - Controller messenger.\n * @param options.sourceAmountRaw - Settled mUSD amount in raw units.\n * @param options.transaction - Original Money Account transaction meta.\n * @param options.transactionId - ID of the original transaction.\n * @returns Nested transactions to submit as the vault deposit batch.\n */\nasync function resolveVaultDepositBatch({\n depositCalls,\n messenger,\n sourceAmountRaw,\n transaction,\n transactionId,\n}: {\n depositCalls?: BatchTransactionParams[];\n messenger: TransactionPayControllerMessenger;\n sourceAmountRaw: string;\n transaction: TransactionMeta;\n transactionId: string;\n}): Promise<NestedTransactionMetadata[]> {\n if (depositCalls?.length) {\n return depositCalls;\n }\n\n const updatedTransaction =\n getTransaction(transactionId, messenger) ?? transaction;\n const { updates } = await messenger.call(\n 'TransactionPayController:getAmountData',\n {\n amount: sourceAmountRaw,\n transaction: updatedTransaction,\n },\n );\n\n if (!updates.length) {\n throw new Error('No amount updates');\n }\n\n const nestedTransactions = updatedTransaction.nestedTransactions?.map(\n (nestedTransaction) => ({ ...nestedTransaction }),\n );\n\n if (!nestedTransactions?.length) {\n throw new Error('Missing nested transactions');\n }\n\n for (const { nestedTransactionIndex, data } of updates) {\n if (nestedTransactions[nestedTransactionIndex]) {\n nestedTransactions[nestedTransactionIndex].data = data;\n }\n }\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Money Account vault deposit: update vault amount',\n },\n (tx) => {\n for (const { nestedTransactionIndex, data } of updates) {\n if (tx.nestedTransactions?.[nestedTransactionIndex]) {\n tx.nestedTransactions[nestedTransactionIndex].data = data;\n }\n }\n\n if (tx.requiredAssets?.[0]) {\n tx.requiredAssets[0].amount = `0x${BigInt(sourceAmountRaw).toString(\n 16,\n )}`;\n }\n },\n );\n\n return nestedTransactions;\n}\n\nasync function tryFindChompDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n}: {\n fromBlock: Hex | undefined;\n messenger: TransactionPayControllerMessenger;\n moneyAccountAddress: Hex;\n sourceAmountRaw: string;\n transactionId: string;\n}): Promise<Hex | undefined> {\n if (!fromBlock) {\n return undefined;\n }\n\n try {\n return await findRecentChompVaultDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n });\n } catch (chompError) {\n log('CHOMP check failed', { chompError, transactionId });\n return undefined;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ma-vault-deposit.js","sourceRoot":"","sources":["../../src/utils/ma-vault-deposit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAM7D,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAEnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAEtE,OAAO,EAAE,2BAA2B,EAAE,MAAM,YAAY,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,iBAAiB,EACjB,2BAA2B,GAC5B,MAAM,kBAAkB,CAAC;AAE1B,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,kBAAkB,CAAC,CAAC;AAElE,MAAM,CAAC,MAAM,kBAAkB,GAAG,SAAS,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,EACnD,SAAS,EACT,SAAS,EACT,mBAAm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,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC3B,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,MAAM,CAAC,eAAe,CAAC,CAAC,QAAQ,CACjE,EAAE,CACH,EAAE,CAAC;QACN,CAAC;IACH,CAAC,CACF,CAAC;IAEF,OAAO,kBAAkB,CAAC;AAC5B,CAAC;AAED,KAAK,UAAU,mBAAmB,CAAC,EACjC,SAAS,EACT,SAAS,EACT,mBAAmB,EACnB,eAAe,EACf,aAAa,GAOd;IACC,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,CAAC;QACH,OAAO,MAAM,2BAA2B,CAAC;YACvC,SAAS;YACT,SAAS;YACT,mBAAmB;YACnB,eAAe;SAChB,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,UAAU,EAAE,CAAC;QACpB,GAAG,CAAC,oBAAoB,EAAE,EAAE,UAAU,EAAE,aAAa,EAAE,CAAC,CAAC;QACzD,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["import { ORIGIN_METAMASK } from '@metamask/controller-utils';\nimport type {\n BatchTransactionParams,\n NestedTransactionMetadata,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger.js';\nimport { MUSD_MONAD_FIAT_ASSET } from '../strategy/fiat/constants.js';\nimport type { TransactionPayControllerMessenger } from '../types.js';\nimport { findRecentChompVaultDeposit } from './chomp.js';\nimport { prefixError } from './error-prefix.js';\nimport { getNetworkClientId } from './provider.js';\nimport {\n collectTransactionIds,\n getTransaction,\n updateTransaction,\n waitForTransactionConfirmed,\n} from './transaction.js';\n\nconst log = createModuleLogger(projectLogger, 'ma-vault-deposit');\n\nexport const VAULT_ERROR_PREFIX = 'Vault: ';\n\n/**\n * Submits a Money Account mUSD vault deposit batch on Monad once the source\n * mUSD has settled in the Money Account (fiat on-ramp, Relay bridge, or any\n * other path). Re-encodes the original nested vault calldata with the\n * settled `sourceAmountRaw` via `getAmountData` and submits as a sponsored,\n * internal EIP-7702 batch. Callers decide whether to honour any vault\n * kill-switch by passing `vaultDisabled`.\n *\n * @param options - Submit options.\n * @param options.fromBlock - Block number to start searching for CHOMP deposits.\n * @param options.messenger - Controller messenger.\n * @param options.moneyAccountAddress - Money Account address sending the vault\n * deposit. Defaults to `transaction.txParams.from` (the deposit-flow sender);\n * withdraw flows pass it explicitly since their `from` is the funding EOA.\n * @param options.depositCalls - Pre-built vault-deposit batch for withdraw\n * flows, whose parent transaction carries no vault calls. When omitted the\n * batch is derived from the transaction's own nested calls re-encoded via\n * `getAmountData`.\n * @param options.sourceAmountRaw - Settled mUSD amount in raw units.\n * @param options.transaction - Original Money Account transaction meta.\n * @param options.vaultDisabled - When `true`, skip the vault batch and leave\n * the settled mUSD in the Money Account. Caller-evaluated kill-switch.\n * @returns Hash of the final submitted child transaction, if available.\n */\nexport async function submitMoneyAccountVaultDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress: moneyAccountAddressOverride,\n depositCalls,\n sourceAmountRaw,\n transaction,\n vaultDisabled,\n}: {\n fromBlock?: Hex;\n messenger: TransactionPayControllerMessenger;\n moneyAccountAddress?: Hex;\n depositCalls?: BatchTransactionParams[];\n sourceAmountRaw: string;\n transaction: TransactionMeta;\n vaultDisabled: boolean;\n}): Promise<{ transactionHash?: Hex }> {\n const transactionId = transaction.id;\n const moneyAccountAddress = (moneyAccountAddressOverride ??\n transaction.txParams.from) as Hex | undefined;\n\n if (!moneyAccountAddress) {\n throw new Error('Missing Money Account address');\n }\n\n if (vaultDisabled) {\n log('Skipping vault deposit because vaultDisabled is true', {\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n });\n\n return { transactionHash: '0x' };\n }\n\n const nestedTransactions = await resolveVaultDepositBatch({\n depositCalls,\n messenger,\n sourceAmountRaw,\n transaction,\n transactionId,\n });\n\n // CHOMP pre-check: skip addTransactionBatch entirely if CHOMP has already\n // auto-vaulted the funds during or before the checkout window.\n const preChompHash = await tryFindChompDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n });\n\n if (preChompHash) {\n return { transactionHash: preChompHash };\n }\n\n const networkClientId = getNetworkClientId(\n messenger,\n MUSD_MONAD_FIAT_ASSET.chainId,\n );\n const transactionIds: string[] = [];\n const { end } = collectTransactionIds(\n MUSD_MONAD_FIAT_ASSET.chainId,\n moneyAccountAddress,\n messenger,\n (id) => {\n transactionIds.push(id);\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Add required transaction ID from Money Account vault submission',\n },\n (tx) => {\n tx.requiredTransactionIds ??= [];\n tx.requiredTransactionIds.push(id);\n },\n );\n },\n );\n\n log('Submitting Money Account vault deposit', {\n moneyAccountAddress,\n nestedTransactionCount: nestedTransactions.length,\n networkClientId,\n sourceAmountRaw,\n transactionId,\n });\n\n try {\n await messenger.call('TransactionController:addTransactionBatch', {\n disableHook: true,\n disableSequential: true,\n disableUpgrade: true,\n from: moneyAccountAddress,\n isGasFeeSponsored: true,\n isInternal: true,\n networkClientId,\n origin: ORIGIN_METAMASK,\n requireApproval: false,\n skipInitialGasEstimate: true,\n transactions: nestedTransactions.map((nestedTransaction, index) => ({\n params: {\n data: nestedTransaction.data,\n to: nestedTransaction.to,\n value: nestedTransaction.value ?? '0x0',\n },\n type:\n index === 0\n ? (nestedTransaction.type ?? TransactionType.tokenMethodApprove)\n : TransactionType.contractInteraction,\n })),\n });\n } catch (error) {\n // CHOMP post-check: CHOMP may have won the race between pre-check and\n // submit. Return the CHOMP hash instead of surfacing a Vault-prefixed error.\n const postChompHash = await tryFindChompDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n });\n\n if (postChompHash) {\n return { transactionHash: postChompHash };\n }\n\n throw prefixError(error, VAULT_ERROR_PREFIX);\n } finally {\n end();\n }\n\n log('Submitted Money Account vault deposit', {\n moneyAccountAddress,\n nestedTransactionCount: nestedTransactions.length,\n networkClientId,\n sourceAmountRaw,\n transactionId,\n transactionIds,\n });\n\n if (!transactionIds.length) {\n throw new Error('No transactions submitted');\n }\n\n await Promise.all(\n transactionIds.map((id) => waitForTransactionConfirmed(id, messenger)),\n );\n\n const hash = getTransaction(transactionIds.slice(-1)[0], messenger)?.hash;\n\n if (!hash) {\n throw new Error('Missing transaction hash');\n }\n\n log('Confirmed Money Account vault deposit', {\n hash,\n moneyAccountAddress,\n nestedTransactionCount: nestedTransactions.length,\n networkClientId,\n sourceAmountRaw,\n transactionId,\n transactionIds,\n });\n\n return { transactionHash: hash as Hex };\n}\n\n/**\n * Resolves the vault-deposit batch (approve + teller deposit) to submit.\n *\n * Withdraw flows have no vault calls on their own nested transactions, so the\n * caller supplies a freshly built `depositCalls` batch. Deposit flows re-encode\n * their existing nested vault calldata with the settled amount via\n * `getAmountData` and also mutate the parent transaction so its stored calls\n * and `requiredAssets` reflect the settled amount.\n *\n * @param options - Resolution options.\n * @param options.depositCalls - Pre-built deposit batch for withdraw flows.\n * @param options.messenger - Controller messenger.\n * @param options.sourceAmountRaw - Settled mUSD amount in raw units.\n * @param options.transaction - Original Money Account transaction meta.\n * @param options.transactionId - ID of the original transaction.\n * @returns Nested transactions to submit as the vault deposit batch.\n */\nasync function resolveVaultDepositBatch({\n depositCalls,\n messenger,\n sourceAmountRaw,\n transaction,\n transactionId,\n}: {\n depositCalls?: BatchTransactionParams[];\n messenger: TransactionPayControllerMessenger;\n sourceAmountRaw: string;\n transaction: TransactionMeta;\n transactionId: string;\n}): Promise<NestedTransactionMetadata[]> {\n if (depositCalls?.length) {\n return depositCalls;\n }\n\n const updatedTransaction =\n getTransaction(transactionId, messenger) ?? transaction;\n const { updates } = await messenger.call(\n 'TransactionPayController:getAmountData',\n {\n amount: sourceAmountRaw,\n transaction: updatedTransaction,\n },\n );\n\n if (!updates.length) {\n throw new Error('No amount updates');\n }\n\n const nestedTransactions = updatedTransaction.nestedTransactions?.map(\n (nestedTransaction) => ({ ...nestedTransaction }),\n );\n\n if (!nestedTransactions?.length) {\n throw new Error('Missing nested transactions');\n }\n\n for (const { nestedTransactionIndex, data } of updates) {\n if (nestedTransactions[nestedTransactionIndex]) {\n nestedTransactions[nestedTransactionIndex].data = data;\n }\n }\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Money Account vault deposit: update vault amount',\n },\n (tx) => {\n for (const { nestedTransactionIndex, data } of updates) {\n if (tx.nestedTransactions?.[nestedTransactionIndex]) {\n tx.nestedTransactions[nestedTransactionIndex].data = data;\n }\n }\n\n if (tx.requiredAssets?.[0]) {\n tx.requiredAssets[0].amount = `0x${BigInt(sourceAmountRaw).toString(\n 16,\n )}`;\n }\n },\n );\n\n return nestedTransactions;\n}\n\nasync function tryFindChompDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n transactionId,\n}: {\n fromBlock: Hex | undefined;\n messenger: TransactionPayControllerMessenger;\n moneyAccountAddress: Hex;\n sourceAmountRaw: string;\n transactionId: string;\n}): Promise<Hex | undefined> {\n if (!fromBlock) {\n return undefined;\n }\n\n try {\n return await findRecentChompVaultDeposit({\n fromBlock,\n messenger,\n moneyAccountAddress,\n sourceAmountRaw,\n });\n } catch (chompError) {\n log('CHOMP check failed', { chompError, transactionId });\n return undefined;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"quotes.d.ts","sourceRoot":"","sources":["../../src/utils/quotes.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAIxE,OAAO,EAAmB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAE1E,OAAO,KAAK,EAGV,eAAe,EACf,iCAAiC,EAMjC,6BAA6B,EAC9B,MAAM,aAAa,CAAC;AAwBrB,MAAM,MAAM,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export async function updateQuotes(request) {
|
|
|
95
95
|
syncTransaction({
|
|
96
96
|
batchTransactions,
|
|
97
97
|
selectedFiatPayment: fiatPayment?.selectedPaymentMethodId,
|
|
98
|
+
hasQuotes: executableQuotes.length > 0,
|
|
98
99
|
isPostQuote,
|
|
99
100
|
messenger,
|
|
100
101
|
paymentToken,
|
|
@@ -132,6 +133,7 @@ export async function updateQuotes(request) {
|
|
|
132
133
|
*
|
|
133
134
|
* @param request - Request object.
|
|
134
135
|
* @param request.batchTransactions - Batch transactions to sync.
|
|
136
|
+
* @param request.hasQuotes - Whether MM Pay produced any quotes for this transaction.
|
|
135
137
|
* @param request.isPostQuote - Whether this is a post-quote flow.
|
|
136
138
|
* @param request.messenger - Messenger instance.
|
|
137
139
|
* @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).
|
|
@@ -140,7 +142,7 @@ export async function updateQuotes(request) {
|
|
|
140
142
|
* @param request.totals - Calculated totals.
|
|
141
143
|
* @param request.transactionId - ID of the transaction to sync.
|
|
142
144
|
*/
|
|
143
|
-
function syncTransaction({ batchTransactions, isPostQuote, messenger, paymentToken, selectedFiatPayment, strategy, totals, transactionId, }) {
|
|
145
|
+
function syncTransaction({ batchTransactions, hasQuotes, isPostQuote, messenger, paymentToken, selectedFiatPayment, strategy, totals, transactionId, }) {
|
|
144
146
|
if (!paymentToken && !selectedFiatPayment) {
|
|
145
147
|
return;
|
|
146
148
|
}
|
|
@@ -151,6 +153,20 @@ function syncTransaction({ batchTransactions, isPostQuote, messenger, paymentTok
|
|
|
151
153
|
}, (tx) => {
|
|
152
154
|
tx.batchTransactions = batchTransactions;
|
|
153
155
|
tx.batchTransactionsOptions = {};
|
|
156
|
+
// When MM Pay has produced quotes, it owns submission of this transaction
|
|
157
|
+
// via its strategy publish hook, so the parent must be marked externally
|
|
158
|
+
// signed to skip the local `KeyringController:signTransaction` call.
|
|
159
|
+
// When there are no quotes (e.g. user selected the target token as the
|
|
160
|
+
// payment token in a Predict flow), the transaction falls back to normal
|
|
161
|
+
// local signing, so the flag is cleared to allow that.
|
|
162
|
+
// If gas is sponsored, TC owns this field — it is set based on the
|
|
163
|
+
// Sentinel simulation result and must not be cleared here. Same-token
|
|
164
|
+
// flows (e.g. Monad mUSD withdrawal via a Money Account) produce no
|
|
165
|
+
// quotes but still need external sign because the account cannot sign
|
|
166
|
+
// locally.
|
|
167
|
+
if (!tx.isGasFeeSponsored) {
|
|
168
|
+
tx.isExternalSign = hasQuotes;
|
|
169
|
+
}
|
|
154
170
|
tx.metamaskPay = {
|
|
155
171
|
bridgeFeeFiat: totals.fees.provider.usd,
|
|
156
172
|
chainId: paymentToken?.chainId,
|
package/dist/utils/quotes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"quotes.js","sourceRoot":"","sources":["../../src/utils/quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAIrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAmB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAa7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EACL,yBAAyB,EACzB,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,wBAAwB,GAAG,EAAE,GAAG,IAAI,CAAC,CA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;oBACd,aAAa;iBACd,CAAC,CAAC;gBACH,OAAO;oBACL,iBAAiB,EAAE,EAAE;oBACrB,KAAK,EAAE,WAAW,CAAC,IAAI;oBACvB,MAAM,EAAE,WAAW,CAAC,MAAqC;iBAC1D,CAAC;YACJ,CAAC;YAED,GAAG,CAAC,8BAA8B,EAAE;gBAClC,KAAK,EAAE,WAAW;gBAClB,QAAQ,EAAE,IAAI;gBACd,aAAa;aACd,CAAC,CAAC;YACH,SAAS;QACX,CAAC;IACH,CAAC;IAED,GAAG,CAAC,qBAAqB,EAAE,EAAE,aAAa,EAAE,CAAC,CAAC;IAE9C,OAAO;QACL,iBAAiB,EAAE,EAAE;QACrB,KAAK;QACL,MAAM,EAAE,EAAE;KACX,CAAC;AACJ,CAAC","sourcesContent":["import { TransactionStatus } from '@metamask/transaction-controller';\nimport type { BatchTransaction } from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { PaymentOverride, TransactionPayStrategy } from '../constants.js';\nimport { projectLogger } from '../logger.js';\nimport type {\n QuoteRequest,\n QuoteErrorInfo,\n TransactionData,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPaySourceAmount,\n TransactionPayTotals,\n TransactionPaymentToken,\n UpdateTransactionDataCallback,\n} from '../types.js';\nimport { accountSupports7702 } from './7702.js';\nimport { buildNoOpQuote } from './no-op-quote.js';\nimport {\n checkStrategyQuoteSupport,\n checkStrategySupport,\n getStrategiesByName,\n getStrategyByName,\n} from './strategy.js';\nimport {\n computeTokenAmounts,\n getLiveTokenBalance,\n getTokenFiatRate,\n} from './token.js';\nimport { calculateTotals } from './totals.js';\nimport { getTransaction, updateTransaction } from './transaction.js';\nimport { isQuoteError } from './validation.js';\n\nconst DEFAULT_REFRESH_INTERVAL = 30 * 1000; // 30 Seconds\n\nconst log = createModuleLogger(projectLogger, 'quotes');\n\nconst inFlightQuoteRequests = new Map<string, AbortController>();\n\nexport type UpdateQuotesRequest = {\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[];\n messenger: TransactionPayControllerMessenger;\n transactionData: TransactionData | undefined;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n};\n\n/**\n * Update the quotes for a specific transaction.\n *\n * Calls for the same `transactionId` are serialised: a fresh call aborts any\n * previous in-flight call so a slower stale response cannot overwrite a newer\n * one in state.\n *\n * @param request - Request parameters.\n * @returns Boolean indicating if the quotes were updated. Returns `false` when\n * the call was aborted by a subsequent call for the same transaction.\n */\nexport async function updateQuotes(\n request: UpdateQuotesRequest,\n): Promise<boolean> {\n const {\n getStrategies,\n messenger,\n transactionData,\n transactionId,\n updateTransactionData,\n } = request;\n\n const transaction = getTransaction(transactionId, messenger);\n\n if (!transaction || !transactionData) {\n throw new Error('Transaction not found');\n }\n\n if (transaction?.status !== TransactionStatus.unapproved) {\n return false;\n }\n\n log('Updating quotes', { transactionId });\n\n const {\n accountOverride,\n atomic,\n fiatPayment,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n isQuoteRequired,\n paymentOverride,\n paymentToken: originalPaymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n } = transactionData;\n\n const from = accountOverride ?? (transaction.txParams.from as Hex);\n\n const controller = abortPreviousAndCreateController(transactionId);\n const { signal } = controller;\n\n updateTransactionData(transactionId, (data) => {\n data.isLoading = true;\n data.quoteError = undefined;\n });\n\n try {\n const paymentToken = await refreshPaymentTokenBalance({\n from,\n messenger,\n paymentToken: originalPaymentToken,\n signal,\n transactionId,\n updateTransactionData,\n });\n\n if (signal.aborted) {\n log('Quote request aborted before building requests', { transactionId });\n return false;\n }\n\n // Refreshing the balance above re-derives max source amounts, so read the\n // latest values instead of the snapshot taken before the refresh. Using\n // the snapshot quotes a max amount against a stale balance, which requests\n // a zero source amount when the token was selected before its balance\n // loaded.\n const latestSourceAmounts =\n getSourceAmounts(messenger, transactionId) ?? sourceAmounts;\n\n const requests = buildQuoteRequests({\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount: isMaxAmount ?? false,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts: latestSourceAmounts,\n tokens,\n transactionId,\n });\n\n const supports7702 = accountSupports7702(messenger, from);\n\n const { batchTransactions, error, quotes } = await getQuotes(\n transaction,\n from,\n requests,\n paymentToken,\n isQuoteRequired ?? false,\n supports7702,\n getStrategies,\n messenger,\n fiatPayment?.selectedPaymentMethodId,\n signal,\n );\n\n if (signal.aborted) {\n log('Quote request aborted before persisting results', { transactionId });\n return false;\n }\n\n // No-op quotes mark direct routes. They have no fees or amounts and the\n // transaction is signed and submitted locally, so totals and transaction\n // sync must treat them as \"no quotes\".\n const executableQuotes = quotes.filter(\n (quote) => quote.strategy !== TransactionPayStrategy.None,\n );\n\n const totals = calculateTotals({\n fiatPaymentAmount: fiatPayment?.amountFiat,\n messenger,\n quotes: executableQuotes,\n tokens,\n transaction,\n });\n\n log('Calculated totals', { transactionId, totals });\n\n syncTransaction({\n batchTransactions,\n selectedFiatPayment: fiatPayment?.selectedPaymentMethodId,\n isPostQuote,\n messenger,\n paymentToken,\n strategy: executableQuotes[0]?.strategy,\n totals,\n transactionId,\n });\n\n updateTransactionData(transactionId, (data) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n data.quotes = quotes as never;\n data.quoteError = error;\n data.quotesLastUpdated = Date.now();\n data.totals = totals;\n });\n } catch (error) {\n if (signal.aborted) {\n log('Quote request aborted', { transactionId, reason: signal.reason });\n return false;\n }\n throw error;\n } finally {\n if (!signal.aborted) {\n updateTransactionData(transactionId, (data) => {\n data.isLoading = false;\n });\n }\n clearControllerIfCurrent(transactionId, controller);\n }\n\n return true;\n}\n\n/**\n * Sync batch transactions to the transaction meta.\n *\n * @param request - Request object.\n * @param request.batchTransactions - Batch transactions to sync.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.messenger - Messenger instance.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.selectedFiatPayment - Selected fiat payment method ID.\n * @param request.strategy - Strategy of the executable quotes.\n * @param request.totals - Calculated totals.\n * @param request.transactionId - ID of the transaction to sync.\n */\nfunction syncTransaction({\n batchTransactions,\n isPostQuote,\n messenger,\n paymentToken,\n selectedFiatPayment,\n strategy,\n totals,\n transactionId,\n}: {\n batchTransactions: BatchTransaction[];\n selectedFiatPayment?: string;\n isPostQuote?: boolean;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n strategy?: TransactionPayStrategy;\n totals: TransactionPayTotals;\n transactionId: string;\n}): void {\n if (!paymentToken && !selectedFiatPayment) {\n return;\n }\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Update transaction pay data',\n },\n (tx: TransactionMeta) => {\n tx.batchTransactions = batchTransactions;\n tx.batchTransactionsOptions = {};\n\n tx.metamaskPay = {\n bridgeFeeFiat: totals.fees.provider.usd,\n chainId: paymentToken?.chainId,\n isPostQuote,\n networkFeeFiat: totals.fees.sourceNetwork.estimate.usd,\n strategy,\n targetFiat: totals.targetAmount.usd,\n tokenAddress: paymentToken?.address,\n totalFiat: totals.total.usd,\n };\n },\n );\n}\n\n/**\n * Refresh quotes for all transactions if expired.\n *\n * @param messenger - Messenger instance.\n * @param updateTransactionData - Callback to update transaction data.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n */\nexport async function refreshQuotes(\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n): Promise<void> {\n const state = messenger.call('TransactionPayController:getState');\n const transactionIds = Object.keys(state.transactionData);\n\n for (const transactionId of transactionIds) {\n const transactionData = state.transactionData[transactionId];\n const { isLoading, quotes, quotesLastUpdated } = transactionData;\n\n if (isLoading || !quotes?.length) {\n continue;\n }\n\n // No-op quotes mark direct routes and have nothing to refresh. They are\n // regenerated whenever the transaction data changes.\n if (\n quotes.every((quote) => quote.strategy === TransactionPayStrategy.None)\n ) {\n continue;\n }\n\n const strategyName = quotes[0].strategy;\n const strategy = getStrategyByName(strategyName);\n\n const refreshInterval =\n (await strategy.getRefreshInterval?.({\n chainId: quotes[0].request.sourceChainId,\n messenger,\n })) ?? DEFAULT_REFRESH_INTERVAL;\n\n const isExpired = Date.now() - (quotesLastUpdated ?? 0) > refreshInterval;\n\n if (!isExpired) {\n continue;\n }\n\n const isUpdated = await updateQuotes({\n getStrategies,\n messenger,\n transactionData,\n transactionId,\n updateTransactionData,\n });\n\n if (isUpdated) {\n log('Refreshed quotes', { transactionId, strategy: strategyName });\n }\n }\n}\n\nfunction abortPreviousAndCreateController(\n transactionId: string,\n): AbortController {\n const previous = inFlightQuoteRequests.get(transactionId);\n\n if (previous && !previous.signal.aborted) {\n log('Aborting previous quote request', { transactionId });\n previous.abort(new Error('Superseded by newer quote request'));\n }\n\n const controller = new AbortController();\n inFlightQuoteRequests.set(transactionId, controller);\n return controller;\n}\n\nfunction clearControllerIfCurrent(\n transactionId: string,\n controller: AbortController,\n): void {\n if (inFlightQuoteRequests.get(transactionId) === controller) {\n inFlightQuoteRequests.delete(transactionId);\n }\n}\n\n/**\n * Read the current source amounts for a transaction from controller state.\n *\n * @param messenger - Messenger instance.\n * @param transactionId - ID of the transaction.\n * @returns The source amounts, or `undefined` if the transaction has none.\n */\nfunction getSourceAmounts(\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n): TransactionPaySourceAmount[] | undefined {\n return messenger.call('TransactionPayController:getState').transactionData[\n transactionId\n ]?.sourceAmounts;\n}\n\n/**\n * Build quote requests required to retrieve quotes.\n *\n * @param request - Request parameters.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction.\n * @param request.tokens - Required tokens for the transaction.\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests.\n */\nfunction buildQuoteRequests({\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n transactionId,\n}: {\n atomic?: boolean;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n isPostQuote?: boolean;\n paymentOverride?: PaymentOverride;\n paymentToken: TransactionPaymentToken | undefined;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n tokens: TransactionPayRequiredToken[];\n transactionId: string;\n}): QuoteRequest[] {\n if (!paymentToken) {\n return [];\n }\n\n if (isPostQuote) {\n return buildPostQuoteRequests({\n atomic,\n destinationToken: paymentToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n });\n }\n\n // Standard flow: source = paymentToken, target = required tokens\n const requests = (sourceAmounts ?? []).map((sourceAmount) => {\n const token = tokens.find(\n (singleToken) => singleToken.address === sourceAmount.targetTokenAddress,\n ) as TransactionPayRequiredToken;\n\n return {\n atomic,\n from,\n isMaxAmount,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: paymentToken.balanceRaw,\n sourceChainId: paymentToken.chainId,\n sourceTokenAddress: paymentToken.address,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: token.allowUnderMinimum ? '0' : token.amountRaw,\n targetChainId: token.chainId,\n targetTokenAddress: token.address,\n };\n });\n\n if (!requests.length) {\n log('No quote requests', { transactionId });\n }\n\n return requests;\n}\n\n/**\n * Build quote requests for post-quote flows.\n * In this flow, the source is the transaction's required token,\n * and the target is the user's selected destination token (paymentToken).\n *\n * @param request - Request parameters.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.destinationToken - Destination token (paymentToken in post-quote mode).\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction (includes source token info).\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests for post-quote flow.\n */\nfunction buildPostQuoteRequests({\n atomic,\n destinationToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n}: {\n atomic?: boolean;\n destinationToken: TransactionPaymentToken;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n paymentOverride?: PaymentOverride;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n transactionId: string;\n}): QuoteRequest[] {\n // Find the source amount where targetTokenAddress matches the destination token\n const sourceAmount = sourceAmounts?.find(\n (amount) =>\n amount.targetTokenAddress.toLowerCase() ===\n destinationToken.address.toLowerCase(),\n );\n\n // Same-token-same-chain cases are already filtered in source-amounts.ts\n if (\n !sourceAmount?.sourceBalanceRaw ||\n !sourceAmount.sourceChainId ||\n !sourceAmount.sourceTokenAddress\n ) {\n log('No valid source amount found for post-quote request', {\n transactionId,\n });\n return [];\n }\n\n const request: QuoteRequest = {\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote: true,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: sourceAmount.sourceBalanceRaw,\n sourceChainId: sourceAmount.sourceChainId,\n sourceTokenAddress: sourceAmount.sourceTokenAddress,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: '0',\n targetChainId: destinationToken.chainId,\n targetTokenAddress: destinationToken.address,\n };\n\n log('Post-quote request built', { transactionId, request });\n\n // Currently only single token post-quote flows are supported.\n // Multiple token support would require multiple quotes for each required token.\n return [request];\n}\n\nasync function refreshPaymentTokenBalance({\n from,\n messenger,\n paymentToken,\n signal,\n transactionId,\n updateTransactionData,\n}: {\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n signal: AbortSignal;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n}): Promise<TransactionPaymentToken | undefined> {\n if (!paymentToken) {\n return undefined;\n }\n\n try {\n const fiatRates = getTokenFiatRate(\n messenger,\n paymentToken.address,\n paymentToken.chainId,\n );\n\n if (!fiatRates) {\n return paymentToken;\n }\n\n const liveBalance = await getLiveTokenBalance(\n messenger,\n from,\n paymentToken.chainId,\n paymentToken.address,\n );\n\n if (signal.aborted) {\n log('Payment token balance refresh aborted', { transactionId });\n return paymentToken;\n }\n\n const {\n raw: balanceRaw,\n human: balanceHuman,\n usd: balanceUsd,\n fiat: balanceFiat,\n } = computeTokenAmounts(liveBalance, paymentToken.decimals, fiatRates);\n\n const updatedToken = {\n ...paymentToken,\n balanceFiat,\n balanceHuman,\n balanceRaw,\n balanceUsd,\n };\n\n updateTransactionData(transactionId, (data) => {\n data.paymentToken = updatedToken;\n });\n\n log('Refreshed payment token balance', { transactionId, balanceRaw });\n\n return updatedToken;\n } catch (error) {\n log('Failed to refresh payment token balance', { transactionId, error });\n return paymentToken;\n }\n}\n\n/**\n * Retrieve quotes for a transaction.\n *\n * @param transaction - Transaction metadata.\n * @param from - Resolved wallet address (`accountOverride ?? txParams.from`).\n * @param requests - Quote requests.\n * @param paymentToken - Selected payment token, if any.\n * @param isQuoteRequired - Whether a quote is always required for the transaction.\n * @param isAccountEIP7702Compatible - Whether the account supports EIP-7702.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n * @param messenger - Controller messenger.\n * @param fiatPaymentMethod - Selected fiat payment method ID, if applicable.\n * @param signal - Signal that aborts when the quote request is superseded.\n * @returns An object containing batch transactions and quotes.\n */\nasync function getQuotes(\n transaction: TransactionMeta,\n from: Hex,\n requests: QuoteRequest[],\n paymentToken: TransactionPaymentToken | undefined,\n isQuoteRequired: boolean,\n isAccountEIP7702Compatible: boolean,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n messenger: TransactionPayControllerMessenger,\n fiatPaymentMethod?: string,\n signal?: AbortSignal,\n): Promise<{\n batchTransactions: BatchTransaction[];\n error?: QuoteErrorInfo;\n quotes: TransactionPayQuote<Json>[];\n}> {\n const { id: transactionId } = transaction;\n const strategies = getStrategiesByName(\n getStrategies(transaction),\n (strategyName) => {\n log('Skipping unknown strategy', {\n strategy: strategyName,\n transactionId,\n });\n },\n );\n\n if (!requests?.length && !fiatPaymentMethod) {\n // A selected payment token with no conversion requests means the route is\n // direct. Return an explicit no-op quote so clients and the publish hook\n // can distinguish \"no conversion needed\" from \"quote needed but missing\".\n // Not applicable when a quote is always required, as an empty requests\n // list then means the source amounts could not be calculated.\n const noOpQuote =\n paymentToken && !isQuoteRequired\n ? buildNoOpQuote(from, paymentToken)\n : undefined;\n\n if (noOpQuote) {\n log('Built no-op quote for direct route', { transactionId });\n }\n\n return {\n batchTransactions: [],\n quotes: noOpQuote ? [noOpQuote] : [],\n };\n }\n\n const request = {\n accountSupports7702: isAccountEIP7702Compatible,\n fiatPaymentMethod,\n from,\n messenger,\n requests,\n signal,\n transaction,\n };\n\n let error: QuoteErrorInfo | undefined;\n\n for (const { name, strategy } of strategies) {\n try {\n const support = await checkStrategySupport(strategy, request);\n\n if (!support) {\n log('Strategy does not support request', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n const quotes = (await strategy.getQuotes(\n request,\n )) as TransactionPayQuote<Json>[];\n\n if (!quotes.length) {\n log('Strategy returned no quotes', { strategy: name, transactionId });\n continue;\n }\n\n const isQuoteSupported = await checkStrategyQuoteSupport(strategy, {\n messenger,\n quotes,\n signal,\n transaction,\n });\n\n if (!isQuoteSupported) {\n log('Strategy does not support quotes', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n log('Updated', { transactionId, quotes });\n\n const batchTransactions = strategy.getBatchTransactions\n ? await strategy.getBatchTransactions({\n messenger,\n quotes,\n signal,\n })\n : [];\n\n log('Batch transactions', { transactionId, batchTransactions });\n\n return {\n batchTransactions,\n quotes,\n };\n } catch (caughtError) {\n if (signal?.aborted) {\n throw caughtError;\n }\n\n error ??= isQuoteError(caughtError)\n ? caughtError.info\n : { message: (caughtError as Error).message, reason: 'no-quotes' };\n\n if (\n isQuoteError(caughtError) &&\n caughtError.info.reason === 'insufficient-source-balance' &&\n caughtError.quotes?.length\n ) {\n log('Keeping quotes despite insufficient source balance', {\n strategy: name,\n transactionId,\n });\n return {\n batchTransactions: [],\n error: caughtError.info,\n quotes: caughtError.quotes as TransactionPayQuote<Json>[],\n };\n }\n\n log('Strategy failed, trying next', {\n error: caughtError,\n strategy: name,\n transactionId,\n });\n continue;\n }\n }\n\n log('No quotes available', { transactionId });\n\n return {\n batchTransactions: [],\n error,\n quotes: [],\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"quotes.js","sourceRoot":"","sources":["../../src/utils/quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAIrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAmB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM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,EAAE,EAAE;QACrB,KAAK;QACL,MAAM,EAAE,EAAE;KACX,CAAC;AACJ,CAAC","sourcesContent":["import { TransactionStatus } from '@metamask/transaction-controller';\nimport type { BatchTransaction } from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { PaymentOverride, TransactionPayStrategy } from '../constants.js';\nimport { projectLogger } from '../logger.js';\nimport type {\n QuoteRequest,\n QuoteErrorInfo,\n TransactionData,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPaySourceAmount,\n TransactionPayTotals,\n TransactionPaymentToken,\n UpdateTransactionDataCallback,\n} from '../types.js';\nimport { accountSupports7702 } from './7702.js';\nimport { buildNoOpQuote } from './no-op-quote.js';\nimport {\n checkStrategyQuoteSupport,\n checkStrategySupport,\n getStrategiesByName,\n getStrategyByName,\n} from './strategy.js';\nimport {\n computeTokenAmounts,\n getLiveTokenBalance,\n getTokenFiatRate,\n} from './token.js';\nimport { calculateTotals } from './totals.js';\nimport { getTransaction, updateTransaction } from './transaction.js';\nimport { isQuoteError } from './validation.js';\n\nconst DEFAULT_REFRESH_INTERVAL = 30 * 1000; // 30 Seconds\n\nconst log = createModuleLogger(projectLogger, 'quotes');\n\nconst inFlightQuoteRequests = new Map<string, AbortController>();\n\nexport type UpdateQuotesRequest = {\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[];\n messenger: TransactionPayControllerMessenger;\n transactionData: TransactionData | undefined;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n};\n\n/**\n * Update the quotes for a specific transaction.\n *\n * Calls for the same `transactionId` are serialised: a fresh call aborts any\n * previous in-flight call so a slower stale response cannot overwrite a newer\n * one in state.\n *\n * @param request - Request parameters.\n * @returns Boolean indicating if the quotes were updated. Returns `false` when\n * the call was aborted by a subsequent call for the same transaction.\n */\nexport async function updateQuotes(\n request: UpdateQuotesRequest,\n): Promise<boolean> {\n const {\n getStrategies,\n messenger,\n transactionData,\n transactionId,\n updateTransactionData,\n } = request;\n\n const transaction = getTransaction(transactionId, messenger);\n\n if (!transaction || !transactionData) {\n throw new Error('Transaction not found');\n }\n\n if (transaction?.status !== TransactionStatus.unapproved) {\n return false;\n }\n\n log('Updating quotes', { transactionId });\n\n const {\n accountOverride,\n atomic,\n fiatPayment,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n isQuoteRequired,\n paymentOverride,\n paymentToken: originalPaymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n } = transactionData;\n\n const from = accountOverride ?? (transaction.txParams.from as Hex);\n\n const controller = abortPreviousAndCreateController(transactionId);\n const { signal } = controller;\n\n updateTransactionData(transactionId, (data) => {\n data.isLoading = true;\n data.quoteError = undefined;\n });\n\n try {\n const paymentToken = await refreshPaymentTokenBalance({\n from,\n messenger,\n paymentToken: originalPaymentToken,\n signal,\n transactionId,\n updateTransactionData,\n });\n\n if (signal.aborted) {\n log('Quote request aborted before building requests', { transactionId });\n return false;\n }\n\n // Refreshing the balance above re-derives max source amounts, so read the\n // latest values instead of the snapshot taken before the refresh. Using\n // the snapshot quotes a max amount against a stale balance, which requests\n // a zero source amount when the token was selected before its balance\n // loaded.\n const latestSourceAmounts =\n getSourceAmounts(messenger, transactionId) ?? sourceAmounts;\n\n const requests = buildQuoteRequests({\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount: isMaxAmount ?? false,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts: latestSourceAmounts,\n tokens,\n transactionId,\n });\n\n const supports7702 = accountSupports7702(messenger, from);\n\n const { batchTransactions, error, quotes } = await getQuotes(\n transaction,\n from,\n requests,\n paymentToken,\n isQuoteRequired ?? false,\n supports7702,\n getStrategies,\n messenger,\n fiatPayment?.selectedPaymentMethodId,\n signal,\n );\n\n if (signal.aborted) {\n log('Quote request aborted before persisting results', { transactionId });\n return false;\n }\n\n // No-op quotes mark direct routes. They have no fees or amounts and the\n // transaction is signed and submitted locally, so totals and transaction\n // sync must treat them as \"no quotes\".\n const executableQuotes = quotes.filter(\n (quote) => quote.strategy !== TransactionPayStrategy.None,\n );\n\n const totals = calculateTotals({\n fiatPaymentAmount: fiatPayment?.amountFiat,\n messenger,\n quotes: executableQuotes,\n tokens,\n transaction,\n });\n\n log('Calculated totals', { transactionId, totals });\n\n syncTransaction({\n batchTransactions,\n selectedFiatPayment: fiatPayment?.selectedPaymentMethodId,\n hasQuotes: executableQuotes.length > 0,\n isPostQuote,\n messenger,\n paymentToken,\n strategy: executableQuotes[0]?.strategy,\n totals,\n transactionId,\n });\n\n updateTransactionData(transactionId, (data) => {\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion\n data.quotes = quotes as never;\n data.quoteError = error;\n data.quotesLastUpdated = Date.now();\n data.totals = totals;\n });\n } catch (error) {\n if (signal.aborted) {\n log('Quote request aborted', { transactionId, reason: signal.reason });\n return false;\n }\n throw error;\n } finally {\n if (!signal.aborted) {\n updateTransactionData(transactionId, (data) => {\n data.isLoading = false;\n });\n }\n clearControllerIfCurrent(transactionId, controller);\n }\n\n return true;\n}\n\n/**\n * Sync batch transactions to the transaction meta.\n *\n * @param request - Request object.\n * @param request.batchTransactions - Batch transactions to sync.\n * @param request.hasQuotes - Whether MM Pay produced any quotes for this transaction.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.messenger - Messenger instance.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.selectedFiatPayment - Selected fiat payment method ID.\n * @param request.strategy - Strategy of the executable quotes.\n * @param request.totals - Calculated totals.\n * @param request.transactionId - ID of the transaction to sync.\n */\nfunction syncTransaction({\n batchTransactions,\n hasQuotes,\n isPostQuote,\n messenger,\n paymentToken,\n selectedFiatPayment,\n strategy,\n totals,\n transactionId,\n}: {\n batchTransactions: BatchTransaction[];\n selectedFiatPayment?: string;\n hasQuotes: boolean;\n isPostQuote?: boolean;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n strategy?: TransactionPayStrategy;\n totals: TransactionPayTotals;\n transactionId: string;\n}): void {\n if (!paymentToken && !selectedFiatPayment) {\n return;\n }\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Update transaction pay data',\n },\n (tx: TransactionMeta) => {\n tx.batchTransactions = batchTransactions;\n tx.batchTransactionsOptions = {};\n\n // When MM Pay has produced quotes, it owns submission of this transaction\n // via its strategy publish hook, so the parent must be marked externally\n // signed to skip the local `KeyringController:signTransaction` call.\n // When there are no quotes (e.g. user selected the target token as the\n // payment token in a Predict flow), the transaction falls back to normal\n // local signing, so the flag is cleared to allow that.\n // If gas is sponsored, TC owns this field — it is set based on the\n // Sentinel simulation result and must not be cleared here. Same-token\n // flows (e.g. Monad mUSD withdrawal via a Money Account) produce no\n // quotes but still need external sign because the account cannot sign\n // locally.\n if (!tx.isGasFeeSponsored) {\n tx.isExternalSign = hasQuotes;\n }\n\n tx.metamaskPay = {\n bridgeFeeFiat: totals.fees.provider.usd,\n chainId: paymentToken?.chainId,\n isPostQuote,\n networkFeeFiat: totals.fees.sourceNetwork.estimate.usd,\n strategy,\n targetFiat: totals.targetAmount.usd,\n tokenAddress: paymentToken?.address,\n totalFiat: totals.total.usd,\n };\n },\n );\n}\n\n/**\n * Refresh quotes for all transactions if expired.\n *\n * @param messenger - Messenger instance.\n * @param updateTransactionData - Callback to update transaction data.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n */\nexport async function refreshQuotes(\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n): Promise<void> {\n const state = messenger.call('TransactionPayController:getState');\n const transactionIds = Object.keys(state.transactionData);\n\n for (const transactionId of transactionIds) {\n const transactionData = state.transactionData[transactionId];\n const { isLoading, quotes, quotesLastUpdated } = transactionData;\n\n if (isLoading || !quotes?.length) {\n continue;\n }\n\n // No-op quotes mark direct routes and have nothing to refresh. They are\n // regenerated whenever the transaction data changes.\n if (\n quotes.every((quote) => quote.strategy === TransactionPayStrategy.None)\n ) {\n continue;\n }\n\n const strategyName = quotes[0].strategy;\n const strategy = getStrategyByName(strategyName);\n\n const refreshInterval =\n (await strategy.getRefreshInterval?.({\n chainId: quotes[0].request.sourceChainId,\n messenger,\n })) ?? DEFAULT_REFRESH_INTERVAL;\n\n const isExpired = Date.now() - (quotesLastUpdated ?? 0) > refreshInterval;\n\n if (!isExpired) {\n continue;\n }\n\n const isUpdated = await updateQuotes({\n getStrategies,\n messenger,\n transactionData,\n transactionId,\n updateTransactionData,\n });\n\n if (isUpdated) {\n log('Refreshed quotes', { transactionId, strategy: strategyName });\n }\n }\n}\n\nfunction abortPreviousAndCreateController(\n transactionId: string,\n): AbortController {\n const previous = inFlightQuoteRequests.get(transactionId);\n\n if (previous && !previous.signal.aborted) {\n log('Aborting previous quote request', { transactionId });\n previous.abort(new Error('Superseded by newer quote request'));\n }\n\n const controller = new AbortController();\n inFlightQuoteRequests.set(transactionId, controller);\n return controller;\n}\n\nfunction clearControllerIfCurrent(\n transactionId: string,\n controller: AbortController,\n): void {\n if (inFlightQuoteRequests.get(transactionId) === controller) {\n inFlightQuoteRequests.delete(transactionId);\n }\n}\n\n/**\n * Read the current source amounts for a transaction from controller state.\n *\n * @param messenger - Messenger instance.\n * @param transactionId - ID of the transaction.\n * @returns The source amounts, or `undefined` if the transaction has none.\n */\nfunction getSourceAmounts(\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n): TransactionPaySourceAmount[] | undefined {\n return messenger.call('TransactionPayController:getState').transactionData[\n transactionId\n ]?.sourceAmounts;\n}\n\n/**\n * Build quote requests required to retrieve quotes.\n *\n * @param request - Request parameters.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.isPostQuote - Whether this is a post-quote flow.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.paymentToken - Payment token (source for standard flows, destination for post-quote).\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction.\n * @param request.tokens - Required tokens for the transaction.\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests.\n */\nfunction buildQuoteRequests({\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote,\n paymentOverride,\n paymentToken,\n refundTo,\n sourceAmounts,\n tokens,\n transactionId,\n}: {\n atomic?: boolean;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n isPostQuote?: boolean;\n paymentOverride?: PaymentOverride;\n paymentToken: TransactionPaymentToken | undefined;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n tokens: TransactionPayRequiredToken[];\n transactionId: string;\n}): QuoteRequest[] {\n if (!paymentToken) {\n return [];\n }\n\n if (isPostQuote) {\n return buildPostQuoteRequests({\n atomic,\n destinationToken: paymentToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n });\n }\n\n // Standard flow: source = paymentToken, target = required tokens\n const requests = (sourceAmounts ?? []).map((sourceAmount) => {\n const token = tokens.find(\n (singleToken) => singleToken.address === sourceAmount.targetTokenAddress,\n ) as TransactionPayRequiredToken;\n\n return {\n atomic,\n from,\n isMaxAmount,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: paymentToken.balanceRaw,\n sourceChainId: paymentToken.chainId,\n sourceTokenAddress: paymentToken.address,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: token.allowUnderMinimum ? '0' : token.amountRaw,\n targetChainId: token.chainId,\n targetTokenAddress: token.address,\n };\n });\n\n if (!requests.length) {\n log('No quote requests', { transactionId });\n }\n\n return requests;\n}\n\n/**\n * Build quote requests for post-quote flows.\n * In this flow, the source is the transaction's required token,\n * and the target is the user's selected destination token (paymentToken).\n *\n * @param request - Request parameters.\n * @param request.atomic - Whether the target transaction is executed atomically with the Relay quote.\n * @param request.destinationToken - Destination token (paymentToken in post-quote mode).\n * @param request.from - Address from which the transaction is sent.\n * @param request.isHyperliquidSource - Whether the source of funds is HyperLiquid.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.isPolymarketDepositWallet - Whether the source of funds is a Polymarket deposit wallet.\n * @param request.paymentOverride - Optional payment override type for the transaction.\n * @param request.refundTo - Optional address to receive refunds if the Relay transaction fails.\n * @param request.sourceAmounts - Source amounts for the transaction (includes source token info).\n * @param request.transactionId - ID of the transaction.\n * @returns Array of quote requests for post-quote flow.\n */\nfunction buildPostQuoteRequests({\n atomic,\n destinationToken,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n paymentOverride,\n refundTo,\n sourceAmounts,\n transactionId,\n}: {\n atomic?: boolean;\n destinationToken: TransactionPaymentToken;\n from: Hex;\n isHyperliquidSource?: boolean;\n isMaxAmount: boolean;\n isPolymarketDepositWallet?: boolean;\n paymentOverride?: PaymentOverride;\n refundTo?: Hex;\n sourceAmounts: TransactionPaySourceAmount[] | undefined;\n transactionId: string;\n}): QuoteRequest[] {\n // Find the source amount where targetTokenAddress matches the destination token\n const sourceAmount = sourceAmounts?.find(\n (amount) =>\n amount.targetTokenAddress.toLowerCase() ===\n destinationToken.address.toLowerCase(),\n );\n\n // Same-token-same-chain cases are already filtered in source-amounts.ts\n if (\n !sourceAmount?.sourceBalanceRaw ||\n !sourceAmount.sourceChainId ||\n !sourceAmount.sourceTokenAddress\n ) {\n log('No valid source amount found for post-quote request', {\n transactionId,\n });\n return [];\n }\n\n const request: QuoteRequest = {\n atomic,\n from,\n isHyperliquidSource,\n isMaxAmount,\n isPolymarketDepositWallet,\n isPostQuote: true,\n paymentOverride,\n refundTo,\n sourceBalanceRaw: sourceAmount.sourceBalanceRaw,\n sourceChainId: sourceAmount.sourceChainId,\n sourceTokenAddress: sourceAmount.sourceTokenAddress,\n sourceTokenAmount: sourceAmount.sourceAmountRaw,\n targetAmountMinimum: '0',\n targetChainId: destinationToken.chainId,\n targetTokenAddress: destinationToken.address,\n };\n\n log('Post-quote request built', { transactionId, request });\n\n // Currently only single token post-quote flows are supported.\n // Multiple token support would require multiple quotes for each required token.\n return [request];\n}\n\nasync function refreshPaymentTokenBalance({\n from,\n messenger,\n paymentToken,\n signal,\n transactionId,\n updateTransactionData,\n}: {\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n paymentToken: TransactionPaymentToken | undefined;\n signal: AbortSignal;\n transactionId: string;\n updateTransactionData: UpdateTransactionDataCallback;\n}): Promise<TransactionPaymentToken | undefined> {\n if (!paymentToken) {\n return undefined;\n }\n\n try {\n const fiatRates = getTokenFiatRate(\n messenger,\n paymentToken.address,\n paymentToken.chainId,\n );\n\n if (!fiatRates) {\n return paymentToken;\n }\n\n const liveBalance = await getLiveTokenBalance(\n messenger,\n from,\n paymentToken.chainId,\n paymentToken.address,\n );\n\n if (signal.aborted) {\n log('Payment token balance refresh aborted', { transactionId });\n return paymentToken;\n }\n\n const {\n raw: balanceRaw,\n human: balanceHuman,\n usd: balanceUsd,\n fiat: balanceFiat,\n } = computeTokenAmounts(liveBalance, paymentToken.decimals, fiatRates);\n\n const updatedToken = {\n ...paymentToken,\n balanceFiat,\n balanceHuman,\n balanceRaw,\n balanceUsd,\n };\n\n updateTransactionData(transactionId, (data) => {\n data.paymentToken = updatedToken;\n });\n\n log('Refreshed payment token balance', { transactionId, balanceRaw });\n\n return updatedToken;\n } catch (error) {\n log('Failed to refresh payment token balance', { transactionId, error });\n return paymentToken;\n }\n}\n\n/**\n * Retrieve quotes for a transaction.\n *\n * @param transaction - Transaction metadata.\n * @param from - Resolved wallet address (`accountOverride ?? txParams.from`).\n * @param requests - Quote requests.\n * @param paymentToken - Selected payment token, if any.\n * @param isQuoteRequired - Whether a quote is always required for the transaction.\n * @param isAccountEIP7702Compatible - Whether the account supports EIP-7702.\n * @param getStrategies - Callback to get ordered strategy names for a transaction.\n * @param messenger - Controller messenger.\n * @param fiatPaymentMethod - Selected fiat payment method ID, if applicable.\n * @param signal - Signal that aborts when the quote request is superseded.\n * @returns An object containing batch transactions and quotes.\n */\nasync function getQuotes(\n transaction: TransactionMeta,\n from: Hex,\n requests: QuoteRequest[],\n paymentToken: TransactionPaymentToken | undefined,\n isQuoteRequired: boolean,\n isAccountEIP7702Compatible: boolean,\n getStrategies: (transaction: TransactionMeta) => TransactionPayStrategy[],\n messenger: TransactionPayControllerMessenger,\n fiatPaymentMethod?: string,\n signal?: AbortSignal,\n): Promise<{\n batchTransactions: BatchTransaction[];\n error?: QuoteErrorInfo;\n quotes: TransactionPayQuote<Json>[];\n}> {\n const { id: transactionId } = transaction;\n const strategies = getStrategiesByName(\n getStrategies(transaction),\n (strategyName) => {\n log('Skipping unknown strategy', {\n strategy: strategyName,\n transactionId,\n });\n },\n );\n\n if (!requests?.length && !fiatPaymentMethod) {\n // A selected payment token with no conversion requests means the route is\n // direct. Return an explicit no-op quote so clients and the publish hook\n // can distinguish \"no conversion needed\" from \"quote needed but missing\".\n // Not applicable when a quote is always required, as an empty requests\n // list then means the source amounts could not be calculated.\n const noOpQuote =\n paymentToken && !isQuoteRequired\n ? buildNoOpQuote(from, paymentToken)\n : undefined;\n\n if (noOpQuote) {\n log('Built no-op quote for direct route', { transactionId });\n }\n\n return {\n batchTransactions: [],\n quotes: noOpQuote ? [noOpQuote] : [],\n };\n }\n\n const request = {\n accountSupports7702: isAccountEIP7702Compatible,\n fiatPaymentMethod,\n from,\n messenger,\n requests,\n signal,\n transaction,\n };\n\n let error: QuoteErrorInfo | undefined;\n\n for (const { name, strategy } of strategies) {\n try {\n const support = await checkStrategySupport(strategy, request);\n\n if (!support) {\n log('Strategy does not support request', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n const quotes = (await strategy.getQuotes(\n request,\n )) as TransactionPayQuote<Json>[];\n\n if (!quotes.length) {\n log('Strategy returned no quotes', { strategy: name, transactionId });\n continue;\n }\n\n const isQuoteSupported = await checkStrategyQuoteSupport(strategy, {\n messenger,\n quotes,\n signal,\n transaction,\n });\n\n if (!isQuoteSupported) {\n log('Strategy does not support quotes', {\n strategy: name,\n transactionId,\n });\n continue;\n }\n\n log('Updated', { transactionId, quotes });\n\n const batchTransactions = strategy.getBatchTransactions\n ? await strategy.getBatchTransactions({\n messenger,\n quotes,\n signal,\n })\n : [];\n\n log('Batch transactions', { transactionId, batchTransactions });\n\n return {\n batchTransactions,\n quotes,\n };\n } catch (caughtError) {\n if (signal?.aborted) {\n throw caughtError;\n }\n\n error ??= isQuoteError(caughtError)\n ? caughtError.info\n : { message: (caughtError as Error).message, reason: 'no-quotes' };\n\n if (\n isQuoteError(caughtError) &&\n caughtError.info.reason === 'insufficient-source-balance' &&\n caughtError.quotes?.length\n ) {\n log('Keeping quotes despite insufficient source balance', {\n strategy: name,\n transactionId,\n });\n return {\n batchTransactions: [],\n error: caughtError.info,\n quotes: caughtError.quotes as TransactionPayQuote<Json>[],\n };\n }\n\n log('Strategy failed, trying next', {\n error: caughtError,\n strategy: name,\n transactionId,\n });\n continue;\n }\n }\n\n log('No quotes available', { transactionId });\n\n return {\n batchTransactions: [],\n error,\n quotes: [],\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/transaction-pay-controller",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "30.0.0-preview-bba5d41",
|
|
4
4
|
"description": "Manages alternate payment strategies to provide required funds for transactions in MetaMask",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|