@metamask-previews/transaction-pay-controller 22.1.0-preview-5e603a6c0 → 22.1.0-preview-2fdaa18

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 CHANGED
@@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
11
11
 
12
12
  - Resolve fiat asset per transaction type from `confirmations_pay_fiat` remote feature flag, falling back to hardcoded map then ETH on mainnet ([#8631](https://github.com/MetaMask/core/pull/8631))
13
13
 
14
+ ### Fixed
15
+
16
+ - Fix fiat strategy submit flow to extract provider code from ramps quote instead of parsing order ID, store `caipAssetId` in fiat payment state, and use target amount for totals when fiat strategy is active ([#8726](https://github.com/MetaMask/core/pull/8726))
17
+
14
18
  ## [22.1.0]
15
19
 
16
20
  ### Fixed
@@ -215,12 +215,11 @@ _TransactionPayController_getDelegationTransaction = new WeakMap(), _Transaction
215
215
  const transaction = (0, transaction_1.getTransaction)(transactionId, this.messenger);
216
216
  const fiatAsset = (0, utils_1.deriveFiatAssetForFiatPayment)(transaction, this.messenger);
217
217
  if (fiatAsset) {
218
- try {
219
- this.messenger.call('RampsController:setSelectedToken', (0, token_1.buildCaipAssetType)(fiatAsset.chainId, fiatAsset.address));
220
- }
221
- catch {
222
- // Intentionally no-op — tokens may not be loaded in RampsController yet.
223
- }
218
+ __classPrivateFieldGet(this, _TransactionPayController_instances, "m", _TransactionPayController_updateTransactionData).call(this, transactionId, (data) => {
219
+ if (data.fiatPayment) {
220
+ data.fiatPayment.caipAssetId = (0, token_1.buildCaipAssetType)(fiatAsset.chainId, fiatAsset.address);
221
+ }
222
+ });
224
223
  }
225
224
  }
226
225
  if (shouldUpdateQuotes) {
@@ -1 +1 @@
1
- {"version":3,"file":"TransactionPayController.cjs","sourceRoot":"","sources":["../src/TransactionPayController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,+DAA2D;AAG3D,mCAA8B;AAE9B,2EAAk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AAM,kBAAkB,GACtB,uBAAA,IAAI,+CAAe,EAAE,KAArB,IAAI,EAAkB,WAAW,CAAC;QAClC,CAAC,uBAAA,IAAI,6CAAa,CAAC,CAAC,CAAC,CAAC,uBAAA,IAAI,6CAAa,MAAjB,IAAI,EAAc,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAE9D,MAAM,eAAe,GAAG,kBAAkB,CAAC,MAAM,CAC/C,CAAC,QAAQ,EAAsC,EAAE,CAC/C,IAAA,oCAAwB,EAAC,QAAQ,CAAC,CACrC,CAAC;IAEF,IAAI,eAAe,CAAC,MAAM,EAAE,CAAC;QAC3B,OAAO,eAAe,CAAC;IACzB,CAAC;IAED,MAAM,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IACnE,MAAM,YAAY,GAAG,eAAe,EAAE,YAAY,CAAC;IAEnD,OAAO,IAAA,gCAAgB,EACrB,IAAI,CAAC,SAAS,EACd,YAAY,EAAE,OAAO,EACrB,YAAY,EAAE,OAAO,EACrB,WAAW,CAAC,IAAI,EAChB,eAAe,EAAE,WAAW,EAAE,uBAAuB,CACtD,CAAC;AACJ,CAAC","sourcesContent":["import type { StateMetadata } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Draft } from 'immer';\nimport { noop } from 'lodash';\n\nimport { updateFiatPayment } from './actions/update-fiat-payment';\nimport { updatePaymentToken } from './actions/update-payment-token';\nimport {\n CONTROLLER_NAME,\n isTransactionPayStrategy,\n TransactionPayStrategy,\n} from './constants';\nimport { QuoteRefresher } from './helpers/QuoteRefresher';\nimport { deriveFiatAssetForFiatPayment } from './strategy/fiat/utils';\nimport type {\n GetDelegationTransactionCallback,\n TransactionConfigCallback,\n TransactionData,\n TransactionPayControllerMessenger,\n TransactionPayControllerOptions,\n TransactionPayControllerState,\n UpdateFiatPaymentRequest,\n UpdatePaymentTokenRequest,\n} from './types';\nimport { getStrategyOrder } from './utils/feature-flags';\nimport { updateQuotes } from './utils/quotes';\nimport { updateSourceAmounts } from './utils/source-amounts';\nimport { buildCaipAssetType } from './utils/token';\nimport {\n getTransaction,\n subscribeAssetChanges,\n subscribeTransactionChanges,\n} from './utils/transaction';\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getDelegationTransaction',\n 'getStrategy',\n 'setTransactionConfig',\n 'updateFiatPayment',\n 'updatePaymentToken',\n] as const;\n\nconst stateMetadata: StateMetadata<TransactionPayControllerState> = {\n transactionData: {\n includeInDebugSnapshot: false,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n};\n\nconst getDefaultState = (): TransactionPayControllerState => ({\n transactionData: {},\n});\n\nexport class TransactionPayController extends BaseController<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState,\n TransactionPayControllerMessenger\n> {\n readonly #getDelegationTransaction: GetDelegationTransactionCallback;\n\n readonly #getStrategy?: (\n transaction: TransactionMeta,\n ) => TransactionPayStrategy;\n\n readonly #getStrategies?: (\n transaction: TransactionMeta,\n ) => TransactionPayStrategy[];\n\n constructor({\n getDelegationTransaction,\n getStrategy,\n getStrategies,\n messenger,\n state,\n }: TransactionPayControllerOptions) {\n super({\n name: CONTROLLER_NAME,\n metadata: stateMetadata,\n messenger,\n state: { ...getDefaultState(), ...state },\n });\n\n this.#getDelegationTransaction = getDelegationTransaction;\n this.#getStrategy = getStrategy;\n this.#getStrategies = getStrategies;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n subscribeTransactionChanges(\n messenger,\n this.#updateTransactionData.bind(this),\n this.#removeTransactionData.bind(this),\n );\n\n subscribeAssetChanges(\n messenger,\n () => this.state,\n this.#updateTransactionData.bind(this),\n );\n\n // eslint-disable-next-line no-new\n new QuoteRefresher({\n getStrategies: this.#getStrategiesWithFallback.bind(this),\n messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Sets the transaction configuration.\n *\n * The callback receives the current configuration properties and can mutate\n * them in place. Updated values are written back to the transaction data.\n *\n * @param transactionId - The ID of the transaction to configure.\n * @param callback - A callback that receives a mutable {@link TransactionConfig} object.\n */\n setTransactionConfig(\n transactionId: string,\n callback: TransactionConfigCallback,\n ): void {\n this.#updateTransactionData(transactionId, (transactionData) => {\n const config = {\n isMaxAmount: transactionData.isMaxAmount,\n isPostQuote: transactionData.isPostQuote,\n isHyperliquidSource: transactionData.isHyperliquidSource,\n refundTo: transactionData.refundTo,\n accountOverride: transactionData.accountOverride,\n };\n\n const previousAccountOverride = config.accountOverride;\n\n callback(config);\n\n transactionData.accountOverride = config.accountOverride;\n transactionData.isMaxAmount = config.isMaxAmount;\n transactionData.isPostQuote = config.isPostQuote;\n transactionData.isHyperliquidSource = config.isHyperliquidSource;\n transactionData.refundTo = config.refundTo;\n\n if (config.accountOverride !== previousAccountOverride) {\n transactionData.paymentToken = undefined;\n }\n });\n }\n\n /**\n * Updates the payment token for a transaction.\n *\n * Resolves token metadata and balances, then stores the new payment token\n * in the transaction data. This triggers recalculation of source amounts\n * and quote retrieval.\n *\n * @param request - The payment token update request containing the\n * transaction ID, token address, and chain ID.\n */\n updatePaymentToken(request: UpdatePaymentTokenRequest): void {\n updatePaymentToken(request, {\n messenger: this.messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Updates the fiat payment state for a transaction.\n *\n * The request callback receives the current fiat payment state and can\n * mutate it to update properties such as the selected payment method or\n * fiat amount.\n *\n * @param request - The fiat payment update request containing the\n * transaction ID and a callback to mutate fiat payment state.\n */\n updateFiatPayment(request: UpdateFiatPaymentRequest): void {\n updateFiatPayment(request, {\n messenger: this.messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Gets the delegation transaction for a given transaction.\n *\n * Converts the provided transaction into a redeem delegation by delegating\n * to the configured callback. Returns the delegation transaction data\n * including the encoded call data, target address, value, and an optional\n * authorization list.\n *\n * @param args - The arguments forwarded to the {@link GetDelegationTransactionCallback},\n * containing the transaction metadata.\n * @returns A promise resolving to the delegation transaction data.\n */\n getDelegationTransaction(\n ...args: Parameters<GetDelegationTransactionCallback>\n ): ReturnType<GetDelegationTransactionCallback> {\n return this.#getDelegationTransaction(...args);\n }\n\n /**\n * Gets the preferred strategy for a transaction.\n *\n * Returns the first strategy from the ordered list of strategies applicable\n * to the given transaction. Falls back to the default strategy order derived\n * from feature flags when no custom strategy callback is configured.\n *\n * @param transaction - The transaction metadata to determine the strategy for.\n * @returns The preferred {@link TransactionPayStrategy} for the transaction.\n */\n getStrategy(transaction: TransactionMeta): TransactionPayStrategy {\n return this.#getStrategiesWithFallback(transaction)[0];\n }\n\n #removeTransactionData(transactionId: string): void {\n this.update((state) => {\n delete state.transactionData[transactionId];\n });\n }\n\n #updateTransactionData(\n transactionId: string,\n fn: (transactionData: Draft<TransactionData>) => void,\n ): void {\n let shouldUpdateQuotes = false;\n let shouldUpdateFiatToken = false;\n\n this.update((state) => {\n const { transactionData } = state;\n let current = transactionData[transactionId];\n const originalPaymentToken = current?.paymentToken;\n const originalTokens = current?.tokens;\n const originalIsMaxAmount = current?.isMaxAmount;\n const originalIsPostQuote = current?.isPostQuote;\n const originalAccountOverride = current?.accountOverride;\n const originalFiatPaymentAmount = current?.fiatPayment?.amountFiat;\n const originalFiatPaymentMethodId =\n current?.fiatPayment?.selectedPaymentMethodId;\n\n if (!current) {\n transactionData[transactionId] = {\n fiatPayment: {},\n isLoading: false,\n tokens: [],\n };\n\n current = transactionData[transactionId];\n }\n\n fn(current);\n\n const isPaymentTokenUpdated =\n current.paymentToken?.address?.toLowerCase() !==\n originalPaymentToken?.address?.toLowerCase() ||\n current.paymentToken?.chainId !== originalPaymentToken?.chainId;\n\n const isTokensUpdated = current.tokens !== originalTokens;\n const isIsMaxUpdated = current.isMaxAmount !== originalIsMaxAmount;\n const isPostQuoteUpdated = current.isPostQuote !== originalIsPostQuote;\n const isAccountOverrideUpdated =\n current.accountOverride !== originalAccountOverride;\n const isFiatAmountUpdated =\n current.fiatPayment?.amountFiat !== originalFiatPaymentAmount;\n const isFiatPaymentMethodUpdated =\n current.fiatPayment?.selectedPaymentMethodId !==\n originalFiatPaymentMethodId;\n\n if (\n isPaymentTokenUpdated ||\n isIsMaxUpdated ||\n isTokensUpdated ||\n isPostQuoteUpdated ||\n isAccountOverrideUpdated\n ) {\n updateSourceAmounts(transactionId, current as never, this.messenger);\n\n shouldUpdateQuotes = true;\n }\n\n if (isFiatAmountUpdated || isFiatPaymentMethodUpdated) {\n shouldUpdateQuotes = true;\n }\n\n if (isFiatPaymentMethodUpdated) {\n shouldUpdateFiatToken = true;\n }\n });\n\n if (shouldUpdateFiatToken) {\n const transaction = getTransaction(\n transactionId,\n this.messenger,\n ) as TransactionMeta;\n const fiatAsset = deriveFiatAssetForFiatPayment(\n transaction,\n this.messenger,\n );\n if (fiatAsset) {\n try {\n this.messenger.call(\n 'RampsController:setSelectedToken',\n buildCaipAssetType(fiatAsset.chainId, fiatAsset.address),\n );\n } catch {\n // Intentionally no-op — tokens may not be loaded in RampsController yet.\n }\n }\n }\n\n if (shouldUpdateQuotes) {\n updateQuotes({\n getStrategies: this.#getStrategiesWithFallback.bind(this),\n messenger: this.messenger,\n transactionData: this.state.transactionData[transactionId],\n transactionId,\n updateTransactionData: this.#updateTransactionData.bind(this),\n }).catch(noop);\n }\n }\n\n #getStrategiesWithFallback(\n transaction: TransactionMeta,\n ): TransactionPayStrategy[] {\n const strategyCandidates: unknown[] =\n this.#getStrategies?.(transaction) ??\n (this.#getStrategy ? [this.#getStrategy(transaction)] : []);\n\n const validStrategies = strategyCandidates.filter(\n (strategy): strategy is TransactionPayStrategy =>\n isTransactionPayStrategy(strategy),\n );\n\n if (validStrategies.length) {\n return validStrategies;\n }\n\n const transactionData = this.state.transactionData[transaction.id];\n const paymentToken = transactionData?.paymentToken;\n\n return getStrategyOrder(\n this.messenger,\n paymentToken?.chainId,\n paymentToken?.address,\n transaction.type,\n transactionData?.fiatPayment?.selectedPaymentMethodId,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"TransactionPayController.cjs","sourceRoot":"","sources":["../src/TransactionPayController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,+DAA2D;AAG3D,mCAA8B;AAE9B,2EAAkE;AAClE,6EAAoE;AACpE,+CAIqB;AACrB,iEAA0D;AAC1D,qDAAsE;AAWtE,6DAAyD;AACzD,+CAA8C;AAC9C,+DAA6D;AAC7D,6CAAmD;AACnD,yDAI6B;AAE7B,MAAM,yBAAyB,GAAG;IAChC,0BAA0B;IAC1B,aAAa;IACb,sBAAsB;IACtB,mBAAmB;IACnB,oBAAoB;CACZ,CAAC;AAEX,MAAM,aAAa,GAAiD;IAClE,eAAe,EAAE;QACf,sBAAsB,EAAE,KAAK;QAC7B,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEF,MAAM,eAAe,GAAG,GAAkC,EAAE,CAAC,CAAC;IAC5D,eAAe,EAAE,EAAE;CACpB,CAAC,CAAC;AAEH,MAAa,wBAAyB,SAAQ,gCAI7C;IAWC,YAAY,EACV,wBAAwB,EACxB,WAAW,EACX,aAAa,EACb,SAAS,EACT,KAAK,GAC2B;QAChC,KAAK,CAAC;YACJ,IAAI,EAAE,2BAAe;YACrB,QAAQ,EAAE,aAAa;YACvB,SAAS;YACT,KAAK,EAAE,EAAE,GAAG,eAAe,EAAE,EAAE,GAAG,KAAK,EAAE;SAC1C,CAAC,CAAC;;QAtBI,qEAA4D;QAE5D,wDAEmB;QAEnB,0DAEqB;QAgB5B,uBAAA,IAAI,sDAA6B,wBAAwB,MAAA,CAAC;QAC1D,uBAAA,IAAI,yCAAgB,WAAW,MAAA,CAAC;QAChC,uBAAA,IAAI,2CAAkB,aAAa,MAAA,CAAC;QAEpC,IAAI,CAAC,SAAS,CAAC,4BAA4B,CACz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I,CAAC;YACzD,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,eAAe,EAAE,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,aAAa,CAAC;YAC1D,aAAa;YACb,qBAAqB,EAAE,uBAAA,IAAI,4FAAuB,CAAC,IAAI,CAAC,IAAI,CAAC;SAC9D,CAAC,CAAC,KAAK,CAAC,aAAI,CAAC,CAAC;IACjB,CAAC;AACH,CAAC,qHAGC,WAA4B;IAE5B,MAAM,kBAAkB,GACtB,uBAAA,IAAI,+CAAe,EAAE,KAArB,IAAI,EAAkB,WAAW,CAAC;QAClC,CAAC,uBAAA,IAAI,6CAAa,CAAC,CAAC,CAAC,CAAC,uBAAA,IAAI,6CAAa,MAAjB,IAAI,EAAc,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAE9D,MAAM,eAAe,GAAG,kBAAkB,CAAC,MAAM,CAC/C,CAAC,QAAQ,EAAsC,EAAE,CAC/C,IAAA,oCAAwB,EAAC,QAAQ,CAAC,CACrC,CAAC;IAEF,IAAI,eAAe,CAAC,MAAM,EAAE,CAAC;QAC3B,OAAO,eAAe,CAAC;IACzB,CAAC;IAED,MAAM,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IACnE,MAAM,YAAY,GAAG,eAAe,EAAE,YAAY,CAAC;IAEnD,OAAO,IAAA,gCAAgB,EACrB,IAAI,CAAC,SAAS,EACd,YAAY,EAAE,OAAO,EACrB,YAAY,EAAE,OAAO,EACrB,WAAW,CAAC,IAAI,EAChB,eAAe,EAAE,WAAW,EAAE,uBAAuB,CACtD,CAAC;AACJ,CAAC","sourcesContent":["import type { StateMetadata } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Draft } from 'immer';\nimport { noop } from 'lodash';\n\nimport { updateFiatPayment } from './actions/update-fiat-payment';\nimport { updatePaymentToken } from './actions/update-payment-token';\nimport {\n CONTROLLER_NAME,\n isTransactionPayStrategy,\n TransactionPayStrategy,\n} from './constants';\nimport { QuoteRefresher } from './helpers/QuoteRefresher';\nimport { deriveFiatAssetForFiatPayment } from './strategy/fiat/utils';\nimport type {\n GetDelegationTransactionCallback,\n TransactionConfigCallback,\n TransactionData,\n TransactionPayControllerMessenger,\n TransactionPayControllerOptions,\n TransactionPayControllerState,\n UpdateFiatPaymentRequest,\n UpdatePaymentTokenRequest,\n} from './types';\nimport { getStrategyOrder } from './utils/feature-flags';\nimport { updateQuotes } from './utils/quotes';\nimport { updateSourceAmounts } from './utils/source-amounts';\nimport { buildCaipAssetType } from './utils/token';\nimport {\n getTransaction,\n subscribeAssetChanges,\n subscribeTransactionChanges,\n} from './utils/transaction';\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getDelegationTransaction',\n 'getStrategy',\n 'setTransactionConfig',\n 'updateFiatPayment',\n 'updatePaymentToken',\n] as const;\n\nconst stateMetadata: StateMetadata<TransactionPayControllerState> = {\n transactionData: {\n includeInDebugSnapshot: false,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n};\n\nconst getDefaultState = (): TransactionPayControllerState => ({\n transactionData: {},\n});\n\nexport class TransactionPayController extends BaseController<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState,\n TransactionPayControllerMessenger\n> {\n readonly #getDelegationTransaction: GetDelegationTransactionCallback;\n\n readonly #getStrategy?: (\n transaction: TransactionMeta,\n ) => TransactionPayStrategy;\n\n readonly #getStrategies?: (\n transaction: TransactionMeta,\n ) => TransactionPayStrategy[];\n\n constructor({\n getDelegationTransaction,\n getStrategy,\n getStrategies,\n messenger,\n state,\n }: TransactionPayControllerOptions) {\n super({\n name: CONTROLLER_NAME,\n metadata: stateMetadata,\n messenger,\n state: { ...getDefaultState(), ...state },\n });\n\n this.#getDelegationTransaction = getDelegationTransaction;\n this.#getStrategy = getStrategy;\n this.#getStrategies = getStrategies;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n subscribeTransactionChanges(\n messenger,\n this.#updateTransactionData.bind(this),\n this.#removeTransactionData.bind(this),\n );\n\n subscribeAssetChanges(\n messenger,\n () => this.state,\n this.#updateTransactionData.bind(this),\n );\n\n // eslint-disable-next-line no-new\n new QuoteRefresher({\n getStrategies: this.#getStrategiesWithFallback.bind(this),\n messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Sets the transaction configuration.\n *\n * The callback receives the current configuration properties and can mutate\n * them in place. Updated values are written back to the transaction data.\n *\n * @param transactionId - The ID of the transaction to configure.\n * @param callback - A callback that receives a mutable {@link TransactionConfig} object.\n */\n setTransactionConfig(\n transactionId: string,\n callback: TransactionConfigCallback,\n ): void {\n this.#updateTransactionData(transactionId, (transactionData) => {\n const config = {\n isMaxAmount: transactionData.isMaxAmount,\n isPostQuote: transactionData.isPostQuote,\n isHyperliquidSource: transactionData.isHyperliquidSource,\n refundTo: transactionData.refundTo,\n accountOverride: transactionData.accountOverride,\n };\n\n const previousAccountOverride = config.accountOverride;\n\n callback(config);\n\n transactionData.accountOverride = config.accountOverride;\n transactionData.isMaxAmount = config.isMaxAmount;\n transactionData.isPostQuote = config.isPostQuote;\n transactionData.isHyperliquidSource = config.isHyperliquidSource;\n transactionData.refundTo = config.refundTo;\n\n if (config.accountOverride !== previousAccountOverride) {\n transactionData.paymentToken = undefined;\n }\n });\n }\n\n /**\n * Updates the payment token for a transaction.\n *\n * Resolves token metadata and balances, then stores the new payment token\n * in the transaction data. This triggers recalculation of source amounts\n * and quote retrieval.\n *\n * @param request - The payment token update request containing the\n * transaction ID, token address, and chain ID.\n */\n updatePaymentToken(request: UpdatePaymentTokenRequest): void {\n updatePaymentToken(request, {\n messenger: this.messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Updates the fiat payment state for a transaction.\n *\n * The request callback receives the current fiat payment state and can\n * mutate it to update properties such as the selected payment method or\n * fiat amount.\n *\n * @param request - The fiat payment update request containing the\n * transaction ID and a callback to mutate fiat payment state.\n */\n updateFiatPayment(request: UpdateFiatPaymentRequest): void {\n updateFiatPayment(request, {\n messenger: this.messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Gets the delegation transaction for a given transaction.\n *\n * Converts the provided transaction into a redeem delegation by delegating\n * to the configured callback. Returns the delegation transaction data\n * including the encoded call data, target address, value, and an optional\n * authorization list.\n *\n * @param args - The arguments forwarded to the {@link GetDelegationTransactionCallback},\n * containing the transaction metadata.\n * @returns A promise resolving to the delegation transaction data.\n */\n getDelegationTransaction(\n ...args: Parameters<GetDelegationTransactionCallback>\n ): ReturnType<GetDelegationTransactionCallback> {\n return this.#getDelegationTransaction(...args);\n }\n\n /**\n * Gets the preferred strategy for a transaction.\n *\n * Returns the first strategy from the ordered list of strategies applicable\n * to the given transaction. Falls back to the default strategy order derived\n * from feature flags when no custom strategy callback is configured.\n *\n * @param transaction - The transaction metadata to determine the strategy for.\n * @returns The preferred {@link TransactionPayStrategy} for the transaction.\n */\n getStrategy(transaction: TransactionMeta): TransactionPayStrategy {\n return this.#getStrategiesWithFallback(transaction)[0];\n }\n\n #removeTransactionData(transactionId: string): void {\n this.update((state) => {\n delete state.transactionData[transactionId];\n });\n }\n\n #updateTransactionData(\n transactionId: string,\n fn: (transactionData: Draft<TransactionData>) => void,\n ): void {\n let shouldUpdateQuotes = false;\n let shouldUpdateFiatToken = false;\n\n this.update((state) => {\n const { transactionData } = state;\n let current = transactionData[transactionId];\n const originalPaymentToken = current?.paymentToken;\n const originalTokens = current?.tokens;\n const originalIsMaxAmount = current?.isMaxAmount;\n const originalIsPostQuote = current?.isPostQuote;\n const originalAccountOverride = current?.accountOverride;\n const originalFiatPaymentAmount = current?.fiatPayment?.amountFiat;\n const originalFiatPaymentMethodId =\n current?.fiatPayment?.selectedPaymentMethodId;\n\n if (!current) {\n transactionData[transactionId] = {\n fiatPayment: {},\n isLoading: false,\n tokens: [],\n };\n\n current = transactionData[transactionId];\n }\n\n fn(current);\n\n const isPaymentTokenUpdated =\n current.paymentToken?.address?.toLowerCase() !==\n originalPaymentToken?.address?.toLowerCase() ||\n current.paymentToken?.chainId !== originalPaymentToken?.chainId;\n\n const isTokensUpdated = current.tokens !== originalTokens;\n const isIsMaxUpdated = current.isMaxAmount !== originalIsMaxAmount;\n const isPostQuoteUpdated = current.isPostQuote !== originalIsPostQuote;\n const isAccountOverrideUpdated =\n current.accountOverride !== originalAccountOverride;\n const isFiatAmountUpdated =\n current.fiatPayment?.amountFiat !== originalFiatPaymentAmount;\n const isFiatPaymentMethodUpdated =\n current.fiatPayment?.selectedPaymentMethodId !==\n originalFiatPaymentMethodId;\n\n if (\n isPaymentTokenUpdated ||\n isIsMaxUpdated ||\n isTokensUpdated ||\n isPostQuoteUpdated ||\n isAccountOverrideUpdated\n ) {\n updateSourceAmounts(transactionId, current as never, this.messenger);\n\n shouldUpdateQuotes = true;\n }\n\n if (isFiatAmountUpdated || isFiatPaymentMethodUpdated) {\n shouldUpdateQuotes = true;\n }\n\n if (isFiatPaymentMethodUpdated) {\n shouldUpdateFiatToken = true;\n }\n });\n\n if (shouldUpdateFiatToken) {\n const transaction = getTransaction(\n transactionId,\n this.messenger,\n ) as TransactionMeta;\n const fiatAsset = deriveFiatAssetForFiatPayment(\n transaction,\n this.messenger,\n );\n if (fiatAsset) {\n this.#updateTransactionData(transactionId, (data) => {\n if (data.fiatPayment) {\n data.fiatPayment.caipAssetId = buildCaipAssetType(\n fiatAsset.chainId,\n fiatAsset.address,\n );\n }\n });\n }\n }\n\n if (shouldUpdateQuotes) {\n updateQuotes({\n getStrategies: this.#getStrategiesWithFallback.bind(this),\n messenger: this.messenger,\n transactionData: this.state.transactionData[transactionId],\n transactionId,\n updateTransactionData: this.#updateTransactionData.bind(this),\n }).catch(noop);\n }\n }\n\n #getStrategiesWithFallback(\n transaction: TransactionMeta,\n ): TransactionPayStrategy[] {\n const strategyCandidates: unknown[] =\n this.#getStrategies?.(transaction) ??\n (this.#getStrategy ? [this.#getStrategy(transaction)] : []);\n\n const validStrategies = strategyCandidates.filter(\n (strategy): strategy is TransactionPayStrategy =>\n isTransactionPayStrategy(strategy),\n );\n\n if (validStrategies.length) {\n return validStrategies;\n }\n\n const transactionData = this.state.transactionData[transaction.id];\n const paymentToken = transactionData?.paymentToken;\n\n return getStrategyOrder(\n this.messenger,\n paymentToken?.chainId,\n paymentToken?.address,\n transaction.type,\n transactionData?.fiatPayment?.selectedPaymentMethodId,\n );\n }\n}\n"]}
@@ -212,12 +212,11 @@ _TransactionPayController_getDelegationTransaction = new WeakMap(), _Transaction
212
212
  const transaction = getTransaction(transactionId, this.messenger);
213
213
  const fiatAsset = deriveFiatAssetForFiatPayment(transaction, this.messenger);
214
214
  if (fiatAsset) {
215
- try {
216
- this.messenger.call('RampsController:setSelectedToken', buildCaipAssetType(fiatAsset.chainId, fiatAsset.address));
217
- }
218
- catch {
219
- // Intentionally no-op — tokens may not be loaded in RampsController yet.
220
- }
215
+ __classPrivateFieldGet(this, _TransactionPayController_instances, "m", _TransactionPayController_updateTransactionData).call(this, transactionId, (data) => {
216
+ if (data.fiatPayment) {
217
+ data.fiatPayment.caipAssetId = buildCaipAssetType(fiatAsset.chainId, fiatAsset.address);
218
+ }
219
+ });
221
220
  }
222
221
  }
223
222
  if (shouldUpdateQuotes) {
@@ -1 +1 @@
1
- {"version":3,"file":"TransactionPayController.mjs","sourceRoot":"","sources":["../src/TransactionPayController.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,cAAc,EAAE,kCAAkC;;;AAK3D,OAAO,EAAE,iBAAiB,EAAE,0CAAsC;AAClE,OAAO,EAAE,kBAAkB,EAAE,2CAAuC;AACpE,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,sBAAsB,EACvB,wBAAoB;AACrB,OAAO,EAAE,cAAc,EAAE,qCAAiC;AAC1D,OAAO,EAAE,6BAA6B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CAAC;AACH,CAAC,qHAGC,WAA4B;IAE5B,MAAM,kBAAkB,GACtB,uBAAA,IAAI,+CAAe,EAAE,KAArB,IAAI,EAAkB,WAAW,CAAC;QAClC,CAAC,uBAAA,IAAI,6CAAa,CAAC,CAAC,CAAC,CAAC,uBAAA,IAAI,6CAAa,MAAjB,IAAI,EAAc,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAE9D,MAAM,eAAe,GAAG,kBAAkB,CAAC,MAAM,CAC/C,CAAC,QAAQ,EAAsC,EAAE,CAC/C,wBAAwB,CAAC,QAAQ,CAAC,CACrC,CAAC;IAEF,IAAI,eAAe,CAAC,MAAM,EAAE,CAAC;QAC3B,OAAO,eAAe,CAAC;IACzB,CAAC;IAED,MAAM,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IACnE,MAAM,YAAY,GAAG,eAAe,EAAE,YAAY,CAAC;IAEnD,OAAO,gBAAgB,CACrB,IAAI,CAAC,SAAS,EACd,YAAY,EAAE,OAAO,EACrB,YAAY,EAAE,OAAO,EACrB,WAAW,CAAC,IAAI,EAChB,eAAe,EAAE,WAAW,EAAE,uBAAuB,CACtD,CAAC;AACJ,CAAC","sourcesContent":["import type { StateMetadata } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Draft } from 'immer';\nimport { noop } from 'lodash';\n\nimport { updateFiatPayment } from './actions/update-fiat-payment';\nimport { updatePaymentToken } from './actions/update-payment-token';\nimport {\n CONTROLLER_NAME,\n isTransactionPayStrategy,\n TransactionPayStrategy,\n} from './constants';\nimport { QuoteRefresher } from './helpers/QuoteRefresher';\nimport { deriveFiatAssetForFiatPayment } from './strategy/fiat/utils';\nimport type {\n GetDelegationTransactionCallback,\n TransactionConfigCallback,\n TransactionData,\n TransactionPayControllerMessenger,\n TransactionPayControllerOptions,\n TransactionPayControllerState,\n UpdateFiatPaymentRequest,\n UpdatePaymentTokenRequest,\n} from './types';\nimport { getStrategyOrder } from './utils/feature-flags';\nimport { updateQuotes } from './utils/quotes';\nimport { updateSourceAmounts } from './utils/source-amounts';\nimport { buildCaipAssetType } from './utils/token';\nimport {\n getTransaction,\n subscribeAssetChanges,\n subscribeTransactionChanges,\n} from './utils/transaction';\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getDelegationTransaction',\n 'getStrategy',\n 'setTransactionConfig',\n 'updateFiatPayment',\n 'updatePaymentToken',\n] as const;\n\nconst stateMetadata: StateMetadata<TransactionPayControllerState> = {\n transactionData: {\n includeInDebugSnapshot: false,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n};\n\nconst getDefaultState = (): TransactionPayControllerState => ({\n transactionData: {},\n});\n\nexport class TransactionPayController extends BaseController<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState,\n TransactionPayControllerMessenger\n> {\n readonly #getDelegationTransaction: GetDelegationTransactionCallback;\n\n readonly #getStrategy?: (\n transaction: TransactionMeta,\n ) => TransactionPayStrategy;\n\n readonly #getStrategies?: (\n transaction: TransactionMeta,\n ) => TransactionPayStrategy[];\n\n constructor({\n getDelegationTransaction,\n getStrategy,\n getStrategies,\n messenger,\n state,\n }: TransactionPayControllerOptions) {\n super({\n name: CONTROLLER_NAME,\n metadata: stateMetadata,\n messenger,\n state: { ...getDefaultState(), ...state },\n });\n\n this.#getDelegationTransaction = getDelegationTransaction;\n this.#getStrategy = getStrategy;\n this.#getStrategies = getStrategies;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n subscribeTransactionChanges(\n messenger,\n this.#updateTransactionData.bind(this),\n this.#removeTransactionData.bind(this),\n );\n\n subscribeAssetChanges(\n messenger,\n () => this.state,\n this.#updateTransactionData.bind(this),\n );\n\n // eslint-disable-next-line no-new\n new QuoteRefresher({\n getStrategies: this.#getStrategiesWithFallback.bind(this),\n messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Sets the transaction configuration.\n *\n * The callback receives the current configuration properties and can mutate\n * them in place. Updated values are written back to the transaction data.\n *\n * @param transactionId - The ID of the transaction to configure.\n * @param callback - A callback that receives a mutable {@link TransactionConfig} object.\n */\n setTransactionConfig(\n transactionId: string,\n callback: TransactionConfigCallback,\n ): void {\n this.#updateTransactionData(transactionId, (transactionData) => {\n const config = {\n isMaxAmount: transactionData.isMaxAmount,\n isPostQuote: transactionData.isPostQuote,\n isHyperliquidSource: transactionData.isHyperliquidSource,\n refundTo: transactionData.refundTo,\n accountOverride: transactionData.accountOverride,\n };\n\n const previousAccountOverride = config.accountOverride;\n\n callback(config);\n\n transactionData.accountOverride = config.accountOverride;\n transactionData.isMaxAmount = config.isMaxAmount;\n transactionData.isPostQuote = config.isPostQuote;\n transactionData.isHyperliquidSource = config.isHyperliquidSource;\n transactionData.refundTo = config.refundTo;\n\n if (config.accountOverride !== previousAccountOverride) {\n transactionData.paymentToken = undefined;\n }\n });\n }\n\n /**\n * Updates the payment token for a transaction.\n *\n * Resolves token metadata and balances, then stores the new payment token\n * in the transaction data. This triggers recalculation of source amounts\n * and quote retrieval.\n *\n * @param request - The payment token update request containing the\n * transaction ID, token address, and chain ID.\n */\n updatePaymentToken(request: UpdatePaymentTokenRequest): void {\n updatePaymentToken(request, {\n messenger: this.messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Updates the fiat payment state for a transaction.\n *\n * The request callback receives the current fiat payment state and can\n * mutate it to update properties such as the selected payment method or\n * fiat amount.\n *\n * @param request - The fiat payment update request containing the\n * transaction ID and a callback to mutate fiat payment state.\n */\n updateFiatPayment(request: UpdateFiatPaymentRequest): void {\n updateFiatPayment(request, {\n messenger: this.messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Gets the delegation transaction for a given transaction.\n *\n * Converts the provided transaction into a redeem delegation by delegating\n * to the configured callback. Returns the delegation transaction data\n * including the encoded call data, target address, value, and an optional\n * authorization list.\n *\n * @param args - The arguments forwarded to the {@link GetDelegationTransactionCallback},\n * containing the transaction metadata.\n * @returns A promise resolving to the delegation transaction data.\n */\n getDelegationTransaction(\n ...args: Parameters<GetDelegationTransactionCallback>\n ): ReturnType<GetDelegationTransactionCallback> {\n return this.#getDelegationTransaction(...args);\n }\n\n /**\n * Gets the preferred strategy for a transaction.\n *\n * Returns the first strategy from the ordered list of strategies applicable\n * to the given transaction. Falls back to the default strategy order derived\n * from feature flags when no custom strategy callback is configured.\n *\n * @param transaction - The transaction metadata to determine the strategy for.\n * @returns The preferred {@link TransactionPayStrategy} for the transaction.\n */\n getStrategy(transaction: TransactionMeta): TransactionPayStrategy {\n return this.#getStrategiesWithFallback(transaction)[0];\n }\n\n #removeTransactionData(transactionId: string): void {\n this.update((state) => {\n delete state.transactionData[transactionId];\n });\n }\n\n #updateTransactionData(\n transactionId: string,\n fn: (transactionData: Draft<TransactionData>) => void,\n ): void {\n let shouldUpdateQuotes = false;\n let shouldUpdateFiatToken = false;\n\n this.update((state) => {\n const { transactionData } = state;\n let current = transactionData[transactionId];\n const originalPaymentToken = current?.paymentToken;\n const originalTokens = current?.tokens;\n const originalIsMaxAmount = current?.isMaxAmount;\n const originalIsPostQuote = current?.isPostQuote;\n const originalAccountOverride = current?.accountOverride;\n const originalFiatPaymentAmount = current?.fiatPayment?.amountFiat;\n const originalFiatPaymentMethodId =\n current?.fiatPayment?.selectedPaymentMethodId;\n\n if (!current) {\n transactionData[transactionId] = {\n fiatPayment: {},\n isLoading: false,\n tokens: [],\n };\n\n current = transactionData[transactionId];\n }\n\n fn(current);\n\n const isPaymentTokenUpdated =\n current.paymentToken?.address?.toLowerCase() !==\n originalPaymentToken?.address?.toLowerCase() ||\n current.paymentToken?.chainId !== originalPaymentToken?.chainId;\n\n const isTokensUpdated = current.tokens !== originalTokens;\n const isIsMaxUpdated = current.isMaxAmount !== originalIsMaxAmount;\n const isPostQuoteUpdated = current.isPostQuote !== originalIsPostQuote;\n const isAccountOverrideUpdated =\n current.accountOverride !== originalAccountOverride;\n const isFiatAmountUpdated =\n current.fiatPayment?.amountFiat !== originalFiatPaymentAmount;\n const isFiatPaymentMethodUpdated =\n current.fiatPayment?.selectedPaymentMethodId !==\n originalFiatPaymentMethodId;\n\n if (\n isPaymentTokenUpdated ||\n isIsMaxUpdated ||\n isTokensUpdated ||\n isPostQuoteUpdated ||\n isAccountOverrideUpdated\n ) {\n updateSourceAmounts(transactionId, current as never, this.messenger);\n\n shouldUpdateQuotes = true;\n }\n\n if (isFiatAmountUpdated || isFiatPaymentMethodUpdated) {\n shouldUpdateQuotes = true;\n }\n\n if (isFiatPaymentMethodUpdated) {\n shouldUpdateFiatToken = true;\n }\n });\n\n if (shouldUpdateFiatToken) {\n const transaction = getTransaction(\n transactionId,\n this.messenger,\n ) as TransactionMeta;\n const fiatAsset = deriveFiatAssetForFiatPayment(\n transaction,\n this.messenger,\n );\n if (fiatAsset) {\n try {\n this.messenger.call(\n 'RampsController:setSelectedToken',\n buildCaipAssetType(fiatAsset.chainId, fiatAsset.address),\n );\n } catch {\n // Intentionally no-op — tokens may not be loaded in RampsController yet.\n }\n }\n }\n\n if (shouldUpdateQuotes) {\n updateQuotes({\n getStrategies: this.#getStrategiesWithFallback.bind(this),\n messenger: this.messenger,\n transactionData: this.state.transactionData[transactionId],\n transactionId,\n updateTransactionData: this.#updateTransactionData.bind(this),\n }).catch(noop);\n }\n }\n\n #getStrategiesWithFallback(\n transaction: TransactionMeta,\n ): TransactionPayStrategy[] {\n const strategyCandidates: unknown[] =\n this.#getStrategies?.(transaction) ??\n (this.#getStrategy ? [this.#getStrategy(transaction)] : []);\n\n const validStrategies = strategyCandidates.filter(\n (strategy): strategy is TransactionPayStrategy =>\n isTransactionPayStrategy(strategy),\n );\n\n if (validStrategies.length) {\n return validStrategies;\n }\n\n const transactionData = this.state.transactionData[transaction.id];\n const paymentToken = transactionData?.paymentToken;\n\n return getStrategyOrder(\n this.messenger,\n paymentToken?.chainId,\n paymentToken?.address,\n transaction.type,\n transactionData?.fiatPayment?.selectedPaymentMethodId,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"TransactionPayController.mjs","sourceRoot":"","sources":["../src/TransactionPayController.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,cAAc,EAAE,kCAAkC;;;AAK3D,OAAO,EAAE,iBAAiB,EAAE,0CAAsC;AAClE,OAAO,EAAE,kBAAkB,EAAE,2CAAuC;AACpE,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,sBAAsB,EACvB,wBAAoB;AACrB,OAAO,EAAE,cAAc,EAAE,qCAAiC;AAC1D,OAAO,EAAE,6BAA6B,EAAE,kCAA8B;AAWtE,OAAO,EAAE,gBAAgB,EAAE,kCAA8B;AACzD,OAAO,EAAE,YAAY,EAAE,2BAAuB;AAC9C,OAAO,EAAE,mBAAmB,EAAE,mCAA+B;AAC7D,OAAO,EAAE,kBAAkB,EAAE,0BAAsB;AACnD,OAAO,EACL,cAAc,EACd,qBAAqB,EACrB,2BAA2B,EAC5B,gCAA4B;AAE7B,MAAM,yBAAyB,GAAG;IAChC,0BAA0B;IAC1B,aAAa;IACb,sBAAsB;IACtB,mBAAmB;IACnB,oBAAoB;CACZ,CAAC;AAEX,MAAM,aAAa,GAAiD;IAClE,eAAe,EAAE;QACf,sBAAsB,EAAE,KAAK;QAC7B,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,KAAK;QACd,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEF,MAAM,eAAe,GAAG,GAAkC,EAAE,CAAC,CAAC;IAC5D,eAAe,EAAE,EAAE;CACpB,CAAC,CAAC;AAEH,MAAM,OAAO,wBAAyB,SAAQ,cAI7C;IAWC,YAAY,EACV,wBAAwB,EACxB,WAAW,EACX,aAAa,EACb,SAAS,EACT,KAAK,GAC2B;QAChC,KAAK,CAAC;YACJ,IAAI,EAAE,eAAe;YACrB,QA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,WAAW,CAAC,IAAI,EAChB,eAAe,EAAE,WAAW,EAAE,uBAAuB,CACtD,CAAC;AACJ,CAAC","sourcesContent":["import type { StateMetadata } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Draft } from 'immer';\nimport { noop } from 'lodash';\n\nimport { updateFiatPayment } from './actions/update-fiat-payment';\nimport { updatePaymentToken } from './actions/update-payment-token';\nimport {\n CONTROLLER_NAME,\n isTransactionPayStrategy,\n TransactionPayStrategy,\n} from './constants';\nimport { QuoteRefresher } from './helpers/QuoteRefresher';\nimport { deriveFiatAssetForFiatPayment } from './strategy/fiat/utils';\nimport type {\n GetDelegationTransactionCallback,\n TransactionConfigCallback,\n TransactionData,\n TransactionPayControllerMessenger,\n TransactionPayControllerOptions,\n TransactionPayControllerState,\n UpdateFiatPaymentRequest,\n UpdatePaymentTokenRequest,\n} from './types';\nimport { getStrategyOrder } from './utils/feature-flags';\nimport { updateQuotes } from './utils/quotes';\nimport { updateSourceAmounts } from './utils/source-amounts';\nimport { buildCaipAssetType } from './utils/token';\nimport {\n getTransaction,\n subscribeAssetChanges,\n subscribeTransactionChanges,\n} from './utils/transaction';\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getDelegationTransaction',\n 'getStrategy',\n 'setTransactionConfig',\n 'updateFiatPayment',\n 'updatePaymentToken',\n] as const;\n\nconst stateMetadata: StateMetadata<TransactionPayControllerState> = {\n transactionData: {\n includeInDebugSnapshot: false,\n includeInStateLogs: true,\n persist: false,\n usedInUi: true,\n },\n};\n\nconst getDefaultState = (): TransactionPayControllerState => ({\n transactionData: {},\n});\n\nexport class TransactionPayController extends BaseController<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState,\n TransactionPayControllerMessenger\n> {\n readonly #getDelegationTransaction: GetDelegationTransactionCallback;\n\n readonly #getStrategy?: (\n transaction: TransactionMeta,\n ) => TransactionPayStrategy;\n\n readonly #getStrategies?: (\n transaction: TransactionMeta,\n ) => TransactionPayStrategy[];\n\n constructor({\n getDelegationTransaction,\n getStrategy,\n getStrategies,\n messenger,\n state,\n }: TransactionPayControllerOptions) {\n super({\n name: CONTROLLER_NAME,\n metadata: stateMetadata,\n messenger,\n state: { ...getDefaultState(), ...state },\n });\n\n this.#getDelegationTransaction = getDelegationTransaction;\n this.#getStrategy = getStrategy;\n this.#getStrategies = getStrategies;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n subscribeTransactionChanges(\n messenger,\n this.#updateTransactionData.bind(this),\n this.#removeTransactionData.bind(this),\n );\n\n subscribeAssetChanges(\n messenger,\n () => this.state,\n this.#updateTransactionData.bind(this),\n );\n\n // eslint-disable-next-line no-new\n new QuoteRefresher({\n getStrategies: this.#getStrategiesWithFallback.bind(this),\n messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Sets the transaction configuration.\n *\n * The callback receives the current configuration properties and can mutate\n * them in place. Updated values are written back to the transaction data.\n *\n * @param transactionId - The ID of the transaction to configure.\n * @param callback - A callback that receives a mutable {@link TransactionConfig} object.\n */\n setTransactionConfig(\n transactionId: string,\n callback: TransactionConfigCallback,\n ): void {\n this.#updateTransactionData(transactionId, (transactionData) => {\n const config = {\n isMaxAmount: transactionData.isMaxAmount,\n isPostQuote: transactionData.isPostQuote,\n isHyperliquidSource: transactionData.isHyperliquidSource,\n refundTo: transactionData.refundTo,\n accountOverride: transactionData.accountOverride,\n };\n\n const previousAccountOverride = config.accountOverride;\n\n callback(config);\n\n transactionData.accountOverride = config.accountOverride;\n transactionData.isMaxAmount = config.isMaxAmount;\n transactionData.isPostQuote = config.isPostQuote;\n transactionData.isHyperliquidSource = config.isHyperliquidSource;\n transactionData.refundTo = config.refundTo;\n\n if (config.accountOverride !== previousAccountOverride) {\n transactionData.paymentToken = undefined;\n }\n });\n }\n\n /**\n * Updates the payment token for a transaction.\n *\n * Resolves token metadata and balances, then stores the new payment token\n * in the transaction data. This triggers recalculation of source amounts\n * and quote retrieval.\n *\n * @param request - The payment token update request containing the\n * transaction ID, token address, and chain ID.\n */\n updatePaymentToken(request: UpdatePaymentTokenRequest): void {\n updatePaymentToken(request, {\n messenger: this.messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Updates the fiat payment state for a transaction.\n *\n * The request callback receives the current fiat payment state and can\n * mutate it to update properties such as the selected payment method or\n * fiat amount.\n *\n * @param request - The fiat payment update request containing the\n * transaction ID and a callback to mutate fiat payment state.\n */\n updateFiatPayment(request: UpdateFiatPaymentRequest): void {\n updateFiatPayment(request, {\n messenger: this.messenger,\n updateTransactionData: this.#updateTransactionData.bind(this),\n });\n }\n\n /**\n * Gets the delegation transaction for a given transaction.\n *\n * Converts the provided transaction into a redeem delegation by delegating\n * to the configured callback. Returns the delegation transaction data\n * including the encoded call data, target address, value, and an optional\n * authorization list.\n *\n * @param args - The arguments forwarded to the {@link GetDelegationTransactionCallback},\n * containing the transaction metadata.\n * @returns A promise resolving to the delegation transaction data.\n */\n getDelegationTransaction(\n ...args: Parameters<GetDelegationTransactionCallback>\n ): ReturnType<GetDelegationTransactionCallback> {\n return this.#getDelegationTransaction(...args);\n }\n\n /**\n * Gets the preferred strategy for a transaction.\n *\n * Returns the first strategy from the ordered list of strategies applicable\n * to the given transaction. Falls back to the default strategy order derived\n * from feature flags when no custom strategy callback is configured.\n *\n * @param transaction - The transaction metadata to determine the strategy for.\n * @returns The preferred {@link TransactionPayStrategy} for the transaction.\n */\n getStrategy(transaction: TransactionMeta): TransactionPayStrategy {\n return this.#getStrategiesWithFallback(transaction)[0];\n }\n\n #removeTransactionData(transactionId: string): void {\n this.update((state) => {\n delete state.transactionData[transactionId];\n });\n }\n\n #updateTransactionData(\n transactionId: string,\n fn: (transactionData: Draft<TransactionData>) => void,\n ): void {\n let shouldUpdateQuotes = false;\n let shouldUpdateFiatToken = false;\n\n this.update((state) => {\n const { transactionData } = state;\n let current = transactionData[transactionId];\n const originalPaymentToken = current?.paymentToken;\n const originalTokens = current?.tokens;\n const originalIsMaxAmount = current?.isMaxAmount;\n const originalIsPostQuote = current?.isPostQuote;\n const originalAccountOverride = current?.accountOverride;\n const originalFiatPaymentAmount = current?.fiatPayment?.amountFiat;\n const originalFiatPaymentMethodId =\n current?.fiatPayment?.selectedPaymentMethodId;\n\n if (!current) {\n transactionData[transactionId] = {\n fiatPayment: {},\n isLoading: false,\n tokens: [],\n };\n\n current = transactionData[transactionId];\n }\n\n fn(current);\n\n const isPaymentTokenUpdated =\n current.paymentToken?.address?.toLowerCase() !==\n originalPaymentToken?.address?.toLowerCase() ||\n current.paymentToken?.chainId !== originalPaymentToken?.chainId;\n\n const isTokensUpdated = current.tokens !== originalTokens;\n const isIsMaxUpdated = current.isMaxAmount !== originalIsMaxAmount;\n const isPostQuoteUpdated = current.isPostQuote !== originalIsPostQuote;\n const isAccountOverrideUpdated =\n current.accountOverride !== originalAccountOverride;\n const isFiatAmountUpdated =\n current.fiatPayment?.amountFiat !== originalFiatPaymentAmount;\n const isFiatPaymentMethodUpdated =\n current.fiatPayment?.selectedPaymentMethodId !==\n originalFiatPaymentMethodId;\n\n if (\n isPaymentTokenUpdated ||\n isIsMaxUpdated ||\n isTokensUpdated ||\n isPostQuoteUpdated ||\n isAccountOverrideUpdated\n ) {\n updateSourceAmounts(transactionId, current as never, this.messenger);\n\n shouldUpdateQuotes = true;\n }\n\n if (isFiatAmountUpdated || isFiatPaymentMethodUpdated) {\n shouldUpdateQuotes = true;\n }\n\n if (isFiatPaymentMethodUpdated) {\n shouldUpdateFiatToken = true;\n }\n });\n\n if (shouldUpdateFiatToken) {\n const transaction = getTransaction(\n transactionId,\n this.messenger,\n ) as TransactionMeta;\n const fiatAsset = deriveFiatAssetForFiatPayment(\n transaction,\n this.messenger,\n );\n if (fiatAsset) {\n this.#updateTransactionData(transactionId, (data) => {\n if (data.fiatPayment) {\n data.fiatPayment.caipAssetId = buildCaipAssetType(\n fiatAsset.chainId,\n fiatAsset.address,\n );\n }\n });\n }\n }\n\n if (shouldUpdateQuotes) {\n updateQuotes({\n getStrategies: this.#getStrategiesWithFallback.bind(this),\n messenger: this.messenger,\n transactionData: this.state.transactionData[transactionId],\n transactionId,\n updateTransactionData: this.#updateTransactionData.bind(this),\n }).catch(noop);\n }\n }\n\n #getStrategiesWithFallback(\n transaction: TransactionMeta,\n ): TransactionPayStrategy[] {\n const strategyCandidates: unknown[] =\n this.#getStrategies?.(transaction) ??\n (this.#getStrategy ? [this.#getStrategy(transaction)] : []);\n\n const validStrategies = strategyCandidates.filter(\n (strategy): strategy is TransactionPayStrategy =>\n isTransactionPayStrategy(strategy),\n );\n\n if (validStrategies.length) {\n return validStrategies;\n }\n\n const transactionData = this.state.transactionData[transaction.id];\n const paymentToken = transactionData?.paymentToken;\n\n return getStrategyOrder(\n this.messenger,\n paymentToken?.chainId,\n paymentToken?.address,\n transaction.type,\n transactionData?.fiatPayment?.selectedPaymentMethodId,\n );\n }\n}\n"]}
@@ -37,23 +37,24 @@ async function submitFiatQuotes(request) {
37
37
  throw new Error('Missing wallet address for fiat submission');
38
38
  }
39
39
  const state = messenger.call('TransactionPayController:getState');
40
- const orderId = state.transactionData[transactionId]?.fiatPayment?.orderId;
40
+ const fiatPayment = state.transactionData[transactionId]?.fiatPayment;
41
+ const orderId = fiatPayment?.orderId;
41
42
  if (!orderId) {
42
43
  throw new Error('Missing order ID for fiat submission');
43
44
  }
44
- const parsedOrder = parseOrderId(orderId);
45
- if (!parsedOrder) {
46
- throw new Error(`Invalid order ID format: ${orderId}`);
45
+ const providerCode = extractProviderCode(fiatPayment?.rampsQuote?.provider);
46
+ if (!providerCode) {
47
+ throw new Error('Missing provider code for fiat submission');
47
48
  }
48
49
  log('Starting fiat order polling', {
49
50
  orderId,
50
- providerCode: parsedOrder.providerCode,
51
+ providerCode,
51
52
  transactionId,
52
53
  });
53
54
  const order = await waitForOrderCompletion({
54
55
  messenger,
55
- orderCode: parsedOrder.orderCode,
56
- providerCode: parsedOrder.providerCode,
56
+ orderCode: orderId,
57
+ providerCode,
57
58
  transactionId,
58
59
  walletAddress,
59
60
  });
@@ -66,17 +67,17 @@ async function submitFiatQuotes(request) {
66
67
  }
67
68
  exports.submitFiatQuotes = submitFiatQuotes;
68
69
  /**
69
- * Parses a normalized order ID string into its provider and order components.
70
+ * Extracts the provider code from a ramps provider string.
70
71
  *
71
- * @param orderId - Order ID in `/providers/{providerCode}/orders/{orderCode}` format.
72
- * @returns The parsed provider and order codes, or `null` if the format is invalid.
72
+ * @param provider - Provider string (e.g. `/providers/transak-native`).
73
+ * @returns The provider code, or `null` if the format is invalid.
73
74
  */
74
- function parseOrderId(orderId) {
75
- const parts = orderId.split('/').filter(Boolean);
76
- if (parts.length < 4 || parts[0] !== 'providers' || parts[2] !== 'orders') {
75
+ function extractProviderCode(provider) {
76
+ if (!provider) {
77
77
  return null;
78
78
  }
79
- return { orderCode: parts[3], providerCode: parts[1] };
79
+ const parts = provider.split('/').filter(Boolean);
80
+ return parts.length >= 2 && parts[0] === 'providers' ? parts[1] : null;
80
81
  }
81
82
  /**
82
83
  * Converts the order's human-readable crypto amount to a raw token amount.
@@ -1 +1 @@
1
- {"version":3,"file":"fiat-submit.cjs","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-submit.ts"],"names":[],"mappings":";;;AAIA,iEAA8D;AAE9D,2CAAqD;AACrD,+CAAyC;AAEzC,6CAA6C;AAO7C,iDAAqE;AACrE,4DAAuD;AACvD,4DAA0D;AAI1D,uCAAwD;AAExD,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,aAAa,CAAC,CAAC;AAE7D,MAAM,sBAAsB,GAAG,IAAI,CAAC;AACpC,MAAM,qBAAqB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC7C,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B,MAAM,yBAAyB,GAAuB;IACpD,mCAAgB,CAAC,SAAS;IAC1B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C,SAAS;QACT,MAAM,EAAE,WAAW;QACnB,WAAW;KACZ,CAAC;IAEF,MAAM,WAAW,GAAG,MAAM,IAAA,gCAAiB,EAAC,kBAAkB,CAAC,CAAC;IAEhE,GAAG,CAAC,6CAA6C,EAAE;QACjD,WAAW;QACX,aAAa;KACd,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import type {\n RampsOrder,\n RampsOrderCryptoCurrency,\n} from '@metamask/ramps-controller';\nimport { RampsOrderStatus } from '@metamask/ramps-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { projectLogger } from '../../logger';\nimport type {\n PayStrategy,\n PayStrategyExecuteRequest,\n QuoteRequest,\n TransactionPayControllerMessenger,\n} from '../../types';\nimport { buildCaipAssetType, getTokenInfo } from '../../utils/token';\nimport { getRelayQuotes } from '../relay/relay-quotes';\nimport { submitRelayQuotes } from '../relay/relay-submit';\nimport type { RelayQuote } from '../relay/types';\nimport type { TransactionPayFiatAsset } from './constants';\nimport type { FiatQuote } from './types';\nimport { deriveFiatAssetForFiatPayment } from './utils';\n\nconst log = createModuleLogger(projectLogger, 'fiat-submit');\n\nconst ORDER_POLL_INTERVAL_MS = 1000;\nconst ORDER_POLL_TIMEOUT_MS = 10 * 60 * 1000;\nconst MAX_SLIPPAGE_PERCENT = 5;\n\nconst TERMINAL_FAILURE_STATUSES: RampsOrderStatus[] = [\n RampsOrderStatus.Cancelled,\n RampsOrderStatus.Failed,\n RampsOrderStatus.IdExpired,\n];\n\n/**\n * Submits fiat strategy quotes by polling the on-ramp order until completion,\n * then re-quoting and submitting the relay leg with the settled crypto amount.\n *\n * @param request - Strategy execute request containing fiat quotes, messenger, and transaction metadata.\n * @param request.messenger - Controller messenger for cross-controller calls.\n * @param request.quotes - Fiat quotes to execute (exactly one expected).\n * @param request.transaction - Original transaction metadata.\n * @param request.isSmartTransaction - Callback to check smart transaction eligibility.\n * @returns An object containing the relay transaction hash if available.\n */\nexport async function submitFiatQuotes(\n request: PayStrategyExecuteRequest<FiatQuote>,\n): ReturnType<PayStrategy<FiatQuote>['execute']> {\n const { messenger, transaction } = request;\n const transactionId = transaction.id;\n const walletAddress = transaction.txParams.from as Hex | undefined;\n\n if (!walletAddress) {\n throw new Error('Missing wallet address for fiat submission');\n }\n\n const state = messenger.call('TransactionPayController:getState');\n const orderId = state.transactionData[transactionId]?.fiatPayment?.orderId;\n\n if (!orderId) {\n throw new Error('Missing order ID for fiat submission');\n }\n\n const parsedOrder = parseOrderId(orderId);\n\n if (!parsedOrder) {\n throw new Error(`Invalid order ID format: ${orderId}`);\n }\n\n log('Starting fiat order polling', {\n orderId,\n providerCode: parsedOrder.providerCode,\n transactionId,\n });\n\n const order = await waitForOrderCompletion({\n messenger,\n orderCode: parsedOrder.orderCode,\n providerCode: parsedOrder.providerCode,\n transactionId,\n walletAddress,\n });\n\n log('Fiat order completed', {\n cryptoAmount: order.cryptoAmount,\n orderId,\n transactionId,\n });\n\n return await submitRelayAfterFiatCompletion({ order, request });\n}\n\n/**\n * Parses a normalized order ID string into its provider and order components.\n *\n * @param orderId - Order ID in `/providers/{providerCode}/orders/{orderCode}` format.\n * @returns The parsed provider and order codes, or `null` if the format is invalid.\n */\nfunction parseOrderId(\n orderId: string,\n): { orderCode: string; providerCode: string } | null {\n const parts = orderId.split('/').filter(Boolean);\n\n if (parts.length < 4 || parts[0] !== 'providers' || parts[2] !== 'orders') {\n return null;\n }\n\n return { orderCode: parts[3], providerCode: parts[1] };\n}\n\n/**\n * Converts the order's human-readable crypto amount to a raw token amount.\n *\n * @param options - The conversion options.\n * @param options.cryptoAmount - Human-readable crypto amount from the completed order.\n * @param options.decimals - Token decimals for the fiat asset.\n * @returns The raw token amount as a string.\n */\nfunction getRawSourceAmountFromOrder({\n cryptoAmount,\n decimals,\n}: {\n cryptoAmount: RampsOrder['cryptoAmount'];\n decimals: number;\n}): string {\n const normalizedAmount = new BigNumber(String(cryptoAmount));\n\n if (!normalizedAmount.isFinite() || normalizedAmount.lte(0)) {\n throw new Error(\n `Invalid fiat order crypto amount: ${String(cryptoAmount)}`,\n );\n }\n\n const rawAmount = normalizedAmount\n .shiftedBy(decimals)\n .decimalPlaces(0, BigNumber.ROUND_DOWN)\n .toFixed(0);\n\n if (!new BigNumber(rawAmount).gt(0)) {\n throw new Error('Computed fiat order source amount is not positive');\n }\n\n return rawAmount;\n}\n\n/**\n * Validates that the completed order's crypto asset matches the expected fiat asset.\n *\n * @param options - The validation options.\n * @param options.expectedAsset - The expected fiat asset derived from the transaction type.\n * @param options.orderCrypto - The crypto currency information from the completed order.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nfunction validateOrderAsset({\n expectedAsset,\n orderCrypto,\n transactionId,\n}: {\n expectedAsset: TransactionPayFiatAsset;\n orderCrypto: RampsOrderCryptoCurrency | undefined;\n transactionId: string;\n}): void {\n const orderAssetId = orderCrypto?.assetId?.toLowerCase();\n const expectedAssetId = buildCaipAssetType(\n expectedAsset.chainId,\n expectedAsset.address,\n ).toLowerCase();\n const expectedChainId = expectedAssetId.split('/')[0];\n const orderChainId = orderCrypto?.chainId?.toLowerCase();\n\n if (orderAssetId && orderAssetId !== expectedAssetId) {\n throw new Error(\n `Fiat order asset mismatch for transaction ${transactionId}: ` +\n `expected ${expectedAssetId}, got ${orderAssetId}`,\n );\n }\n\n if (orderChainId && orderChainId !== expectedChainId) {\n throw new Error(\n `Fiat order chain mismatch for transaction ${transactionId}: ` +\n `expected ${expectedChainId}, got ${orderChainId}`,\n );\n }\n}\n\n/**\n * Validates that the re-quoted relay target output hasn't drifted beyond the\n * acceptable slippage threshold compared to the original quote shown to the user.\n *\n * @param options - The validation options.\n * @param options.originalTargetRaw - Raw target amount from the original relay quote.\n * @param options.reQuotedTargetRaw - Raw target amount from the re-quoted relay.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nfunction validateRelaySlippage({\n originalTargetRaw,\n reQuotedTargetRaw,\n transactionId,\n}: {\n originalTargetRaw: string;\n reQuotedTargetRaw: string;\n transactionId: string;\n}): void {\n const original = new BigNumber(originalTargetRaw);\n const reQuoted = new BigNumber(reQuotedTargetRaw);\n\n if (!original.gt(0) || !reQuoted.gt(0)) {\n return;\n }\n\n const slippagePercent = original\n .minus(reQuoted)\n .dividedBy(original)\n .multipliedBy(100);\n\n log('Relay slippage check', {\n originalTargetRaw,\n reQuotedTargetRaw,\n slippagePercent: slippagePercent.toFixed(2),\n transactionId,\n });\n\n if (slippagePercent.gt(MAX_SLIPPAGE_PERCENT)) {\n throw new Error(\n `Relay re-quote slippage too high for transaction ` +\n `${slippagePercent.toFixed(2)}% exceeds ${MAX_SLIPPAGE_PERCENT}% max`,\n );\n }\n}\n\n/**\n * Polls the on-ramp order until it reaches a terminal status.\n *\n * @param options - The polling options.\n * @param options.messenger - Controller messenger for calling `RampsController:getOrder`.\n * @param options.orderCode - The order identifier within the provider.\n * @param options.providerCode - The on-ramp provider code (e.g. \"transak\").\n * @param options.transactionId - Transaction ID for logging.\n * @param options.walletAddress - Wallet address associated with the order.\n * @returns The completed order data.\n */\nasync function waitForOrderCompletion({\n messenger,\n orderCode,\n providerCode,\n transactionId,\n walletAddress,\n}: {\n messenger: TransactionPayControllerMessenger;\n orderCode: string;\n providerCode: string;\n transactionId: string;\n walletAddress: string;\n}): Promise<RampsOrder> {\n const startTime = Date.now();\n let lastStatus: string | undefined;\n\n while (true) {\n let order: RampsOrder | undefined;\n\n try {\n order = await messenger.call(\n 'RampsController:getOrder',\n providerCode,\n orderCode,\n walletAddress,\n );\n } catch (error) {\n log('Order polling network error', error);\n }\n\n if (order) {\n lastStatus = order.status;\n\n log('Polled fiat order', {\n orderStatus: order.status,\n providerCode,\n transactionId,\n });\n\n if (order.status === RampsOrderStatus.Completed) {\n return order;\n }\n\n if (TERMINAL_FAILURE_STATUSES.includes(order.status)) {\n throw new Error(`Fiat order ${order.status.toLowerCase()}`);\n }\n }\n\n if (Date.now() - startTime >= ORDER_POLL_TIMEOUT_MS) {\n throw new Error(\n `Fiat order polling timed out (last status: ${lastStatus})`,\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, ORDER_POLL_INTERVAL_MS));\n }\n}\n\n/**\n * Re-quotes and submits the relay leg using the settled amount from a completed fiat order.\n *\n * @param options - The submission options.\n * @param options.order - The completed on-ramp order containing the settled crypto amount.\n * @param options.request - The original fiat strategy execute request.\n * @returns An object containing the relay transaction hash if available.\n */\nasync function submitRelayAfterFiatCompletion({\n order,\n request,\n}: {\n order: RampsOrder;\n request: PayStrategyExecuteRequest<FiatQuote>;\n}): Promise<{ transactionHash?: Hex }> {\n const { messenger, quotes, transaction } = request;\n const transactionId = transaction.id;\n\n if (!quotes.length) {\n throw new Error('Missing fiat quote for relay submission');\n }\n\n if (quotes.length > 1) {\n throw new Error('Multiple fiat quotes are not supported for submission');\n }\n\n const fiatAsset = deriveFiatAssetForFiatPayment(transaction, messenger);\n\n validateOrderAsset({\n expectedAsset: fiatAsset,\n orderCrypto: order.cryptoCurrency,\n transactionId,\n });\n\n const tokenInfo = getTokenInfo(\n messenger,\n fiatAsset.address,\n fiatAsset.chainId,\n );\n\n if (!tokenInfo) {\n throw new Error(\n `Unable to resolve token info for fiat asset ${fiatAsset.address} on chain ${fiatAsset.chainId}`,\n );\n }\n\n const sourceAmountRaw = getRawSourceAmountFromOrder({\n cryptoAmount: order.cryptoAmount,\n decimals: tokenInfo.decimals,\n });\n\n const baseRequest = quotes[0].request;\n const relayRequest: QuoteRequest = {\n ...baseRequest,\n isMaxAmount: true,\n isPostQuote: false,\n sourceBalanceRaw: sourceAmountRaw,\n sourceTokenAmount: sourceAmountRaw,\n };\n\n log('Re-quoting relay from completed fiat order', {\n completedOrderAmount: order.cryptoAmount,\n relayRequest,\n sourceAmountRaw,\n transactionId,\n });\n\n const relayQuotes = await getRelayQuotes({\n accountSupports7702: request.accountSupports7702,\n messenger,\n requests: [relayRequest],\n transaction,\n });\n\n if (!relayQuotes.length) {\n throw new Error('No relay quotes returned for completed fiat order');\n }\n\n const originalRelayQuote = quotes[0].original.relayQuote;\n validateRelaySlippage({\n originalTargetRaw: originalRelayQuote.details.currencyOut.amount,\n reQuotedTargetRaw: relayQuotes[0].original.details.currencyOut.amount,\n transactionId,\n });\n\n log('Received relay quotes for completed fiat order', {\n relayQuoteCount: relayQuotes.length,\n transactionId,\n });\n\n const relaySubmitRequest: PayStrategyExecuteRequest<RelayQuote> = {\n accountSupports7702: request.accountSupports7702,\n isSmartTransaction: request.isSmartTransaction,\n messenger,\n quotes: relayQuotes,\n transaction,\n };\n\n const relayResult = await submitRelayQuotes(relaySubmitRequest);\n\n log('Relay submission completed after fiat order', {\n relayResult,\n transactionId,\n });\n\n return relayResult;\n}\n"]}
1
+ {"version":3,"file":"fiat-submit.cjs","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-submit.ts"],"names":[],"mappings":";;;AAIA,iEAA8D;AAE9D,2CAAqD;AACrD,+CAAyC;AAEzC,6CAA6C;AAO7C,iDAAqE;AACrE,4DAAuD;AACvD,4DAA0D;AAI1D,uCAAwD;AAExD,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,aAAa,CAAC,CAAC;AAE7D,MAAM,sBAAsB,GAAG,IAAI,CAAC;AACpC,MAAM,qBAAqB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC7C,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B,MAAM,yBAAyB,GAAuB;IACpD,mCAAgB,CAAC,SAAS;IAC1B,mCAAgB,CAAC,MAAM;IACvB,mCAAgB,CAAC,SAAS;CAC3B,CAAC;AAEF;;;;;;;;;;GAUG;AACI,KAAK,UAAU,gBAAgB,CACpC,OAA6C;IAE7C,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;IAC3C,MAAM,aAAa,GAAG,WAAW,CAAC,EAAE,CAAC;IACrC,MAAM,aAAa,GAAG,WAAW,CAAC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IAEF,GAAG,CAAC,4CAA4C,EAAE;QAChD,oBAAoB,EAAE,KAAK,CAAC,YAAY;QACxC,YAAY;QACZ,eAAe;QACf,aAAa;KACd,CAAC,CAAC;IAEH,MAAM,WAAW,GAAG,MAAM,IAAA,6BAAc,EAAC;QACvC,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;QAChD,SAAS;QACT,QAAQ,EAAE,CAAC,YAAY,CAAC;QACxB,WAAW;KACZ,CAAC,CAAC;IAEH,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;IACvE,CAAC;IAED,MAAM,kBAAkB,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC;IACzD,qBAAqB,CAAC;QACpB,iBAAiB,EAAE,kBAAkB,CAAC,OAAO,CAAC,WAAW,CAAC,MAAM;QAChE,iBAAiB,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,MAAM;QACrE,aAAa;KACd,CAAC,CAAC;IAEH,GAAG,CAAC,gDAAgD,EAAE;QACpD,eAAe,EAAE,WAAW,CAAC,MAAM;QACnC,aAAa;KACd,CAAC,CAAC;IAEH,MAAM,kBAAkB,GAA0C;QAChE,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;QAChD,kBAAkB,EAAE,OAAO,CAAC,kBAAkB;QAC9C,SAAS;QACT,MAAM,EAAE,WAAW;QACnB,WAAW;KACZ,CAAC;IAEF,MAAM,WAAW,GAAG,MAAM,IAAA,gCAAiB,EAAC,kBAAkB,CAAC,CAAC;IAEhE,GAAG,CAAC,6CAA6C,EAAE;QACjD,WAAW;QACX,aAAa;KACd,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import type {\n RampsOrder,\n RampsOrderCryptoCurrency,\n} from '@metamask/ramps-controller';\nimport { RampsOrderStatus } from '@metamask/ramps-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { projectLogger } from '../../logger';\nimport type {\n PayStrategy,\n PayStrategyExecuteRequest,\n QuoteRequest,\n TransactionPayControllerMessenger,\n} from '../../types';\nimport { buildCaipAssetType, getTokenInfo } from '../../utils/token';\nimport { getRelayQuotes } from '../relay/relay-quotes';\nimport { submitRelayQuotes } from '../relay/relay-submit';\nimport type { RelayQuote } from '../relay/types';\nimport type { TransactionPayFiatAsset } from './constants';\nimport type { FiatQuote } from './types';\nimport { deriveFiatAssetForFiatPayment } from './utils';\n\nconst log = createModuleLogger(projectLogger, 'fiat-submit');\n\nconst ORDER_POLL_INTERVAL_MS = 1000;\nconst ORDER_POLL_TIMEOUT_MS = 10 * 60 * 1000;\nconst MAX_SLIPPAGE_PERCENT = 5;\n\nconst TERMINAL_FAILURE_STATUSES: RampsOrderStatus[] = [\n RampsOrderStatus.Cancelled,\n RampsOrderStatus.Failed,\n RampsOrderStatus.IdExpired,\n];\n\n/**\n * Submits fiat strategy quotes by polling the on-ramp order until completion,\n * then re-quoting and submitting the relay leg with the settled crypto amount.\n *\n * @param request - Strategy execute request containing fiat quotes, messenger, and transaction metadata.\n * @param request.messenger - Controller messenger for cross-controller calls.\n * @param request.quotes - Fiat quotes to execute (exactly one expected).\n * @param request.transaction - Original transaction metadata.\n * @param request.isSmartTransaction - Callback to check smart transaction eligibility.\n * @returns An object containing the relay transaction hash if available.\n */\nexport async function submitFiatQuotes(\n request: PayStrategyExecuteRequest<FiatQuote>,\n): ReturnType<PayStrategy<FiatQuote>['execute']> {\n const { messenger, transaction } = request;\n const transactionId = transaction.id;\n const walletAddress = transaction.txParams.from as Hex | undefined;\n\n if (!walletAddress) {\n throw new Error('Missing wallet address for fiat submission');\n }\n\n const state = messenger.call('TransactionPayController:getState');\n const fiatPayment = state.transactionData[transactionId]?.fiatPayment;\n const orderId = fiatPayment?.orderId;\n\n if (!orderId) {\n throw new Error('Missing order ID for fiat submission');\n }\n\n const providerCode = extractProviderCode(fiatPayment?.rampsQuote?.provider);\n\n if (!providerCode) {\n throw new Error('Missing provider code for fiat submission');\n }\n\n log('Starting fiat order polling', {\n orderId,\n providerCode,\n transactionId,\n });\n\n const order = await waitForOrderCompletion({\n messenger,\n orderCode: orderId,\n providerCode,\n transactionId,\n walletAddress,\n });\n\n log('Fiat order completed', {\n cryptoAmount: order.cryptoAmount,\n orderId,\n transactionId,\n });\n\n return await submitRelayAfterFiatCompletion({ order, request });\n}\n\n/**\n * Extracts the provider code from a ramps provider string.\n *\n * @param provider - Provider string (e.g. `/providers/transak-native`).\n * @returns The provider code, or `null` if the format is invalid.\n */\nfunction extractProviderCode(provider: string | undefined): string | null {\n if (!provider) {\n return null;\n }\n\n const parts = provider.split('/').filter(Boolean);\n return parts.length >= 2 && parts[0] === 'providers' ? parts[1] : null;\n}\n\n/**\n * Converts the order's human-readable crypto amount to a raw token amount.\n *\n * @param options - The conversion options.\n * @param options.cryptoAmount - Human-readable crypto amount from the completed order.\n * @param options.decimals - Token decimals for the fiat asset.\n * @returns The raw token amount as a string.\n */\nfunction getRawSourceAmountFromOrder({\n cryptoAmount,\n decimals,\n}: {\n cryptoAmount: RampsOrder['cryptoAmount'];\n decimals: number;\n}): string {\n const normalizedAmount = new BigNumber(String(cryptoAmount));\n\n if (!normalizedAmount.isFinite() || normalizedAmount.lte(0)) {\n throw new Error(\n `Invalid fiat order crypto amount: ${String(cryptoAmount)}`,\n );\n }\n\n const rawAmount = normalizedAmount\n .shiftedBy(decimals)\n .decimalPlaces(0, BigNumber.ROUND_DOWN)\n .toFixed(0);\n\n if (!new BigNumber(rawAmount).gt(0)) {\n throw new Error('Computed fiat order source amount is not positive');\n }\n\n return rawAmount;\n}\n\n/**\n * Validates that the completed order's crypto asset matches the expected fiat asset.\n *\n * @param options - The validation options.\n * @param options.expectedAsset - The expected fiat asset derived from the transaction type.\n * @param options.orderCrypto - The crypto currency information from the completed order.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nfunction validateOrderAsset({\n expectedAsset,\n orderCrypto,\n transactionId,\n}: {\n expectedAsset: TransactionPayFiatAsset;\n orderCrypto: RampsOrderCryptoCurrency | undefined;\n transactionId: string;\n}): void {\n const orderAssetId = orderCrypto?.assetId?.toLowerCase();\n const expectedAssetId = buildCaipAssetType(\n expectedAsset.chainId,\n expectedAsset.address,\n ).toLowerCase();\n const expectedChainId = expectedAssetId.split('/')[0];\n const orderChainId = orderCrypto?.chainId?.toLowerCase();\n\n if (orderAssetId && orderAssetId !== expectedAssetId) {\n throw new Error(\n `Fiat order asset mismatch for transaction ${transactionId}: ` +\n `expected ${expectedAssetId}, got ${orderAssetId}`,\n );\n }\n\n if (orderChainId && orderChainId !== expectedChainId) {\n throw new Error(\n `Fiat order chain mismatch for transaction ${transactionId}: ` +\n `expected ${expectedChainId}, got ${orderChainId}`,\n );\n }\n}\n\n/**\n * Validates that the re-quoted relay target output hasn't drifted beyond the\n * acceptable slippage threshold compared to the original quote shown to the user.\n *\n * @param options - The validation options.\n * @param options.originalTargetRaw - Raw target amount from the original relay quote.\n * @param options.reQuotedTargetRaw - Raw target amount from the re-quoted relay.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nfunction validateRelaySlippage({\n originalTargetRaw,\n reQuotedTargetRaw,\n transactionId,\n}: {\n originalTargetRaw: string;\n reQuotedTargetRaw: string;\n transactionId: string;\n}): void {\n const original = new BigNumber(originalTargetRaw);\n const reQuoted = new BigNumber(reQuotedTargetRaw);\n\n if (!original.gt(0) || !reQuoted.gt(0)) {\n return;\n }\n\n const slippagePercent = original\n .minus(reQuoted)\n .dividedBy(original)\n .multipliedBy(100);\n\n log('Relay slippage check', {\n originalTargetRaw,\n reQuotedTargetRaw,\n slippagePercent: slippagePercent.toFixed(2),\n transactionId,\n });\n\n if (slippagePercent.gt(MAX_SLIPPAGE_PERCENT)) {\n throw new Error(\n `Relay re-quote slippage too high for transaction ` +\n `${slippagePercent.toFixed(2)}% exceeds ${MAX_SLIPPAGE_PERCENT}% max`,\n );\n }\n}\n\n/**\n * Polls the on-ramp order until it reaches a terminal status.\n *\n * @param options - The polling options.\n * @param options.messenger - Controller messenger for calling `RampsController:getOrder`.\n * @param options.orderCode - The order identifier within the provider.\n * @param options.providerCode - The on-ramp provider code (e.g. \"transak\").\n * @param options.transactionId - Transaction ID for logging.\n * @param options.walletAddress - Wallet address associated with the order.\n * @returns The completed order data.\n */\nasync function waitForOrderCompletion({\n messenger,\n orderCode,\n providerCode,\n transactionId,\n walletAddress,\n}: {\n messenger: TransactionPayControllerMessenger;\n orderCode: string;\n providerCode: string;\n transactionId: string;\n walletAddress: string;\n}): Promise<RampsOrder> {\n const startTime = Date.now();\n let lastStatus: string | undefined;\n\n while (true) {\n let order: RampsOrder | undefined;\n\n try {\n order = await messenger.call(\n 'RampsController:getOrder',\n providerCode,\n orderCode,\n walletAddress,\n );\n } catch (error) {\n log('Order polling network error', error);\n }\n\n if (order) {\n lastStatus = order.status;\n\n log('Polled fiat order', {\n orderStatus: order.status,\n providerCode,\n transactionId,\n });\n\n if (order.status === RampsOrderStatus.Completed) {\n return order;\n }\n\n if (TERMINAL_FAILURE_STATUSES.includes(order.status)) {\n throw new Error(`Fiat order ${order.status.toLowerCase()}`);\n }\n }\n\n if (Date.now() - startTime >= ORDER_POLL_TIMEOUT_MS) {\n throw new Error(\n `Fiat order polling timed out (last status: ${lastStatus})`,\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, ORDER_POLL_INTERVAL_MS));\n }\n}\n\n/**\n * Re-quotes and submits the relay leg using the settled amount from a completed fiat order.\n *\n * @param options - The submission options.\n * @param options.order - The completed on-ramp order containing the settled crypto amount.\n * @param options.request - The original fiat strategy execute request.\n * @returns An object containing the relay transaction hash if available.\n */\nasync function submitRelayAfterFiatCompletion({\n order,\n request,\n}: {\n order: RampsOrder;\n request: PayStrategyExecuteRequest<FiatQuote>;\n}): Promise<{ transactionHash?: Hex }> {\n const { messenger, quotes, transaction } = request;\n const transactionId = transaction.id;\n\n if (!quotes.length) {\n throw new Error('Missing fiat quote for relay submission');\n }\n\n if (quotes.length > 1) {\n throw new Error('Multiple fiat quotes are not supported for submission');\n }\n\n const fiatAsset = deriveFiatAssetForFiatPayment(transaction, messenger);\n\n validateOrderAsset({\n expectedAsset: fiatAsset,\n orderCrypto: order.cryptoCurrency,\n transactionId,\n });\n\n const tokenInfo = getTokenInfo(\n messenger,\n fiatAsset.address,\n fiatAsset.chainId,\n );\n\n if (!tokenInfo) {\n throw new Error(\n `Unable to resolve token info for fiat asset ${fiatAsset.address} on chain ${fiatAsset.chainId}`,\n );\n }\n\n const sourceAmountRaw = getRawSourceAmountFromOrder({\n cryptoAmount: order.cryptoAmount,\n decimals: tokenInfo.decimals,\n });\n\n const baseRequest = quotes[0].request;\n const relayRequest: QuoteRequest = {\n ...baseRequest,\n isMaxAmount: true,\n isPostQuote: false,\n sourceBalanceRaw: sourceAmountRaw,\n sourceTokenAmount: sourceAmountRaw,\n };\n\n log('Re-quoting relay from completed fiat order', {\n completedOrderAmount: order.cryptoAmount,\n relayRequest,\n sourceAmountRaw,\n transactionId,\n });\n\n const relayQuotes = await getRelayQuotes({\n accountSupports7702: request.accountSupports7702,\n messenger,\n requests: [relayRequest],\n transaction,\n });\n\n if (!relayQuotes.length) {\n throw new Error('No relay quotes returned for completed fiat order');\n }\n\n const originalRelayQuote = quotes[0].original.relayQuote;\n validateRelaySlippage({\n originalTargetRaw: originalRelayQuote.details.currencyOut.amount,\n reQuotedTargetRaw: relayQuotes[0].original.details.currencyOut.amount,\n transactionId,\n });\n\n log('Received relay quotes for completed fiat order', {\n relayQuoteCount: relayQuotes.length,\n transactionId,\n });\n\n const relaySubmitRequest: PayStrategyExecuteRequest<RelayQuote> = {\n accountSupports7702: request.accountSupports7702,\n isSmartTransaction: request.isSmartTransaction,\n messenger,\n quotes: relayQuotes,\n transaction,\n };\n\n const relayResult = await submitRelayQuotes(relaySubmitRequest);\n\n log('Relay submission completed after fiat order', {\n relayResult,\n transactionId,\n });\n\n return relayResult;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"fiat-submit.d.cts","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-submit.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EACV,WAAW,EACX,yBAAyB,EAG1B,wBAAoB;AAMrB,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAgB;AAezC;;;;;;;;;;GAUG;AACH,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,yBAAyB,CAAC,SAAS,CAAC,GAC5C,UAAU,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,CA2C/C"}
1
+ {"version":3,"file":"fiat-submit.d.cts","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-submit.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EACV,WAAW,EACX,yBAAyB,EAG1B,wBAAoB;AAMrB,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAgB;AAezC;;;;;;;;;;GAUG;AACH,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,yBAAyB,CAAC,SAAS,CAAC,GAC5C,UAAU,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,CA4C/C"}
@@ -1 +1 @@
1
- {"version":3,"file":"fiat-submit.d.mts","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-submit.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EACV,WAAW,EACX,yBAAyB,EAG1B,wBAAoB;AAMrB,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAgB;AAezC;;;;;;;;;;GAUG;AACH,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,yBAAyB,CAAC,SAAS,CAAC,GAC5C,UAAU,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,CA2C/C"}
1
+ {"version":3,"file":"fiat-submit.d.mts","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-submit.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EACV,WAAW,EACX,yBAAyB,EAG1B,wBAAoB;AAMrB,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAgB;AAezC;;;;;;;;;;GAUG;AACH,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,yBAAyB,CAAC,SAAS,CAAC,GAC5C,UAAU,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,CA4C/C"}
@@ -34,23 +34,24 @@ export async function submitFiatQuotes(request) {
34
34
  throw new Error('Missing wallet address for fiat submission');
35
35
  }
36
36
  const state = messenger.call('TransactionPayController:getState');
37
- const orderId = state.transactionData[transactionId]?.fiatPayment?.orderId;
37
+ const fiatPayment = state.transactionData[transactionId]?.fiatPayment;
38
+ const orderId = fiatPayment?.orderId;
38
39
  if (!orderId) {
39
40
  throw new Error('Missing order ID for fiat submission');
40
41
  }
41
- const parsedOrder = parseOrderId(orderId);
42
- if (!parsedOrder) {
43
- throw new Error(`Invalid order ID format: ${orderId}`);
42
+ const providerCode = extractProviderCode(fiatPayment?.rampsQuote?.provider);
43
+ if (!providerCode) {
44
+ throw new Error('Missing provider code for fiat submission');
44
45
  }
45
46
  log('Starting fiat order polling', {
46
47
  orderId,
47
- providerCode: parsedOrder.providerCode,
48
+ providerCode,
48
49
  transactionId,
49
50
  });
50
51
  const order = await waitForOrderCompletion({
51
52
  messenger,
52
- orderCode: parsedOrder.orderCode,
53
- providerCode: parsedOrder.providerCode,
53
+ orderCode: orderId,
54
+ providerCode,
54
55
  transactionId,
55
56
  walletAddress,
56
57
  });
@@ -62,17 +63,17 @@ export async function submitFiatQuotes(request) {
62
63
  return await submitRelayAfterFiatCompletion({ order, request });
63
64
  }
64
65
  /**
65
- * Parses a normalized order ID string into its provider and order components.
66
+ * Extracts the provider code from a ramps provider string.
66
67
  *
67
- * @param orderId - Order ID in `/providers/{providerCode}/orders/{orderCode}` format.
68
- * @returns The parsed provider and order codes, or `null` if the format is invalid.
68
+ * @param provider - Provider string (e.g. `/providers/transak-native`).
69
+ * @returns The provider code, or `null` if the format is invalid.
69
70
  */
70
- function parseOrderId(orderId) {
71
- const parts = orderId.split('/').filter(Boolean);
72
- if (parts.length < 4 || parts[0] !== 'providers' || parts[2] !== 'orders') {
71
+ function extractProviderCode(provider) {
72
+ if (!provider) {
73
73
  return null;
74
74
  }
75
- return { orderCode: parts[3], providerCode: parts[1] };
75
+ const parts = provider.split('/').filter(Boolean);
76
+ return parts.length >= 2 && parts[0] === 'providers' ? parts[1] : null;
76
77
  }
77
78
  /**
78
79
  * Converts the order's human-readable crypto amount to a raw token amount.
@@ -1 +1 @@
1
- {"version":3,"file":"fiat-submit.mjs","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-submit.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,gBAAgB,EAAE,mCAAmC;AAE9D,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AACrD,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EAAE,aAAa,EAAE,yBAAqB;AAO7C,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,8BAA0B;AACrE,OAAO,EAAE,cAAc,EAAE,kCAA8B;AACvD,OAAO,EAAE,iBAAiB,EAAE,kCAA8B;AAI1D,OAAO,EAAE,6BAA6B,EAAE,oBAAgB;AAExD,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;AAE7D,MAAM,sBAAsB,GAAG,IAAI,CAAC;AACpC,MAAM,qBAAqB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC7C,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B,MAAM,yBAAyB,GAAuB;IACpD,gBAAgB,CAAC,SAAS;IAC1B,gBAAgB,CAAC,MAAM;IACvB,gBAAgB,CAAC,SAAS;CAC3B,CAAC;AAEF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAg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ACjD,WAAW;QACX,aAAa;KACd,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import type {\n RampsOrder,\n RampsOrderCryptoCurrency,\n} from '@metamask/ramps-controller';\nimport { RampsOrderStatus } from '@metamask/ramps-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { projectLogger } from '../../logger';\nimport type {\n PayStrategy,\n PayStrategyExecuteRequest,\n QuoteRequest,\n TransactionPayControllerMessenger,\n} from '../../types';\nimport { buildCaipAssetType, getTokenInfo } from '../../utils/token';\nimport { getRelayQuotes } from '../relay/relay-quotes';\nimport { submitRelayQuotes } from '../relay/relay-submit';\nimport type { RelayQuote } from '../relay/types';\nimport type { TransactionPayFiatAsset } from './constants';\nimport type { FiatQuote } from './types';\nimport { deriveFiatAssetForFiatPayment } from './utils';\n\nconst log = createModuleLogger(projectLogger, 'fiat-submit');\n\nconst ORDER_POLL_INTERVAL_MS = 1000;\nconst ORDER_POLL_TIMEOUT_MS = 10 * 60 * 1000;\nconst MAX_SLIPPAGE_PERCENT = 5;\n\nconst TERMINAL_FAILURE_STATUSES: RampsOrderStatus[] = [\n RampsOrderStatus.Cancelled,\n RampsOrderStatus.Failed,\n RampsOrderStatus.IdExpired,\n];\n\n/**\n * Submits fiat strategy quotes by polling the on-ramp order until completion,\n * then re-quoting and submitting the relay leg with the settled crypto amount.\n *\n * @param request - Strategy execute request containing fiat quotes, messenger, and transaction metadata.\n * @param request.messenger - Controller messenger for cross-controller calls.\n * @param request.quotes - Fiat quotes to execute (exactly one expected).\n * @param request.transaction - Original transaction metadata.\n * @param request.isSmartTransaction - Callback to check smart transaction eligibility.\n * @returns An object containing the relay transaction hash if available.\n */\nexport async function submitFiatQuotes(\n request: PayStrategyExecuteRequest<FiatQuote>,\n): ReturnType<PayStrategy<FiatQuote>['execute']> {\n const { messenger, transaction } = request;\n const transactionId = transaction.id;\n const walletAddress = transaction.txParams.from as Hex | undefined;\n\n if (!walletAddress) {\n throw new Error('Missing wallet address for fiat submission');\n }\n\n const state = messenger.call('TransactionPayController:getState');\n const orderId = state.transactionData[transactionId]?.fiatPayment?.orderId;\n\n if (!orderId) {\n throw new Error('Missing order ID for fiat submission');\n }\n\n const parsedOrder = parseOrderId(orderId);\n\n if (!parsedOrder) {\n throw new Error(`Invalid order ID format: ${orderId}`);\n }\n\n log('Starting fiat order polling', {\n orderId,\n providerCode: parsedOrder.providerCode,\n transactionId,\n });\n\n const order = await waitForOrderCompletion({\n messenger,\n orderCode: parsedOrder.orderCode,\n providerCode: parsedOrder.providerCode,\n transactionId,\n walletAddress,\n });\n\n log('Fiat order completed', {\n cryptoAmount: order.cryptoAmount,\n orderId,\n transactionId,\n });\n\n return await submitRelayAfterFiatCompletion({ order, request });\n}\n\n/**\n * Parses a normalized order ID string into its provider and order components.\n *\n * @param orderId - Order ID in `/providers/{providerCode}/orders/{orderCode}` format.\n * @returns The parsed provider and order codes, or `null` if the format is invalid.\n */\nfunction parseOrderId(\n orderId: string,\n): { orderCode: string; providerCode: string } | null {\n const parts = orderId.split('/').filter(Boolean);\n\n if (parts.length < 4 || parts[0] !== 'providers' || parts[2] !== 'orders') {\n return null;\n }\n\n return { orderCode: parts[3], providerCode: parts[1] };\n}\n\n/**\n * Converts the order's human-readable crypto amount to a raw token amount.\n *\n * @param options - The conversion options.\n * @param options.cryptoAmount - Human-readable crypto amount from the completed order.\n * @param options.decimals - Token decimals for the fiat asset.\n * @returns The raw token amount as a string.\n */\nfunction getRawSourceAmountFromOrder({\n cryptoAmount,\n decimals,\n}: {\n cryptoAmount: RampsOrder['cryptoAmount'];\n decimals: number;\n}): string {\n const normalizedAmount = new BigNumber(String(cryptoAmount));\n\n if (!normalizedAmount.isFinite() || normalizedAmount.lte(0)) {\n throw new Error(\n `Invalid fiat order crypto amount: ${String(cryptoAmount)}`,\n );\n }\n\n const rawAmount = normalizedAmount\n .shiftedBy(decimals)\n .decimalPlaces(0, BigNumber.ROUND_DOWN)\n .toFixed(0);\n\n if (!new BigNumber(rawAmount).gt(0)) {\n throw new Error('Computed fiat order source amount is not positive');\n }\n\n return rawAmount;\n}\n\n/**\n * Validates that the completed order's crypto asset matches the expected fiat asset.\n *\n * @param options - The validation options.\n * @param options.expectedAsset - The expected fiat asset derived from the transaction type.\n * @param options.orderCrypto - The crypto currency information from the completed order.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nfunction validateOrderAsset({\n expectedAsset,\n orderCrypto,\n transactionId,\n}: {\n expectedAsset: TransactionPayFiatAsset;\n orderCrypto: RampsOrderCryptoCurrency | undefined;\n transactionId: string;\n}): void {\n const orderAssetId = orderCrypto?.assetId?.toLowerCase();\n const expectedAssetId = buildCaipAssetType(\n expectedAsset.chainId,\n expectedAsset.address,\n ).toLowerCase();\n const expectedChainId = expectedAssetId.split('/')[0];\n const orderChainId = orderCrypto?.chainId?.toLowerCase();\n\n if (orderAssetId && orderAssetId !== expectedAssetId) {\n throw new Error(\n `Fiat order asset mismatch for transaction ${transactionId}: ` +\n `expected ${expectedAssetId}, got ${orderAssetId}`,\n );\n }\n\n if (orderChainId && orderChainId !== expectedChainId) {\n throw new Error(\n `Fiat order chain mismatch for transaction ${transactionId}: ` +\n `expected ${expectedChainId}, got ${orderChainId}`,\n );\n }\n}\n\n/**\n * Validates that the re-quoted relay target output hasn't drifted beyond the\n * acceptable slippage threshold compared to the original quote shown to the user.\n *\n * @param options - The validation options.\n * @param options.originalTargetRaw - Raw target amount from the original relay quote.\n * @param options.reQuotedTargetRaw - Raw target amount from the re-quoted relay.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nfunction validateRelaySlippage({\n originalTargetRaw,\n reQuotedTargetRaw,\n transactionId,\n}: {\n originalTargetRaw: string;\n reQuotedTargetRaw: string;\n transactionId: string;\n}): void {\n const original = new BigNumber(originalTargetRaw);\n const reQuoted = new BigNumber(reQuotedTargetRaw);\n\n if (!original.gt(0) || !reQuoted.gt(0)) {\n return;\n }\n\n const slippagePercent = original\n .minus(reQuoted)\n .dividedBy(original)\n .multipliedBy(100);\n\n log('Relay slippage check', {\n originalTargetRaw,\n reQuotedTargetRaw,\n slippagePercent: slippagePercent.toFixed(2),\n transactionId,\n });\n\n if (slippagePercent.gt(MAX_SLIPPAGE_PERCENT)) {\n throw new Error(\n `Relay re-quote slippage too high for transaction ` +\n `${slippagePercent.toFixed(2)}% exceeds ${MAX_SLIPPAGE_PERCENT}% max`,\n );\n }\n}\n\n/**\n * Polls the on-ramp order until it reaches a terminal status.\n *\n * @param options - The polling options.\n * @param options.messenger - Controller messenger for calling `RampsController:getOrder`.\n * @param options.orderCode - The order identifier within the provider.\n * @param options.providerCode - The on-ramp provider code (e.g. \"transak\").\n * @param options.transactionId - Transaction ID for logging.\n * @param options.walletAddress - Wallet address associated with the order.\n * @returns The completed order data.\n */\nasync function waitForOrderCompletion({\n messenger,\n orderCode,\n providerCode,\n transactionId,\n walletAddress,\n}: {\n messenger: TransactionPayControllerMessenger;\n orderCode: string;\n providerCode: string;\n transactionId: string;\n walletAddress: string;\n}): Promise<RampsOrder> {\n const startTime = Date.now();\n let lastStatus: string | undefined;\n\n while (true) {\n let order: RampsOrder | undefined;\n\n try {\n order = await messenger.call(\n 'RampsController:getOrder',\n providerCode,\n orderCode,\n walletAddress,\n );\n } catch (error) {\n log('Order polling network error', error);\n }\n\n if (order) {\n lastStatus = order.status;\n\n log('Polled fiat order', {\n orderStatus: order.status,\n providerCode,\n transactionId,\n });\n\n if (order.status === RampsOrderStatus.Completed) {\n return order;\n }\n\n if (TERMINAL_FAILURE_STATUSES.includes(order.status)) {\n throw new Error(`Fiat order ${order.status.toLowerCase()}`);\n }\n }\n\n if (Date.now() - startTime >= ORDER_POLL_TIMEOUT_MS) {\n throw new Error(\n `Fiat order polling timed out (last status: ${lastStatus})`,\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, ORDER_POLL_INTERVAL_MS));\n }\n}\n\n/**\n * Re-quotes and submits the relay leg using the settled amount from a completed fiat order.\n *\n * @param options - The submission options.\n * @param options.order - The completed on-ramp order containing the settled crypto amount.\n * @param options.request - The original fiat strategy execute request.\n * @returns An object containing the relay transaction hash if available.\n */\nasync function submitRelayAfterFiatCompletion({\n order,\n request,\n}: {\n order: RampsOrder;\n request: PayStrategyExecuteRequest<FiatQuote>;\n}): Promise<{ transactionHash?: Hex }> {\n const { messenger, quotes, transaction } = request;\n const transactionId = transaction.id;\n\n if (!quotes.length) {\n throw new Error('Missing fiat quote for relay submission');\n }\n\n if (quotes.length > 1) {\n throw new Error('Multiple fiat quotes are not supported for submission');\n }\n\n const fiatAsset = deriveFiatAssetForFiatPayment(transaction, messenger);\n\n validateOrderAsset({\n expectedAsset: fiatAsset,\n orderCrypto: order.cryptoCurrency,\n transactionId,\n });\n\n const tokenInfo = getTokenInfo(\n messenger,\n fiatAsset.address,\n fiatAsset.chainId,\n );\n\n if (!tokenInfo) {\n throw new Error(\n `Unable to resolve token info for fiat asset ${fiatAsset.address} on chain ${fiatAsset.chainId}`,\n );\n }\n\n const sourceAmountRaw = getRawSourceAmountFromOrder({\n cryptoAmount: order.cryptoAmount,\n decimals: tokenInfo.decimals,\n });\n\n const baseRequest = quotes[0].request;\n const relayRequest: QuoteRequest = {\n ...baseRequest,\n isMaxAmount: true,\n isPostQuote: false,\n sourceBalanceRaw: sourceAmountRaw,\n sourceTokenAmount: sourceAmountRaw,\n };\n\n log('Re-quoting relay from completed fiat order', {\n completedOrderAmount: order.cryptoAmount,\n relayRequest,\n sourceAmountRaw,\n transactionId,\n });\n\n const relayQuotes = await getRelayQuotes({\n accountSupports7702: request.accountSupports7702,\n messenger,\n requests: [relayRequest],\n transaction,\n });\n\n if (!relayQuotes.length) {\n throw new Error('No relay quotes returned for completed fiat order');\n }\n\n const originalRelayQuote = quotes[0].original.relayQuote;\n validateRelaySlippage({\n originalTargetRaw: originalRelayQuote.details.currencyOut.amount,\n reQuotedTargetRaw: relayQuotes[0].original.details.currencyOut.amount,\n transactionId,\n });\n\n log('Received relay quotes for completed fiat order', {\n relayQuoteCount: relayQuotes.length,\n transactionId,\n });\n\n const relaySubmitRequest: PayStrategyExecuteRequest<RelayQuote> = {\n accountSupports7702: request.accountSupports7702,\n isSmartTransaction: request.isSmartTransaction,\n messenger,\n quotes: relayQuotes,\n transaction,\n };\n\n const relayResult = await submitRelayQuotes(relaySubmitRequest);\n\n log('Relay submission completed after fiat order', {\n relayResult,\n transactionId,\n });\n\n return relayResult;\n}\n"]}
1
+ {"version":3,"file":"fiat-submit.mjs","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-submit.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,gBAAgB,EAAE,mCAAmC;AAE9D,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AACrD,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EAAE,aAAa,EAAE,yBAAqB;AAO7C,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,8BAA0B;AACrE,OAAO,EAAE,cAAc,EAAE,kCAA8B;AACvD,OAAO,EAAE,iBAAiB,EAAE,kCAA8B;AAI1D,OAAO,EAAE,6BAA6B,EAAE,oBAAgB;AAExD,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;AAE7D,MAAM,sBAAsB,GAAG,IAAI,CAAC;AACpC,MAAM,qBAAqB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC7C,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B,MAAM,yBAAyB,GAAuB;IACpD,gBAAgB,CAAC,SAAS;IAC1B,gBAAgB,CAAC,MAAM;IACvB,gBAAgB,CAAC,SAAS;CAC3B,CAAC;AAEF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,OAA6C;IAE7C,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;IAC3C,MAAM,aAAa,GAAG,W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AAe;KACnC,CAAC;IAEF,GAAG,CAAC,4CAA4C,EAAE;QAChD,oBAAoB,EAAE,KAAK,CAAC,YAAY;QACxC,YAAY;QACZ,eAAe;QACf,aAAa;KACd,CAAC,CAAC;IAEH,MAAM,WAAW,GAAG,MAAM,cAAc,CAAC;QACvC,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;QAChD,SAAS;QACT,QAAQ,EAAE,CAAC,YAAY,CAAC;QACxB,WAAW;KACZ,CAAC,CAAC;IAEH,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;IACvE,CAAC;IAED,MAAM,kBAAkB,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC;IACzD,qBAAqB,CAAC;QACpB,iBAAiB,EAAE,kBAAkB,CAAC,OAAO,CAAC,WAAW,CAAC,MAAM;QAChE,iBAAiB,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,MAAM;QACrE,aAAa;KACd,CAAC,CAAC;IAEH,GAAG,CAAC,gDAAgD,EAAE;QACpD,eAAe,EAAE,WAAW,CAAC,MAAM;QACnC,aAAa;KACd,CAAC,CAAC;IAEH,MAAM,kBAAkB,GAA0C;QAChE,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;QAChD,kBAAkB,EAAE,OAAO,CAAC,kBAAkB;QAC9C,SAAS;QACT,MAAM,EAAE,WAAW;QACnB,WAAW;KACZ,CAAC;IAEF,MAAM,WAAW,GAAG,MAAM,iBAAiB,CAAC,kBAAkB,CAAC,CAAC;IAEhE,GAAG,CAAC,6CAA6C,EAAE;QACjD,WAAW;QACX,aAAa;KACd,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import type {\n RampsOrder,\n RampsOrderCryptoCurrency,\n} from '@metamask/ramps-controller';\nimport { RampsOrderStatus } from '@metamask/ramps-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { projectLogger } from '../../logger';\nimport type {\n PayStrategy,\n PayStrategyExecuteRequest,\n QuoteRequest,\n TransactionPayControllerMessenger,\n} from '../../types';\nimport { buildCaipAssetType, getTokenInfo } from '../../utils/token';\nimport { getRelayQuotes } from '../relay/relay-quotes';\nimport { submitRelayQuotes } from '../relay/relay-submit';\nimport type { RelayQuote } from '../relay/types';\nimport type { TransactionPayFiatAsset } from './constants';\nimport type { FiatQuote } from './types';\nimport { deriveFiatAssetForFiatPayment } from './utils';\n\nconst log = createModuleLogger(projectLogger, 'fiat-submit');\n\nconst ORDER_POLL_INTERVAL_MS = 1000;\nconst ORDER_POLL_TIMEOUT_MS = 10 * 60 * 1000;\nconst MAX_SLIPPAGE_PERCENT = 5;\n\nconst TERMINAL_FAILURE_STATUSES: RampsOrderStatus[] = [\n RampsOrderStatus.Cancelled,\n RampsOrderStatus.Failed,\n RampsOrderStatus.IdExpired,\n];\n\n/**\n * Submits fiat strategy quotes by polling the on-ramp order until completion,\n * then re-quoting and submitting the relay leg with the settled crypto amount.\n *\n * @param request - Strategy execute request containing fiat quotes, messenger, and transaction metadata.\n * @param request.messenger - Controller messenger for cross-controller calls.\n * @param request.quotes - Fiat quotes to execute (exactly one expected).\n * @param request.transaction - Original transaction metadata.\n * @param request.isSmartTransaction - Callback to check smart transaction eligibility.\n * @returns An object containing the relay transaction hash if available.\n */\nexport async function submitFiatQuotes(\n request: PayStrategyExecuteRequest<FiatQuote>,\n): ReturnType<PayStrategy<FiatQuote>['execute']> {\n const { messenger, transaction } = request;\n const transactionId = transaction.id;\n const walletAddress = transaction.txParams.from as Hex | undefined;\n\n if (!walletAddress) {\n throw new Error('Missing wallet address for fiat submission');\n }\n\n const state = messenger.call('TransactionPayController:getState');\n const fiatPayment = state.transactionData[transactionId]?.fiatPayment;\n const orderId = fiatPayment?.orderId;\n\n if (!orderId) {\n throw new Error('Missing order ID for fiat submission');\n }\n\n const providerCode = extractProviderCode(fiatPayment?.rampsQuote?.provider);\n\n if (!providerCode) {\n throw new Error('Missing provider code for fiat submission');\n }\n\n log('Starting fiat order polling', {\n orderId,\n providerCode,\n transactionId,\n });\n\n const order = await waitForOrderCompletion({\n messenger,\n orderCode: orderId,\n providerCode,\n transactionId,\n walletAddress,\n });\n\n log('Fiat order completed', {\n cryptoAmount: order.cryptoAmount,\n orderId,\n transactionId,\n });\n\n return await submitRelayAfterFiatCompletion({ order, request });\n}\n\n/**\n * Extracts the provider code from a ramps provider string.\n *\n * @param provider - Provider string (e.g. `/providers/transak-native`).\n * @returns The provider code, or `null` if the format is invalid.\n */\nfunction extractProviderCode(provider: string | undefined): string | null {\n if (!provider) {\n return null;\n }\n\n const parts = provider.split('/').filter(Boolean);\n return parts.length >= 2 && parts[0] === 'providers' ? parts[1] : null;\n}\n\n/**\n * Converts the order's human-readable crypto amount to a raw token amount.\n *\n * @param options - The conversion options.\n * @param options.cryptoAmount - Human-readable crypto amount from the completed order.\n * @param options.decimals - Token decimals for the fiat asset.\n * @returns The raw token amount as a string.\n */\nfunction getRawSourceAmountFromOrder({\n cryptoAmount,\n decimals,\n}: {\n cryptoAmount: RampsOrder['cryptoAmount'];\n decimals: number;\n}): string {\n const normalizedAmount = new BigNumber(String(cryptoAmount));\n\n if (!normalizedAmount.isFinite() || normalizedAmount.lte(0)) {\n throw new Error(\n `Invalid fiat order crypto amount: ${String(cryptoAmount)}`,\n );\n }\n\n const rawAmount = normalizedAmount\n .shiftedBy(decimals)\n .decimalPlaces(0, BigNumber.ROUND_DOWN)\n .toFixed(0);\n\n if (!new BigNumber(rawAmount).gt(0)) {\n throw new Error('Computed fiat order source amount is not positive');\n }\n\n return rawAmount;\n}\n\n/**\n * Validates that the completed order's crypto asset matches the expected fiat asset.\n *\n * @param options - The validation options.\n * @param options.expectedAsset - The expected fiat asset derived from the transaction type.\n * @param options.orderCrypto - The crypto currency information from the completed order.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nfunction validateOrderAsset({\n expectedAsset,\n orderCrypto,\n transactionId,\n}: {\n expectedAsset: TransactionPayFiatAsset;\n orderCrypto: RampsOrderCryptoCurrency | undefined;\n transactionId: string;\n}): void {\n const orderAssetId = orderCrypto?.assetId?.toLowerCase();\n const expectedAssetId = buildCaipAssetType(\n expectedAsset.chainId,\n expectedAsset.address,\n ).toLowerCase();\n const expectedChainId = expectedAssetId.split('/')[0];\n const orderChainId = orderCrypto?.chainId?.toLowerCase();\n\n if (orderAssetId && orderAssetId !== expectedAssetId) {\n throw new Error(\n `Fiat order asset mismatch for transaction ${transactionId}: ` +\n `expected ${expectedAssetId}, got ${orderAssetId}`,\n );\n }\n\n if (orderChainId && orderChainId !== expectedChainId) {\n throw new Error(\n `Fiat order chain mismatch for transaction ${transactionId}: ` +\n `expected ${expectedChainId}, got ${orderChainId}`,\n );\n }\n}\n\n/**\n * Validates that the re-quoted relay target output hasn't drifted beyond the\n * acceptable slippage threshold compared to the original quote shown to the user.\n *\n * @param options - The validation options.\n * @param options.originalTargetRaw - Raw target amount from the original relay quote.\n * @param options.reQuotedTargetRaw - Raw target amount from the re-quoted relay.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nfunction validateRelaySlippage({\n originalTargetRaw,\n reQuotedTargetRaw,\n transactionId,\n}: {\n originalTargetRaw: string;\n reQuotedTargetRaw: string;\n transactionId: string;\n}): void {\n const original = new BigNumber(originalTargetRaw);\n const reQuoted = new BigNumber(reQuotedTargetRaw);\n\n if (!original.gt(0) || !reQuoted.gt(0)) {\n return;\n }\n\n const slippagePercent = original\n .minus(reQuoted)\n .dividedBy(original)\n .multipliedBy(100);\n\n log('Relay slippage check', {\n originalTargetRaw,\n reQuotedTargetRaw,\n slippagePercent: slippagePercent.toFixed(2),\n transactionId,\n });\n\n if (slippagePercent.gt(MAX_SLIPPAGE_PERCENT)) {\n throw new Error(\n `Relay re-quote slippage too high for transaction ` +\n `${slippagePercent.toFixed(2)}% exceeds ${MAX_SLIPPAGE_PERCENT}% max`,\n );\n }\n}\n\n/**\n * Polls the on-ramp order until it reaches a terminal status.\n *\n * @param options - The polling options.\n * @param options.messenger - Controller messenger for calling `RampsController:getOrder`.\n * @param options.orderCode - The order identifier within the provider.\n * @param options.providerCode - The on-ramp provider code (e.g. \"transak\").\n * @param options.transactionId - Transaction ID for logging.\n * @param options.walletAddress - Wallet address associated with the order.\n * @returns The completed order data.\n */\nasync function waitForOrderCompletion({\n messenger,\n orderCode,\n providerCode,\n transactionId,\n walletAddress,\n}: {\n messenger: TransactionPayControllerMessenger;\n orderCode: string;\n providerCode: string;\n transactionId: string;\n walletAddress: string;\n}): Promise<RampsOrder> {\n const startTime = Date.now();\n let lastStatus: string | undefined;\n\n while (true) {\n let order: RampsOrder | undefined;\n\n try {\n order = await messenger.call(\n 'RampsController:getOrder',\n providerCode,\n orderCode,\n walletAddress,\n );\n } catch (error) {\n log('Order polling network error', error);\n }\n\n if (order) {\n lastStatus = order.status;\n\n log('Polled fiat order', {\n orderStatus: order.status,\n providerCode,\n transactionId,\n });\n\n if (order.status === RampsOrderStatus.Completed) {\n return order;\n }\n\n if (TERMINAL_FAILURE_STATUSES.includes(order.status)) {\n throw new Error(`Fiat order ${order.status.toLowerCase()}`);\n }\n }\n\n if (Date.now() - startTime >= ORDER_POLL_TIMEOUT_MS) {\n throw new Error(\n `Fiat order polling timed out (last status: ${lastStatus})`,\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, ORDER_POLL_INTERVAL_MS));\n }\n}\n\n/**\n * Re-quotes and submits the relay leg using the settled amount from a completed fiat order.\n *\n * @param options - The submission options.\n * @param options.order - The completed on-ramp order containing the settled crypto amount.\n * @param options.request - The original fiat strategy execute request.\n * @returns An object containing the relay transaction hash if available.\n */\nasync function submitRelayAfterFiatCompletion({\n order,\n request,\n}: {\n order: RampsOrder;\n request: PayStrategyExecuteRequest<FiatQuote>;\n}): Promise<{ transactionHash?: Hex }> {\n const { messenger, quotes, transaction } = request;\n const transactionId = transaction.id;\n\n if (!quotes.length) {\n throw new Error('Missing fiat quote for relay submission');\n }\n\n if (quotes.length > 1) {\n throw new Error('Multiple fiat quotes are not supported for submission');\n }\n\n const fiatAsset = deriveFiatAssetForFiatPayment(transaction, messenger);\n\n validateOrderAsset({\n expectedAsset: fiatAsset,\n orderCrypto: order.cryptoCurrency,\n transactionId,\n });\n\n const tokenInfo = getTokenInfo(\n messenger,\n fiatAsset.address,\n fiatAsset.chainId,\n );\n\n if (!tokenInfo) {\n throw new Error(\n `Unable to resolve token info for fiat asset ${fiatAsset.address} on chain ${fiatAsset.chainId}`,\n );\n }\n\n const sourceAmountRaw = getRawSourceAmountFromOrder({\n cryptoAmount: order.cryptoAmount,\n decimals: tokenInfo.decimals,\n });\n\n const baseRequest = quotes[0].request;\n const relayRequest: QuoteRequest = {\n ...baseRequest,\n isMaxAmount: true,\n isPostQuote: false,\n sourceBalanceRaw: sourceAmountRaw,\n sourceTokenAmount: sourceAmountRaw,\n };\n\n log('Re-quoting relay from completed fiat order', {\n completedOrderAmount: order.cryptoAmount,\n relayRequest,\n sourceAmountRaw,\n transactionId,\n });\n\n const relayQuotes = await getRelayQuotes({\n accountSupports7702: request.accountSupports7702,\n messenger,\n requests: [relayRequest],\n transaction,\n });\n\n if (!relayQuotes.length) {\n throw new Error('No relay quotes returned for completed fiat order');\n }\n\n const originalRelayQuote = quotes[0].original.relayQuote;\n validateRelaySlippage({\n originalTargetRaw: originalRelayQuote.details.currencyOut.amount,\n reQuotedTargetRaw: relayQuotes[0].original.details.currencyOut.amount,\n transactionId,\n });\n\n log('Received relay quotes for completed fiat order', {\n relayQuoteCount: relayQuotes.length,\n transactionId,\n });\n\n const relaySubmitRequest: PayStrategyExecuteRequest<RelayQuote> = {\n accountSupports7702: request.accountSupports7702,\n isSmartTransaction: request.isSmartTransaction,\n messenger,\n quotes: relayQuotes,\n transaction,\n };\n\n const relayResult = await submitRelayQuotes(relaySubmitRequest);\n\n log('Relay submission completed after fiat order', {\n relayResult,\n transactionId,\n });\n\n return relayResult;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.cjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAwKA;;;GAGG;AACU,QAAA,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type {\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n CurrencyRateStateChange,\n TokenBalancesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type { TokenRatesControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { TokenRatesControllerStateChangeEvent } from '@metamask/assets-controllers';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n} from '@metamask/assets-controllers';\nimport type { AccountTrackerControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { BridgeControllerFetchQuotesAction } from '@metamask/bridge-controller';\nimport type { BridgeStatusControllerStateChangeEvent } from '@metamask/bridge-status-controller';\nimport type {\n BridgeStatusControllerGetStateAction,\n BridgeStatusControllerSubmitTxAction,\n} from '@metamask/bridge-status-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuotesAction,\n RampsControllerGetStateAction,\n RampsControllerSetSelectedTokenAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n 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 { CONTROLLER_NAME, TransactionPayStrategy } from './constants';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types';\n\nexport type AllowedActions =\n | AccountTrackerControllerGetStateAction\n | AssetsControllerGetStateForTransactionPayAction\n | BridgeControllerFetchQuotesAction\n | BridgeStatusControllerGetStateAction\n | BridgeStatusControllerSubmitTxAction\n | CurrencyRateControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuotesAction\n | RampsControllerGetStateAction\n | RampsControllerSetSelectedTokenAction\n | RemoteFeatureFlagControllerGetStateAction\n | TokenBalancesControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | TokensControllerGetStateAction\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | BridgeStatusControllerStateChangeEvent\n | CurrencyRateStateChange\n | TokenRatesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * 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 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 /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay 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 * 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/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** 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 /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /** 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 /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay quote\n * request.\n */\n refundTo?: Hex;\n\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 * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay quote\n * request.\n */\n refundTo?: Hex;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n}: {\n transaction: TransactionMeta;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** 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.cjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAwKA;;;GAGG;AACU,QAAA,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type {\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n CurrencyRateStateChange,\n TokenBalancesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type { TokenRatesControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { TokenRatesControllerStateChangeEvent } from '@metamask/assets-controllers';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n} from '@metamask/assets-controllers';\nimport type { AccountTrackerControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { BridgeControllerFetchQuotesAction } from '@metamask/bridge-controller';\nimport type { BridgeStatusControllerStateChangeEvent } from '@metamask/bridge-status-controller';\nimport type {\n BridgeStatusControllerGetStateAction,\n BridgeStatusControllerSubmitTxAction,\n} from '@metamask/bridge-status-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuotesAction,\n RampsControllerGetStateAction,\n RampsControllerSetSelectedTokenAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n 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 { CONTROLLER_NAME, TransactionPayStrategy } from './constants';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types';\n\nexport type AllowedActions =\n | AccountTrackerControllerGetStateAction\n | AssetsControllerGetStateForTransactionPayAction\n | BridgeControllerFetchQuotesAction\n | BridgeStatusControllerGetStateAction\n | BridgeStatusControllerSubmitTxAction\n | CurrencyRateControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuotesAction\n | RampsControllerGetStateAction\n | RampsControllerSetSelectedTokenAction\n | RemoteFeatureFlagControllerGetStateAction\n | TokenBalancesControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | TokensControllerGetStateAction\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | BridgeStatusControllerStateChangeEvent\n | CurrencyRateStateChange\n | TokenRatesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * 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 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 /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay 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 * 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/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** 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 /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /** 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 /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay quote\n * request.\n */\n refundTo?: Hex;\n\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 * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */\n caipAssetId?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay quote\n * request.\n */\n refundTo?: Hex;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n}: {\n transaction: TransactionMeta;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** 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"]}
package/dist/types.d.cts CHANGED
@@ -139,6 +139,8 @@ export type TransactionData = {
139
139
  export type TransactionFiatPayment = {
140
140
  /** Entered fiat amount for the selected payment method. */
141
141
  amountFiat?: string;
142
+ /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */
143
+ caipAssetId?: string;
142
144
  /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */
143
145
  orderId?: string;
144
146
  /** The ramps quote received from the ramps provider. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,+CAA+C,EAC/C,gCAAgC,EACjC,oCAAoC;AACrC,OAAO,KAAK,EACV,oCAAoC,EACpC,uBAAuB,EACvB,qCAAqC,EACtC,qCAAqC;AACtC,OAAO,KAAK,EAAE,kCAAkC,EAAE,qCAAqC;AACvF,OAAO,KAAK,EAAE,oCAAoC,EAAE,qCAAqC;AACzF,OAAO,KAAK,EACV,8BAA8B,EAC9B,gCAAgC,EACjC,qCAAqC;AACtC,OAAO,KAAK,EAAE,sCAAsC,EAAE,qCAAqC;AAC3F,OAAO,KAAK,EAAE,0BAA0B,E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AAM,MAAM,wBAAwB,GAAG;IACrC,uCAAuC;IACvC,aAAa,EAAE,MAAM,CAAC;IAEtB,6CAA6C;IAC7C,QAAQ,EAAE,8BAA8B,CAAC;CAC1C,CAAC;AAEF,gEAAgE;AAChE,MAAM,MAAM,gCAAgC,GAAG,CAAC,EAC9C,WAAW,GACZ,EAAE;IACD,WAAW,EAAE,eAAe,CAAC;CAC9B,KAAK,OAAO,CAAC;IACZ,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,IAAI,EAAE,GAAG,CAAC;IACV,EAAE,EAAE,GAAG,CAAC;IACR,KAAK,EAAE,GAAG,CAAC;CACZ,CAAC,CAAC;AAEH,0CAA0C;AAC1C,MAAM,MAAM,MAAM,GAAG,SAAS,GAAG;IAC/B,gEAAgE;IAChE,KAAK,EAAE,MAAM,CAAC;IAEd,gEAAgE;IAChE,GAAG,EAAE,MAAM,CAAC;CACb,CAAC"}
package/dist/types.d.mts CHANGED
@@ -139,6 +139,8 @@ export type TransactionData = {
139
139
  export type TransactionFiatPayment = {
140
140
  /** Entered fiat amount for the selected payment method. */
141
141
  amountFiat?: string;
142
+ /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */
143
+ caipAssetId?: string;
142
144
  /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */
143
145
  orderId?: string;
144
146
  /** The ramps quote received from the ramps provider. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,+CAA+C,EAC/C,gCAAgC,EACjC,oCAAoC;AACrC,OAAO,KAAK,EACV,oCAAoC,EACpC,uBAAuB,EACvB,qCAAqC,EACtC,qCAAqC;AACtC,OAAO,KAAK,EAAE,kCAAkC,EAAE,qCAAqC;AACvF,OAAO,KAAK,EAAE,oCAAoC,EAAE,qCAAqC;AACzF,OAAO,KAAK,EACV,8BAA8B,EAC9B,gCAAgC,EACjC,qCAAqC;AACtC,OAAO,KA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yC;IACzC,OAAO,EAAE,GAAG,CAAC;CACd,CAAC;AAEF,8DAA8D;AAC9D,MAAM,MAAM,wBAAwB,GAAG;IACrC,uCAAuC;IACvC,aAAa,EAAE,MAAM,CAAC;IAEtB,6CAA6C;IAC7C,QAAQ,EAAE,8BAA8B,CAAC;CAC1C,CAAC;AAEF,gEAAgE;AAChE,MAAM,MAAM,gCAAgC,GAAG,CAAC,EAC9C,WAAW,GACZ,EAAE;IACD,WAAW,EAAE,eAAe,CAAC;CAC9B,KAAK,OAAO,CAAC;IACZ,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,IAAI,EAAE,GAAG,CAAC;IACV,EAAE,EAAE,GAAG,CAAC;IACR,KAAK,EAAE,GAAG,CAAC;CACZ,CAAC,CAAC;AAEH,0CAA0C;AAC1C,MAAM,MAAM,MAAM,GAAG,SAAS,GAAG;IAC/B,gEAAgE;IAChE,KAAK,EAAE,MAAM,CAAC;IAEd,gEAAgE;IAChE,GAAG,EAAE,MAAM,CAAC;CACb,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAwKA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type {\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n CurrencyRateStateChange,\n TokenBalancesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type { TokenRatesControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { TokenRatesControllerStateChangeEvent } from '@metamask/assets-controllers';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n} from '@metamask/assets-controllers';\nimport type { AccountTrackerControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { BridgeControllerFetchQuotesAction } from '@metamask/bridge-controller';\nimport type { BridgeStatusControllerStateChangeEvent } from '@metamask/bridge-status-controller';\nimport type {\n BridgeStatusControllerGetStateAction,\n BridgeStatusControllerSubmitTxAction,\n} from '@metamask/bridge-status-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuotesAction,\n RampsControllerGetStateAction,\n RampsControllerSetSelectedTokenAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n 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 { CONTROLLER_NAME, TransactionPayStrategy } from './constants';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types';\n\nexport type AllowedActions =\n | AccountTrackerControllerGetStateAction\n | AssetsControllerGetStateForTransactionPayAction\n | BridgeControllerFetchQuotesAction\n | BridgeStatusControllerGetStateAction\n | BridgeStatusControllerSubmitTxAction\n | CurrencyRateControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuotesAction\n | RampsControllerGetStateAction\n | RampsControllerSetSelectedTokenAction\n | RemoteFeatureFlagControllerGetStateAction\n | TokenBalancesControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | TokensControllerGetStateAction\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | BridgeStatusControllerStateChangeEvent\n | CurrencyRateStateChange\n | TokenRatesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * 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 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 /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay 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 * 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/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** 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 /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /** 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 /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay quote\n * request.\n */\n refundTo?: Hex;\n\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 * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay quote\n * request.\n */\n refundTo?: Hex;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n}: {\n transaction: TransactionMeta;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** Single amount in alternate formats. */\nexport type Amount = FiatValue & {\n /** Amount in human-readable format factoring token decimals. */\n human: string;\n\n /** Amount in atomic format without factoring token decimals. */\n raw: string;\n};\n"]}
1
+ {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAwKA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type {\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n CurrencyRateStateChange,\n TokenBalancesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type { TokenRatesControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { TokenRatesControllerStateChangeEvent } from '@metamask/assets-controllers';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n} from '@metamask/assets-controllers';\nimport type { AccountTrackerControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { BridgeControllerFetchQuotesAction } from '@metamask/bridge-controller';\nimport type { BridgeStatusControllerStateChangeEvent } from '@metamask/bridge-status-controller';\nimport type {\n BridgeStatusControllerGetStateAction,\n BridgeStatusControllerSubmitTxAction,\n} from '@metamask/bridge-status-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuotesAction,\n RampsControllerGetStateAction,\n RampsControllerSetSelectedTokenAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n 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 { CONTROLLER_NAME, TransactionPayStrategy } from './constants';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types';\n\nexport type AllowedActions =\n | AccountTrackerControllerGetStateAction\n | AssetsControllerGetStateForTransactionPayAction\n | BridgeControllerFetchQuotesAction\n | BridgeStatusControllerGetStateAction\n | BridgeStatusControllerSubmitTxAction\n | CurrencyRateControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuotesAction\n | RampsControllerGetStateAction\n | RampsControllerSetSelectedTokenAction\n | RemoteFeatureFlagControllerGetStateAction\n | TokenBalancesControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | TokensControllerGetStateAction\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | BridgeStatusControllerStateChangeEvent\n | CurrencyRateStateChange\n | TokenRatesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * 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 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 /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay 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 * 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/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** 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 /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /** 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 /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay quote\n * request.\n */\n refundTo?: Hex;\n\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 * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */\n caipAssetId?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /**\n * Optional address to receive refunds if the Relay transaction fails.\n * When set, overrides the default refund recipient (EOA) in the Relay quote\n * request.\n */\n refundTo?: Hex;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n}: {\n transaction: TransactionMeta;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** 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"]}
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.calculateTotals = void 0;
4
4
  const bignumber_js_1 = require("bignumber.js");
5
+ const constants_1 = require("../constants.cjs");
5
6
  const amounts_1 = require("./amounts.cjs");
6
7
  const gas_1 = require("./gas.cjs");
7
8
  /**
@@ -19,6 +20,7 @@ function calculateTotals({ isMaxAmount, quotes, messenger, tokens, transaction,
19
20
  const metaMaskFee = sumFiat(quotes.map((quote) => quote.fees.metaMask));
20
21
  const providerFee = sumFiat(quotes.map((quote) => quote.fees.provider));
21
22
  const providerFiatFee = sumFiat(quotes.map((quote) => quote.fees.providerFiat ?? { fiat: '0', usd: '0' }));
23
+ const hasFiatStrategy = quotes.some((quote) => quote.strategy === constants_1.TransactionPayStrategy.Fiat);
22
24
  const sourceNetworkFeeMax = (0, amounts_1.sumAmounts)(quotes.map((quote) => quote.fees.sourceNetwork.max));
23
25
  const sourceNetworkFeeEstimate = (0, amounts_1.sumAmounts)(quotes.map((quote) => quote.fees.sourceNetwork.estimate));
24
26
  const transactionNetworkFee = (0, gas_1.calculateTransactionGasCost)(transaction, messenger);
@@ -38,13 +40,17 @@ function calculateTotals({ isMaxAmount, quotes, messenger, tokens, transaction,
38
40
  .plus(metaMaskFee.fiat)
39
41
  .plus(sourceNetworkFeeEstimate.fiat)
40
42
  .plus(targetNetworkFee.fiat)
41
- .plus(isMaxAmount && hasQuotes ? targetAmount.fiat : amountFiat)
43
+ .plus((hasFiatStrategy || isMaxAmount) && hasQuotes
44
+ ? targetAmount.fiat
45
+ : amountFiat)
42
46
  .toString(10);
43
47
  const totalUsd = new bignumber_js_1.BigNumber(providerFee.usd)
44
48
  .plus(metaMaskFee.usd)
45
49
  .plus(sourceNetworkFeeEstimate.usd)
46
50
  .plus(targetNetworkFee.usd)
47
- .plus(isMaxAmount && hasQuotes ? targetAmount.usd : amountUsd)
51
+ .plus((hasFiatStrategy || isMaxAmount) && hasQuotes
52
+ ? targetAmount.usd
53
+ : amountUsd)
48
54
  .toString(10);
49
55
  const estimatedDuration = Number(sumProperty(quotes, (quote) => quote.estimatedDuration));
50
56
  const isSourceGasFeeToken = quotes.some((quote) => quote.fees.isSourceGasFeeToken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,GAAG,WAAW,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAClD,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;AACvB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAClB,IAAgB,EAChB,WAAgD;IAEhD,OAAO,IAAI;SACR,GAAG,CAAC,WAAW,CAAC;SAChB,MAAM,CAAY,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,IAAI,wBAAS,CAAC,CAAC,CAAC,CAAC;SACxE,QAAQ,CAAC,EAAE,CAAC,CAAC;AAClB,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport { BigNumber } from 'bignumber.js';\n\nimport type {\n FiatValue,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPayTotals,\n} from '../types';\nimport { sumAmounts } from './amounts';\nimport { calculateTransactionGasCost } from './gas';\n\n/**\n * Calculate totals for a list of quotes and tokens.\n *\n * @param request - Request parameters.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.quotes - List of bridge quotes.\n * @param request.messenger - Controller messenger.\n * @param request.tokens - List of required tokens.\n * @param request.transaction - Transaction metadata.\n * @returns The calculated totals in USD and fiat currency.\n */\nexport function calculateTotals({\n isMaxAmount,\n quotes,\n messenger,\n tokens,\n transaction,\n}: {\n isMaxAmount?: boolean;\n quotes: TransactionPayQuote<unknown>[];\n messenger: TransactionPayControllerMessenger;\n tokens: TransactionPayRequiredToken[];\n transaction: TransactionMeta;\n}): TransactionPayTotals {\n const metaMaskFee = sumFiat(quotes.map((quote) => quote.fees.metaMask));\n const providerFee = sumFiat(quotes.map((quote) => quote.fees.provider));\n const providerFiatFee = sumFiat(\n quotes.map((quote) => quote.fees.providerFiat ?? { fiat: '0', usd: '0' }),\n );\n\n const sourceNetworkFeeMax = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.max),\n );\n\n const sourceNetworkFeeEstimate = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.estimate),\n );\n\n const transactionNetworkFee = calculateTransactionGasCost(\n transaction,\n messenger,\n );\n\n const targetNetworkFee = quotes?.length\n ? {\n ...sumFiat(quotes.map((quote) => quote.fees.targetNetwork)),\n isGasFeeToken: false,\n }\n : transactionNetworkFee;\n\n const sourceAmount = sumAmounts(quotes.map((quote) => quote.sourceAmount));\n const targetAmount = sumFiat(quotes.map((quote) => quote.targetAmount));\n\n const quoteTokens = tokens.filter(\n (singleToken) => !singleToken.skipIfBalance,\n );\n\n const amountFiat = sumProperty(quoteTokens, (token) => token.amountFiat);\n const amountUsd = sumProperty(quoteTokens, (token) => token.amountUsd);\n const hasQuotes = quotes.length > 0;\n\n const totalFiat = new BigNumber(providerFee.fiat)\n .plus(metaMaskFee.fiat)\n .plus(sourceNetworkFeeEstimate.fiat)\n .plus(targetNetworkFee.fiat)\n .plus(isMaxAmount && hasQuotes ? targetAmount.fiat : amountFiat)\n .toString(10);\n\n const totalUsd = new BigNumber(providerFee.usd)\n .plus(metaMaskFee.usd)\n .plus(sourceNetworkFeeEstimate.usd)\n .plus(targetNetworkFee.usd)\n .plus(isMaxAmount && hasQuotes ? targetAmount.usd : amountUsd)\n .toString(10);\n\n const estimatedDuration = Number(\n sumProperty(quotes, (quote) => quote.estimatedDuration),\n );\n\n const isSourceGasFeeToken = quotes.some(\n (quote) => quote.fees.isSourceGasFeeToken,\n );\n\n const isTargetGasFeeToken =\n Boolean(targetNetworkFee.isGasFeeToken) ||\n quotes.some((quote) => quote.fees.isTargetGasFeeToken);\n\n return {\n estimatedDuration,\n fees: {\n isSourceGasFeeToken,\n isTargetGasFeeToken,\n providerFiat: providerFiatFee,\n metaMask: metaMaskFee,\n provider: providerFee,\n sourceNetwork: {\n estimate: sourceNetworkFeeEstimate,\n max: sourceNetworkFeeMax,\n },\n targetNetwork: targetNetworkFee,\n },\n sourceAmount,\n targetAmount,\n total: {\n fiat: totalFiat,\n usd: totalUsd,\n },\n };\n}\n\n/**\n * Sum a list of fiat value.\n *\n * @param data - List of fiat values.\n * @returns Total fiat value.\n */\nfunction sumFiat(data: FiatValue[]): FiatValue {\n const fiat = sumProperty(data, (item) => item.fiat);\n const usd = sumProperty(data, (item) => item.usd);\n return { fiat, usd };\n}\n\n/**\n * Sum a specific property from a list of items.\n *\n * @param data - List of items.\n * @param getProperty - Function to extract the property to sum from each item.\n * @returns The summed value as a string.\n */\nfunction sumProperty<DataType>(\n data: DataType[],\n getProperty: (item: DataType) => BigNumber.Value,\n): string {\n return data\n .map(getProperty)\n .reduce<BigNumber>((total, value) => total.plus(value), new BigNumber(0))\n .toString(10);\n}\n"]}
1
+ {"version":3,"file":"totals.cjs","sourceRoot":"","sources":["../../src/utils/totals.ts"],"names":[],"mappings":";;;AACA,+CAAyC;AAEzC,gDAAsD;AAQtD,2CAAuC;AACvC,mCAAoD;AAEpD;;;;;;;;;;GAUG;AACH,SAAgB,eAAe,CAAC,EAC9B,WAAW,EACX,MAAM,EACN,SAAS,EACT,MAAM,EACN,WAAW,GAOZ;IACC,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IACxE,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IACxE,MAAM,eAAe,GAAG,OAAO,CAC7B,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,YAAY,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAC1E,CAAC;IACF,MAAM,eAAe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AAC;QACvC,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IAEzD,OAAO;QACL,iBAAiB;QACjB,IAAI,EAAE;YACJ,mBAAmB;YACnB,mBAAmB;YACnB,YAAY,EAAE,eAAe;YAC7B,QAAQ,EAAE,WAAW;YACrB,QAAQ,EAAE,WAAW;YACrB,aAAa,EAAE;gBACb,QAAQ,EAAE,wBAAwB;gBAClC,GAAG,EAAE,mBAAmB;aACzB;YACD,aAAa,EAAE,gBAAgB;SAChC;QACD,YAAY;QACZ,YAAY;QACZ,KAAK,EAAE;YACL,IAAI,EAAE,SAAS;YACf,GAAG,EAAE,QAAQ;SACd;KACF,CAAC;AACJ,CAAC;AA5GD,0CA4GC;AAED;;;;;GAKG;AACH,SAAS,OAAO,CAAC,IAAiB;IAChC,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpD,MAAM,GAAG,GAAG,WAAW,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAClD,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;AACvB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAClB,IAAgB,EAChB,WAAgD;IAEhD,OAAO,IAAI;SACR,GAAG,CAAC,WAAW,CAAC;SAChB,MAAM,CAAY,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,IAAI,wBAAS,CAAC,CAAC,CAAC,CAAC;SACxE,QAAQ,CAAC,EAAE,CAAC,CAAC;AAClB,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport { BigNumber } from 'bignumber.js';\n\nimport { TransactionPayStrategy } from '../constants';\nimport type {\n FiatValue,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPayTotals,\n} from '../types';\nimport { sumAmounts } from './amounts';\nimport { calculateTransactionGasCost } from './gas';\n\n/**\n * Calculate totals for a list of quotes and tokens.\n *\n * @param request - Request parameters.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.quotes - List of bridge quotes.\n * @param request.messenger - Controller messenger.\n * @param request.tokens - List of required tokens.\n * @param request.transaction - Transaction metadata.\n * @returns The calculated totals in USD and fiat currency.\n */\nexport function calculateTotals({\n isMaxAmount,\n quotes,\n messenger,\n tokens,\n transaction,\n}: {\n isMaxAmount?: boolean;\n quotes: TransactionPayQuote<unknown>[];\n messenger: TransactionPayControllerMessenger;\n tokens: TransactionPayRequiredToken[];\n transaction: TransactionMeta;\n}): TransactionPayTotals {\n const metaMaskFee = sumFiat(quotes.map((quote) => quote.fees.metaMask));\n const providerFee = sumFiat(quotes.map((quote) => quote.fees.provider));\n const providerFiatFee = sumFiat(\n quotes.map((quote) => quote.fees.providerFiat ?? { fiat: '0', usd: '0' }),\n );\n const hasFiatStrategy = quotes.some(\n (quote) => quote.strategy === TransactionPayStrategy.Fiat,\n );\n\n const sourceNetworkFeeMax = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.max),\n );\n\n const sourceNetworkFeeEstimate = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.estimate),\n );\n\n const transactionNetworkFee = calculateTransactionGasCost(\n transaction,\n messenger,\n );\n\n const targetNetworkFee = quotes?.length\n ? {\n ...sumFiat(quotes.map((quote) => quote.fees.targetNetwork)),\n isGasFeeToken: false,\n }\n : transactionNetworkFee;\n\n const sourceAmount = sumAmounts(quotes.map((quote) => quote.sourceAmount));\n const targetAmount = sumFiat(quotes.map((quote) => quote.targetAmount));\n\n const quoteTokens = tokens.filter(\n (singleToken) => !singleToken.skipIfBalance,\n );\n\n const amountFiat = sumProperty(quoteTokens, (token) => token.amountFiat);\n const amountUsd = sumProperty(quoteTokens, (token) => token.amountUsd);\n const hasQuotes = quotes.length > 0;\n\n const totalFiat = new BigNumber(providerFee.fiat)\n .plus(metaMaskFee.fiat)\n .plus(sourceNetworkFeeEstimate.fiat)\n .plus(targetNetworkFee.fiat)\n .plus(\n (hasFiatStrategy || isMaxAmount) && hasQuotes\n ? targetAmount.fiat\n : amountFiat,\n )\n .toString(10);\n\n const totalUsd = new BigNumber(providerFee.usd)\n .plus(metaMaskFee.usd)\n .plus(sourceNetworkFeeEstimate.usd)\n .plus(targetNetworkFee.usd)\n .plus(\n (hasFiatStrategy || isMaxAmount) && hasQuotes\n ? targetAmount.usd\n : amountUsd,\n )\n .toString(10);\n\n const estimatedDuration = Number(\n sumProperty(quotes, (quote) => quote.estimatedDuration),\n );\n\n const isSourceGasFeeToken = quotes.some(\n (quote) => quote.fees.isSourceGasFeeToken,\n );\n\n const isTargetGasFeeToken =\n Boolean(targetNetworkFee.isGasFeeToken) ||\n quotes.some((quote) => quote.fees.isTargetGasFeeToken);\n\n return {\n estimatedDuration,\n fees: {\n isSourceGasFeeToken,\n isTargetGasFeeToken,\n providerFiat: providerFiatFee,\n metaMask: metaMaskFee,\n provider: providerFee,\n sourceNetwork: {\n estimate: sourceNetworkFeeEstimate,\n max: sourceNetworkFeeMax,\n },\n targetNetwork: targetNetworkFee,\n },\n sourceAmount,\n targetAmount,\n total: {\n fiat: totalFiat,\n usd: totalUsd,\n },\n };\n}\n\n/**\n * Sum a list of fiat value.\n *\n * @param data - List of fiat values.\n * @returns Total fiat value.\n */\nfunction sumFiat(data: FiatValue[]): FiatValue {\n const fiat = sumProperty(data, (item) => item.fiat);\n const usd = sumProperty(data, (item) => item.usd);\n return { fiat, usd };\n}\n\n/**\n * Sum a specific property from a list of items.\n *\n * @param data - List of items.\n * @param getProperty - Function to extract the property to sum from each item.\n * @returns The summed value as a string.\n */\nfunction sumProperty<DataType>(\n data: DataType[],\n getProperty: (item: DataType) => BigNumber.Value,\n): string {\n return data\n .map(getProperty)\n .reduce<BigNumber>((total, value) => total.plus(value), new BigNumber(0))\n .toString(10);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"totals.d.cts","sourceRoot":"","sources":["../../src/utils/totals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AAGxE,OAAO,KAAK,EAEV,iCAAiC,EACjC,mBAAmB,EACnB,2BAA2B,EAC3B,oBAAoB,EACrB,qBAAiB;AAIlB;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,EAC9B,WAAW,EACX,MAAM,EACN,SAAS,EACT,MAAM,EACN,WAAW,GACZ,EAAE;IACD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,MAAM,EAAE,mBAAmB,CAAC,OAAO,CAAC,EAAE,CAAC;IACvC,SAAS,EAAE,iCAAiC,CAAC;IAC7C,MAAM,EAAE,2BAA2B,EAAE,CAAC;IACtC,WAAW,EAAE,eAAe,CAAC;CAC9B,GAAG,oBAAoB,CAqFvB"}
1
+ {"version":3,"file":"totals.d.cts","sourceRoot":"","sources":["../../src/utils/totals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AAIxE,OAAO,KAAK,EAEV,iCAAiC,EACjC,mBAAmB,EACnB,2BAA2B,EAC3B,oBAAoB,EACrB,qBAAiB;AAIlB;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,EAC9B,WAAW,EACX,MAAM,EACN,SAAS,EACT,MAAM,EACN,WAAW,GACZ,EAAE;IACD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,MAAM,EAAE,mBAAmB,CAAC,OAAO,CAAC,EAAE,CAAC;IACvC,SAAS,EAAE,iCAAiC,CAAC;IAC7C,MAAM,EAAE,2BAA2B,EAAE,CAAC;IACtC,WAAW,EAAE,eAAe,CAAC;CAC9B,GAAG,oBAAoB,CAgGvB"}
@@ -1 +1 @@
1
- {"version":3,"file":"totals.d.mts","sourceRoot":"","sources":["../../src/utils/totals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AAGxE,OAAO,KAAK,EAEV,iCAAiC,EACjC,mBAAmB,EACnB,2BAA2B,EAC3B,oBAAoB,EACrB,qBAAiB;AAIlB;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,EAC9B,WAAW,EACX,MAAM,EACN,SAAS,EACT,MAAM,EACN,WAAW,GACZ,EAAE;IACD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,MAAM,EAAE,mBAAmB,CAAC,OAAO,CAAC,EAAE,CAAC;IACvC,SAAS,EAAE,iCAAiC,CAAC;IAC7C,MAAM,EAAE,2BAA2B,EAAE,CAAC;IACtC,WAAW,EAAE,eAAe,CAAC;CAC9B,GAAG,oBAAoB,CAqFvB"}
1
+ {"version":3,"file":"totals.d.mts","sourceRoot":"","sources":["../../src/utils/totals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AAIxE,OAAO,KAAK,EAEV,iCAAiC,EACjC,mBAAmB,EACnB,2BAA2B,EAC3B,oBAAoB,EACrB,qBAAiB;AAIlB;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,EAC9B,WAAW,EACX,MAAM,EACN,SAAS,EACT,MAAM,EACN,WAAW,GACZ,EAAE;IACD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,MAAM,EAAE,mBAAmB,CAAC,OAAO,CAAC,EAAE,CAAC;IACvC,SAAS,EAAE,iCAAiC,CAAC;IAC7C,MAAM,EAAE,2BAA2B,EAAE,CAAC;IACtC,WAAW,EAAE,eAAe,CAAC;CAC9B,GAAG,oBAAoB,CAgGvB"}
@@ -1,4 +1,5 @@
1
1
  import { BigNumber } from "bignumber.js";
2
+ import { TransactionPayStrategy } from "../constants.mjs";
2
3
  import { sumAmounts } from "./amounts.mjs";
3
4
  import { calculateTransactionGasCost } from "./gas.mjs";
4
5
  /**
@@ -16,6 +17,7 @@ export function calculateTotals({ isMaxAmount, quotes, messenger, tokens, transa
16
17
  const metaMaskFee = sumFiat(quotes.map((quote) => quote.fees.metaMask));
17
18
  const providerFee = sumFiat(quotes.map((quote) => quote.fees.provider));
18
19
  const providerFiatFee = sumFiat(quotes.map((quote) => quote.fees.providerFiat ?? { fiat: '0', usd: '0' }));
20
+ const hasFiatStrategy = quotes.some((quote) => quote.strategy === TransactionPayStrategy.Fiat);
19
21
  const sourceNetworkFeeMax = sumAmounts(quotes.map((quote) => quote.fees.sourceNetwork.max));
20
22
  const sourceNetworkFeeEstimate = sumAmounts(quotes.map((quote) => quote.fees.sourceNetwork.estimate));
21
23
  const transactionNetworkFee = calculateTransactionGasCost(transaction, messenger);
@@ -35,13 +37,17 @@ export function calculateTotals({ isMaxAmount, quotes, messenger, tokens, transa
35
37
  .plus(metaMaskFee.fiat)
36
38
  .plus(sourceNetworkFeeEstimate.fiat)
37
39
  .plus(targetNetworkFee.fiat)
38
- .plus(isMaxAmount && hasQuotes ? targetAmount.fiat : amountFiat)
40
+ .plus((hasFiatStrategy || isMaxAmount) && hasQuotes
41
+ ? targetAmount.fiat
42
+ : amountFiat)
39
43
  .toString(10);
40
44
  const totalUsd = new BigNumber(providerFee.usd)
41
45
  .plus(metaMaskFee.usd)
42
46
  .plus(sourceNetworkFeeEstimate.usd)
43
47
  .plus(targetNetworkFee.usd)
44
- .plus(isMaxAmount && hasQuotes ? targetAmount.usd : amountUsd)
48
+ .plus((hasFiatStrategy || isMaxAmount) && hasQuotes
49
+ ? targetAmount.usd
50
+ : amountUsd)
45
51
  .toString(10);
46
52
  const estimatedDuration = Number(sumProperty(quotes, (quote) => quote.estimatedDuration));
47
53
  const isSourceGasFeeToken = quotes.some((quote) => quote.fees.isSourceGasFeeToken);
@@ -1 +1 @@
1
- {"version":3,"file":"totals.mjs","sourceRoot":"","sources":["../../src/utils/totals.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,q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AAC;IAClD,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;AACvB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAClB,IAAgB,EAChB,WAAgD;IAEhD,OAAO,IAAI;SACR,GAAG,CAAC,WAAW,CAAC;SAChB,MAAM,CAAY,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;SACxE,QAAQ,CAAC,EAAE,CAAC,CAAC;AAClB,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport { BigNumber } from 'bignumber.js';\n\nimport type {\n FiatValue,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPayTotals,\n} from '../types';\nimport { sumAmounts } from './amounts';\nimport { calculateTransactionGasCost } from './gas';\n\n/**\n * Calculate totals for a list of quotes and tokens.\n *\n * @param request - Request parameters.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.quotes - List of bridge quotes.\n * @param request.messenger - Controller messenger.\n * @param request.tokens - List of required tokens.\n * @param request.transaction - Transaction metadata.\n * @returns The calculated totals in USD and fiat currency.\n */\nexport function calculateTotals({\n isMaxAmount,\n quotes,\n messenger,\n tokens,\n transaction,\n}: {\n isMaxAmount?: boolean;\n quotes: TransactionPayQuote<unknown>[];\n messenger: TransactionPayControllerMessenger;\n tokens: TransactionPayRequiredToken[];\n transaction: TransactionMeta;\n}): TransactionPayTotals {\n const metaMaskFee = sumFiat(quotes.map((quote) => quote.fees.metaMask));\n const providerFee = sumFiat(quotes.map((quote) => quote.fees.provider));\n const providerFiatFee = sumFiat(\n quotes.map((quote) => quote.fees.providerFiat ?? { fiat: '0', usd: '0' }),\n );\n\n const sourceNetworkFeeMax = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.max),\n );\n\n const sourceNetworkFeeEstimate = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.estimate),\n );\n\n const transactionNetworkFee = calculateTransactionGasCost(\n transaction,\n messenger,\n );\n\n const targetNetworkFee = quotes?.length\n ? {\n ...sumFiat(quotes.map((quote) => quote.fees.targetNetwork)),\n isGasFeeToken: false,\n }\n : transactionNetworkFee;\n\n const sourceAmount = sumAmounts(quotes.map((quote) => quote.sourceAmount));\n const targetAmount = sumFiat(quotes.map((quote) => quote.targetAmount));\n\n const quoteTokens = tokens.filter(\n (singleToken) => !singleToken.skipIfBalance,\n );\n\n const amountFiat = sumProperty(quoteTokens, (token) => token.amountFiat);\n const amountUsd = sumProperty(quoteTokens, (token) => token.amountUsd);\n const hasQuotes = quotes.length > 0;\n\n const totalFiat = new BigNumber(providerFee.fiat)\n .plus(metaMaskFee.fiat)\n .plus(sourceNetworkFeeEstimate.fiat)\n .plus(targetNetworkFee.fiat)\n .plus(isMaxAmount && hasQuotes ? targetAmount.fiat : amountFiat)\n .toString(10);\n\n const totalUsd = new BigNumber(providerFee.usd)\n .plus(metaMaskFee.usd)\n .plus(sourceNetworkFeeEstimate.usd)\n .plus(targetNetworkFee.usd)\n .plus(isMaxAmount && hasQuotes ? targetAmount.usd : amountUsd)\n .toString(10);\n\n const estimatedDuration = Number(\n sumProperty(quotes, (quote) => quote.estimatedDuration),\n );\n\n const isSourceGasFeeToken = quotes.some(\n (quote) => quote.fees.isSourceGasFeeToken,\n );\n\n const isTargetGasFeeToken =\n Boolean(targetNetworkFee.isGasFeeToken) ||\n quotes.some((quote) => quote.fees.isTargetGasFeeToken);\n\n return {\n estimatedDuration,\n fees: {\n isSourceGasFeeToken,\n isTargetGasFeeToken,\n providerFiat: providerFiatFee,\n metaMask: metaMaskFee,\n provider: providerFee,\n sourceNetwork: {\n estimate: sourceNetworkFeeEstimate,\n max: sourceNetworkFeeMax,\n },\n targetNetwork: targetNetworkFee,\n },\n sourceAmount,\n targetAmount,\n total: {\n fiat: totalFiat,\n usd: totalUsd,\n },\n };\n}\n\n/**\n * Sum a list of fiat value.\n *\n * @param data - List of fiat values.\n * @returns Total fiat value.\n */\nfunction sumFiat(data: FiatValue[]): FiatValue {\n const fiat = sumProperty(data, (item) => item.fiat);\n const usd = sumProperty(data, (item) => item.usd);\n return { fiat, usd };\n}\n\n/**\n * Sum a specific property from a list of items.\n *\n * @param data - List of items.\n * @param getProperty - Function to extract the property to sum from each item.\n * @returns The summed value as a string.\n */\nfunction sumProperty<DataType>(\n data: DataType[],\n getProperty: (item: DataType) => BigNumber.Value,\n): string {\n return data\n .map(getProperty)\n .reduce<BigNumber>((total, value) => total.plus(value), new BigNumber(0))\n .toString(10);\n}\n"]}
1
+ {"version":3,"file":"totals.mjs","sourceRoot":"","sources":["../../src/utils/totals.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EAAE,sBAAsB,EAAE,yBAAqB;AAQtD,OAAO,EAAE,UAAU,EAAE,sBAAkB;AACvC,OAAO,EAAE,2BAA2B,EAAE,kBAAc;AAEpD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,eAAe,CAAC,EAC9B,WAAW,EACX,MAAM,EACN,SAAS,EACT,MAAM,EACN,WAAW,GAOZ;IACC,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IACxE,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IACxE,MAAM,eAAe,GAAG,OAAO,CAC7B,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,YAAY,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAC1E,CAAC;I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,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IAEzD,OAAO;QACL,iBAAiB;QACjB,IAAI,EAAE;YACJ,mBAAmB;YACnB,mBAAmB;YACnB,YAAY,EAAE,eAAe;YAC7B,QAAQ,EAAE,WAAW;YACrB,QAAQ,EAAE,WAAW;YACrB,aAAa,EAAE;gBACb,QAAQ,EAAE,wBAAwB;gBAClC,GAAG,EAAE,mBAAmB;aACzB;YACD,aAAa,EAAE,gBAAgB;SAChC;QACD,YAAY;QACZ,YAAY;QACZ,KAAK,EAAE;YACL,IAAI,EAAE,SAAS;YACf,GAAG,EAAE,QAAQ;SACd;KACF,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,OAAO,CAAC,IAAiB;IAChC,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpD,MAAM,GAAG,GAAG,WAAW,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAClD,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;AACvB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAClB,IAAgB,EAChB,WAAgD;IAEhD,OAAO,IAAI;SACR,GAAG,CAAC,WAAW,CAAC;SAChB,MAAM,CAAY,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;SACxE,QAAQ,CAAC,EAAE,CAAC,CAAC;AAClB,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport { BigNumber } from 'bignumber.js';\n\nimport { TransactionPayStrategy } from '../constants';\nimport type {\n FiatValue,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPayTotals,\n} from '../types';\nimport { sumAmounts } from './amounts';\nimport { calculateTransactionGasCost } from './gas';\n\n/**\n * Calculate totals for a list of quotes and tokens.\n *\n * @param request - Request parameters.\n * @param request.isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param request.quotes - List of bridge quotes.\n * @param request.messenger - Controller messenger.\n * @param request.tokens - List of required tokens.\n * @param request.transaction - Transaction metadata.\n * @returns The calculated totals in USD and fiat currency.\n */\nexport function calculateTotals({\n isMaxAmount,\n quotes,\n messenger,\n tokens,\n transaction,\n}: {\n isMaxAmount?: boolean;\n quotes: TransactionPayQuote<unknown>[];\n messenger: TransactionPayControllerMessenger;\n tokens: TransactionPayRequiredToken[];\n transaction: TransactionMeta;\n}): TransactionPayTotals {\n const metaMaskFee = sumFiat(quotes.map((quote) => quote.fees.metaMask));\n const providerFee = sumFiat(quotes.map((quote) => quote.fees.provider));\n const providerFiatFee = sumFiat(\n quotes.map((quote) => quote.fees.providerFiat ?? { fiat: '0', usd: '0' }),\n );\n const hasFiatStrategy = quotes.some(\n (quote) => quote.strategy === TransactionPayStrategy.Fiat,\n );\n\n const sourceNetworkFeeMax = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.max),\n );\n\n const sourceNetworkFeeEstimate = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.estimate),\n );\n\n const transactionNetworkFee = calculateTransactionGasCost(\n transaction,\n messenger,\n );\n\n const targetNetworkFee = quotes?.length\n ? {\n ...sumFiat(quotes.map((quote) => quote.fees.targetNetwork)),\n isGasFeeToken: false,\n }\n : transactionNetworkFee;\n\n const sourceAmount = sumAmounts(quotes.map((quote) => quote.sourceAmount));\n const targetAmount = sumFiat(quotes.map((quote) => quote.targetAmount));\n\n const quoteTokens = tokens.filter(\n (singleToken) => !singleToken.skipIfBalance,\n );\n\n const amountFiat = sumProperty(quoteTokens, (token) => token.amountFiat);\n const amountUsd = sumProperty(quoteTokens, (token) => token.amountUsd);\n const hasQuotes = quotes.length > 0;\n\n const totalFiat = new BigNumber(providerFee.fiat)\n .plus(metaMaskFee.fiat)\n .plus(sourceNetworkFeeEstimate.fiat)\n .plus(targetNetworkFee.fiat)\n .plus(\n (hasFiatStrategy || isMaxAmount) && hasQuotes\n ? targetAmount.fiat\n : amountFiat,\n )\n .toString(10);\n\n const totalUsd = new BigNumber(providerFee.usd)\n .plus(metaMaskFee.usd)\n .plus(sourceNetworkFeeEstimate.usd)\n .plus(targetNetworkFee.usd)\n .plus(\n (hasFiatStrategy || isMaxAmount) && hasQuotes\n ? targetAmount.usd\n : amountUsd,\n )\n .toString(10);\n\n const estimatedDuration = Number(\n sumProperty(quotes, (quote) => quote.estimatedDuration),\n );\n\n const isSourceGasFeeToken = quotes.some(\n (quote) => quote.fees.isSourceGasFeeToken,\n );\n\n const isTargetGasFeeToken =\n Boolean(targetNetworkFee.isGasFeeToken) ||\n quotes.some((quote) => quote.fees.isTargetGasFeeToken);\n\n return {\n estimatedDuration,\n fees: {\n isSourceGasFeeToken,\n isTargetGasFeeToken,\n providerFiat: providerFiatFee,\n metaMask: metaMaskFee,\n provider: providerFee,\n sourceNetwork: {\n estimate: sourceNetworkFeeEstimate,\n max: sourceNetworkFeeMax,\n },\n targetNetwork: targetNetworkFee,\n },\n sourceAmount,\n targetAmount,\n total: {\n fiat: totalFiat,\n usd: totalUsd,\n },\n };\n}\n\n/**\n * Sum a list of fiat value.\n *\n * @param data - List of fiat values.\n * @returns Total fiat value.\n */\nfunction sumFiat(data: FiatValue[]): FiatValue {\n const fiat = sumProperty(data, (item) => item.fiat);\n const usd = sumProperty(data, (item) => item.usd);\n return { fiat, usd };\n}\n\n/**\n * Sum a specific property from a list of items.\n *\n * @param data - List of items.\n * @param getProperty - Function to extract the property to sum from each item.\n * @returns The summed value as a string.\n */\nfunction sumProperty<DataType>(\n data: DataType[],\n getProperty: (item: DataType) => BigNumber.Value,\n): string {\n return data\n .map(getProperty)\n .reduce<BigNumber>((total, value) => total.plus(value), new BigNumber(0))\n .toString(10);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/transaction-pay-controller",
3
- "version": "22.1.0-preview-5e603a6c0",
3
+ "version": "22.1.0-preview-2fdaa18",
4
4
  "description": "Manages alternate payment strategies to provide required funds for transactions in MetaMask",
5
5
  "keywords": [
6
6
  "Ethereum",