@metamask-previews/transaction-pay-controller 21.1.0-preview-8f8f607 → 21.1.0-preview-2b316ced3
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 +0 -1
- package/dist/TransactionPayController.cjs +1 -2
- package/dist/TransactionPayController.cjs.map +1 -1
- package/dist/TransactionPayController.d.cts.map +1 -1
- package/dist/TransactionPayController.d.mts.map +1 -1
- package/dist/TransactionPayController.mjs +2 -3
- package/dist/TransactionPayController.mjs.map +1 -1
- package/dist/tests/messenger-mock.d.cts +1 -1
- package/dist/tests/messenger-mock.d.mts +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +4 -5
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +4 -5
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/required-tokens.cjs +2 -24
- package/dist/utils/required-tokens.cjs.map +1 -1
- package/dist/utils/required-tokens.d.cts.map +1 -1
- package/dist/utils/required-tokens.d.mts.map +1 -1
- package/dist/utils/required-tokens.mjs +2 -24
- package/dist/utils/required-tokens.mjs.map +1 -1
- package/dist/utils/transaction.cjs +4 -37
- package/dist/utils/transaction.cjs.map +1 -1
- package/dist/utils/transaction.d.cts +3 -12
- package/dist/utils/transaction.d.cts.map +1 -1
- package/dist/utils/transaction.d.mts +3 -12
- package/dist/utils/transaction.d.mts.map +1 -1
- package/dist/utils/transaction.mjs +2 -34
- package/dist/utils/transaction.mjs.map +1 -1
- package/package.json +1 -1
package/dist/types.mjs.map
CHANGED
|
@@ -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":"AA4JA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type { AssetsControllerGetStateForTransactionPayAction } from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n TokenBalancesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type { TokenRatesControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { TokensControllerGetStateAction } 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 | BridgeStatusControllerStateChangeEvent\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"]}
|
|
@@ -4,10 +4,7 @@ exports.parseRequiredTokens = void 0;
|
|
|
4
4
|
const abi_1 = require("@ethersproject/abi");
|
|
5
5
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
6
6
|
const metamask_eth_abis_1 = require("@metamask/metamask-eth-abis");
|
|
7
|
-
const utils_1 = require("@metamask/utils");
|
|
8
|
-
const logger_1 = require("../logger.cjs");
|
|
9
7
|
const token_1 = require("./token.cjs");
|
|
10
|
-
const log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'required-tokens');
|
|
11
8
|
const FOUR_BYTE_TOKEN_TRANSFER = '0xa9059cbb';
|
|
12
9
|
/**
|
|
13
10
|
* Parse required tokens from a transaction.
|
|
@@ -41,26 +38,17 @@ exports.parseRequiredTokens = parseRequiredTokens;
|
|
|
41
38
|
function getTokenTransferToken(transaction, messenger) {
|
|
42
39
|
const { data, to } = getTokenTransferData(transaction) ?? {};
|
|
43
40
|
if (!to || !data) {
|
|
44
|
-
log('No token transfer detected', {
|
|
45
|
-
transactionId: transaction.id,
|
|
46
|
-
});
|
|
47
41
|
return undefined;
|
|
48
42
|
}
|
|
49
43
|
let transferAmount;
|
|
50
|
-
let decodeError;
|
|
51
44
|
try {
|
|
52
45
|
const result = new abi_1.Interface(metamask_eth_abis_1.abiERC20).decodeFunctionData('transfer', data);
|
|
53
46
|
transferAmount = (0, controller_utils_1.toHex)(result._value);
|
|
54
47
|
}
|
|
55
|
-
catch
|
|
56
|
-
|
|
48
|
+
catch {
|
|
49
|
+
// Intentionally empty
|
|
57
50
|
}
|
|
58
51
|
if (transferAmount === undefined) {
|
|
59
|
-
log('Failed to decode transfer calldata', {
|
|
60
|
-
transactionId: transaction.id,
|
|
61
|
-
to,
|
|
62
|
-
error: decodeError,
|
|
63
|
-
});
|
|
64
52
|
return undefined;
|
|
65
53
|
}
|
|
66
54
|
return buildRequiredToken(transaction, to, transferAmount, messenger);
|
|
@@ -81,16 +69,6 @@ function buildRequiredToken(transaction, tokenAddress, amountRawHex, messenger)
|
|
|
81
69
|
const fiatRates = (0, token_1.getTokenFiatRate)(messenger, tokenAddress, chainId);
|
|
82
70
|
const tokenBalance = (0, token_1.getTokenBalance)(messenger, from, chainId, tokenAddress);
|
|
83
71
|
if (tokenDecimals === undefined || !symbol || fiatRates === undefined) {
|
|
84
|
-
log('Missing token data', {
|
|
85
|
-
transactionId: transaction.id,
|
|
86
|
-
chainId,
|
|
87
|
-
tokenAddress,
|
|
88
|
-
missing: {
|
|
89
|
-
decimals: tokenDecimals === undefined,
|
|
90
|
-
symbol: !symbol,
|
|
91
|
-
fiatRates: fiatRates === undefined,
|
|
92
|
-
},
|
|
93
|
-
});
|
|
94
72
|
return undefined;
|
|
95
73
|
}
|
|
96
74
|
const { human: balanceHuman, raw: balanceRaw, fiat: balanceFiat, usd: balanceUsd, } = (0, token_1.computeTokenAmounts)(tokenBalance, tokenDecimals, fiatRates);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"required-tokens.cjs","sourceRoot":"","sources":["../../src/utils/required-tokens.ts"],"names":[],"mappings":";;;AAAA,4CAA+C;AAC/C,iEAAmD;AACnD,mEAAuD;
|
|
1
|
+
{"version":3,"file":"required-tokens.cjs","sourceRoot":"","sources":["../../src/utils/required-tokens.ts"],"names":[],"mappings":";;;AAAA,4CAA+C;AAC/C,iEAAmD;AACnD,mEAAuD;AAQvD,uCAKiB;AAEjB,MAAM,wBAAwB,GAAG,YAAY,CAAC;AAE9C;;;;;;;;;GASG;AACH,SAAgB,mBAAmB,CACjC,WAA4B,EAC5B,SAA4C;IAE5C,MAAM,EAAE,cAAc,EAAE,GAAG,WAAW,CAAC;IAEvC,IAAI,cAAc,EAAE,MAAM,EAAE,CAAC;QAC3B,MAAM,WAAW,GAAG,cAAc;aAC/B,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CACb,kBAAkB,CAAC,WAAW,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,SAAS,CAAC,CACxE;aACA,MAAM,CAA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IAAI,QAAQ,EAAE,CAAC;QACjE,OAAO,EAAE,IAAI,EAAE,UAAiB,EAAE,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;IACrE,CAAC;IAED,MAAM,eAAe,GAAG,kBAAkB,EAAE,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE,CAC7D,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,wBAAwB,CAAC,CAChD,CAAC;IAEF,MAAM,UAAU,GACd,eAAe,KAAK,SAAS,IAAI,eAAe,KAAK,CAAC,CAAC;QACrD,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,kBAAkB,EAAE,CAAC,eAAe,CAAC,CAAC;IAE5C,IAAI,UAAU,EAAE,IAAI,IAAI,UAAU,CAAC,EAAE,EAAE,CAAC;QACtC,OAAO;YACL,IAAI,EAAE,UAAU,CAAC,IAAI;YACrB,EAAE,EAAE,UAAU,CAAC,EAAE;YACjB,KAAK,EAAE,eAAe;SACvB,CAAC;IACJ,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport { toHex } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport type {\n TransactionPayControllerMessenger,\n TransactionPayRequiredToken,\n} from '../types';\nimport {\n computeTokenAmounts,\n getTokenBalance,\n getTokenFiatRate,\n getTokenInfo,\n} from './token';\n\nconst FOUR_BYTE_TOKEN_TRANSFER = '0xa9059cbb';\n\n/**\n * Parse required tokens from a transaction.\n *\n * If the transaction has `requiredAssets`, those are used to determine required tokens.\n * Otherwise, falls back to parsing the transaction data for token transfers.\n *\n * @param transaction - Transaction metadata.\n * @param messenger - Controller messenger.\n * @returns An array of required tokens.\n */\nexport function parseRequiredTokens(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): TransactionPayRequiredToken[] {\n const { requiredAssets } = transaction;\n\n if (requiredAssets?.length) {\n const assetTokens = requiredAssets\n .map((asset) =>\n buildRequiredToken(transaction, asset.address, asset.amount, messenger),\n )\n .filter(Boolean) as TransactionPayRequiredToken[];\n\n return assetTokens;\n }\n\n const transferToken = getTokenTransferToken(transaction, messenger);\n return transferToken ? [transferToken] : [];\n}\n\n/**\n * Parse a required token from a token transfer.\n *\n * @param transaction - Transaction metadata.\n * @param messenger - Controller messenger.\n * @returns The required token or undefined if the transaction is not a token transfer.\n */\nfunction getTokenTransferToken(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): TransactionPayRequiredToken | undefined {\n const { data, to } = getTokenTransferData(transaction) ?? {};\n\n if (!to || !data) {\n return undefined;\n }\n\n let transferAmount: Hex | undefined;\n\n try {\n const result = new Interface(abiERC20).decodeFunctionData('transfer', data);\n transferAmount = toHex(result._value);\n } catch {\n // Intentionally empty\n }\n\n if (transferAmount === undefined) {\n return undefined;\n }\n\n return buildRequiredToken(transaction, to, transferAmount, messenger);\n}\n\n/**\n * Get the full token properties for a specific token and amount.\n *\n * @param transaction - Transaction metadata.\n * @param tokenAddress - Token address.\n * @param amountRawHex - Raw token amount in hexadecimal format.\n * @param messenger - Controller messenger.\n * @returns The full token properties or undefined if the token data could not be retrieved.\n */\nfunction buildRequiredToken(\n transaction: TransactionMeta,\n tokenAddress: Hex,\n amountRawHex: Hex,\n messenger: TransactionPayControllerMessenger,\n): TransactionPayRequiredToken | undefined {\n const { chainId, txParams } = transaction;\n const from = txParams.from as Hex;\n\n const { decimals: tokenDecimals, symbol } =\n getTokenInfo(messenger, tokenAddress, chainId) ?? {};\n\n const fiatRates = getTokenFiatRate(messenger, tokenAddress, chainId);\n const tokenBalance = getTokenBalance(messenger, from, chainId, tokenAddress);\n\n if (tokenDecimals === undefined || !symbol || fiatRates === undefined) {\n return undefined;\n }\n\n const {\n human: balanceHuman,\n raw: balanceRaw,\n fiat: balanceFiat,\n usd: balanceUsd,\n } = computeTokenAmounts(tokenBalance, tokenDecimals, fiatRates);\n\n const {\n human: amountHuman,\n raw: amountRaw,\n fiat: amountFiat,\n usd: amountUsd,\n } = computeTokenAmounts(amountRawHex, tokenDecimals, fiatRates);\n\n return {\n address: tokenAddress,\n allowUnderMinimum: false,\n amountFiat,\n amountHuman,\n amountRaw,\n amountUsd,\n balanceFiat,\n balanceHuman,\n balanceRaw,\n balanceUsd,\n chainId,\n decimals: tokenDecimals,\n skipIfBalance: false,\n symbol,\n };\n}\n\n/**\n * Find token transfer data in a transaction.\n *\n * @param transactionMeta - Transaction metadata.\n * @returns - Token transfer data or undefined if not found.\n */\nfunction getTokenTransferData(transactionMeta: TransactionMeta):\n | {\n data: Hex;\n to: Hex;\n index?: number;\n }\n | undefined {\n const { nestedTransactions, txParams } = transactionMeta;\n const { data: singleData } = txParams;\n const singleTo = txParams?.to as Hex | undefined;\n\n if (singleData?.startsWith(FOUR_BYTE_TOKEN_TRANSFER) && singleTo) {\n return { data: singleData as Hex, to: singleTo, index: undefined };\n }\n\n const nestedCallIndex = nestedTransactions?.findIndex((call) =>\n call.data?.startsWith(FOUR_BYTE_TOKEN_TRANSFER),\n );\n\n const nestedCall =\n nestedCallIndex === undefined || nestedCallIndex === -1\n ? undefined\n : nestedTransactions?.[nestedCallIndex];\n\n if (nestedCall?.data && nestedCall.to) {\n return {\n data: nestedCall.data,\n to: nestedCall.to,\n index: nestedCallIndex,\n };\n }\n\n return undefined;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"required-tokens.d.cts","sourceRoot":"","sources":["../../src/utils/required-tokens.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;
|
|
1
|
+
{"version":3,"file":"required-tokens.d.cts","sourceRoot":"","sources":["../../src/utils/required-tokens.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AAGxE,OAAO,KAAK,EACV,iCAAiC,EACjC,2BAA2B,EAC5B,qBAAiB;AAUlB;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,eAAe,EAC5B,SAAS,EAAE,iCAAiC,GAC3C,2BAA2B,EAAE,CAe/B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"required-tokens.d.mts","sourceRoot":"","sources":["../../src/utils/required-tokens.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;
|
|
1
|
+
{"version":3,"file":"required-tokens.d.mts","sourceRoot":"","sources":["../../src/utils/required-tokens.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AAGxE,OAAO,KAAK,EACV,iCAAiC,EACjC,2BAA2B,EAC5B,qBAAiB;AAUlB;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,eAAe,EAC5B,SAAS,EAAE,iCAAiC,GAC3C,2BAA2B,EAAE,CAe/B"}
|
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import { Interface } from "@ethersproject/abi";
|
|
2
2
|
import { toHex } from "@metamask/controller-utils";
|
|
3
3
|
import { abiERC20 } from "@metamask/metamask-eth-abis";
|
|
4
|
-
import { createModuleLogger } from "@metamask/utils";
|
|
5
|
-
import { projectLogger } from "../logger.mjs";
|
|
6
4
|
import { computeTokenAmounts, getTokenBalance, getTokenFiatRate, getTokenInfo } from "./token.mjs";
|
|
7
|
-
const log = createModuleLogger(projectLogger, 'required-tokens');
|
|
8
5
|
const FOUR_BYTE_TOKEN_TRANSFER = '0xa9059cbb';
|
|
9
6
|
/**
|
|
10
7
|
* Parse required tokens from a transaction.
|
|
@@ -37,26 +34,17 @@ export function parseRequiredTokens(transaction, messenger) {
|
|
|
37
34
|
function getTokenTransferToken(transaction, messenger) {
|
|
38
35
|
const { data, to } = getTokenTransferData(transaction) ?? {};
|
|
39
36
|
if (!to || !data) {
|
|
40
|
-
log('No token transfer detected', {
|
|
41
|
-
transactionId: transaction.id,
|
|
42
|
-
});
|
|
43
37
|
return undefined;
|
|
44
38
|
}
|
|
45
39
|
let transferAmount;
|
|
46
|
-
let decodeError;
|
|
47
40
|
try {
|
|
48
41
|
const result = new Interface(abiERC20).decodeFunctionData('transfer', data);
|
|
49
42
|
transferAmount = toHex(result._value);
|
|
50
43
|
}
|
|
51
|
-
catch
|
|
52
|
-
|
|
44
|
+
catch {
|
|
45
|
+
// Intentionally empty
|
|
53
46
|
}
|
|
54
47
|
if (transferAmount === undefined) {
|
|
55
|
-
log('Failed to decode transfer calldata', {
|
|
56
|
-
transactionId: transaction.id,
|
|
57
|
-
to,
|
|
58
|
-
error: decodeError,
|
|
59
|
-
});
|
|
60
48
|
return undefined;
|
|
61
49
|
}
|
|
62
50
|
return buildRequiredToken(transaction, to, transferAmount, messenger);
|
|
@@ -77,16 +65,6 @@ function buildRequiredToken(transaction, tokenAddress, amountRawHex, messenger)
|
|
|
77
65
|
const fiatRates = getTokenFiatRate(messenger, tokenAddress, chainId);
|
|
78
66
|
const tokenBalance = getTokenBalance(messenger, from, chainId, tokenAddress);
|
|
79
67
|
if (tokenDecimals === undefined || !symbol || fiatRates === undefined) {
|
|
80
|
-
log('Missing token data', {
|
|
81
|
-
transactionId: transaction.id,
|
|
82
|
-
chainId,
|
|
83
|
-
tokenAddress,
|
|
84
|
-
missing: {
|
|
85
|
-
decimals: tokenDecimals === undefined,
|
|
86
|
-
symbol: !symbol,
|
|
87
|
-
fiatRates: fiatRates === undefined,
|
|
88
|
-
},
|
|
89
|
-
});
|
|
90
68
|
return undefined;
|
|
91
69
|
}
|
|
92
70
|
const { human: balanceHuman, raw: balanceRaw, fiat: balanceFiat, usd: balanceUsd, } = computeTokenAmounts(tokenBalance, tokenDecimals, fiatRates);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"required-tokens.mjs","sourceRoot":"","sources":["../../src/utils/required-tokens.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,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IAAI,EAAE,UAAU,CAAC,IAAI;YACrB,EAAE,EAAE,UAAU,CAAC,EAAE;YACjB,KAAK,EAAE,eAAe;SACvB,CAAC;IACJ,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport { toHex } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport type {\n TransactionPayControllerMessenger,\n TransactionPayRequiredToken,\n} from '../types';\nimport {\n computeTokenAmounts,\n getTokenBalance,\n getTokenFiatRate,\n getTokenInfo,\n} from './token';\n\nconst FOUR_BYTE_TOKEN_TRANSFER = '0xa9059cbb';\n\n/**\n * Parse required tokens from a transaction.\n *\n * If the transaction has `requiredAssets`, those are used to determine required tokens.\n * Otherwise, falls back to parsing the transaction data for token transfers.\n *\n * @param transaction - Transaction metadata.\n * @param messenger - Controller messenger.\n * @returns An array of required tokens.\n */\nexport function parseRequiredTokens(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): TransactionPayRequiredToken[] {\n const { requiredAssets } = transaction;\n\n if (requiredAssets?.length) {\n const assetTokens = requiredAssets\n .map((asset) =>\n buildRequiredToken(transaction, asset.address, asset.amount, messenger),\n )\n .filter(Boolean) as TransactionPayRequiredToken[];\n\n return assetTokens;\n }\n\n const transferToken = getTokenTransferToken(transaction, messenger);\n return transferToken ? [transferToken] : [];\n}\n\n/**\n * Parse a required token from a token transfer.\n *\n * @param transaction - Transaction metadata.\n * @param messenger - Controller messenger.\n * @returns The required token or undefined if the transaction is not a token transfer.\n */\nfunction getTokenTransferToken(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): TransactionPayRequiredToken | undefined {\n const { data, to } = getTokenTransferData(transaction) ?? {};\n\n if (!to || !data) {\n return undefined;\n }\n\n let transferAmount: Hex | undefined;\n\n try {\n const result = new Interface(abiERC20).decodeFunctionData('transfer', data);\n transferAmount = toHex(result._value);\n } catch {\n // Intentionally empty\n }\n\n if (transferAmount === undefined) {\n return undefined;\n }\n\n return buildRequiredToken(transaction, to, transferAmount, messenger);\n}\n\n/**\n * Get the full token properties for a specific token and amount.\n *\n * @param transaction - Transaction metadata.\n * @param tokenAddress - Token address.\n * @param amountRawHex - Raw token amount in hexadecimal format.\n * @param messenger - Controller messenger.\n * @returns The full token properties or undefined if the token data could not be retrieved.\n */\nfunction buildRequiredToken(\n transaction: TransactionMeta,\n tokenAddress: Hex,\n amountRawHex: Hex,\n messenger: TransactionPayControllerMessenger,\n): TransactionPayRequiredToken | undefined {\n const { chainId, txParams } = transaction;\n const from = txParams.from as Hex;\n\n const { decimals: tokenDecimals, symbol } =\n getTokenInfo(messenger, tokenAddress, chainId) ?? {};\n\n const fiatRates = getTokenFiatRate(messenger, tokenAddress, chainId);\n const tokenBalance = getTokenBalance(messenger, from, chainId, tokenAddress);\n\n if (tokenDecimals === undefined || !symbol || fiatRates === undefined) {\n return undefined;\n }\n\n const {\n human: balanceHuman,\n raw: balanceRaw,\n fiat: balanceFiat,\n usd: balanceUsd,\n } = computeTokenAmounts(tokenBalance, tokenDecimals, fiatRates);\n\n const {\n human: amountHuman,\n raw: amountRaw,\n fiat: amountFiat,\n usd: amountUsd,\n } = computeTokenAmounts(amountRawHex, tokenDecimals, fiatRates);\n\n return {\n address: tokenAddress,\n allowUnderMinimum: false,\n amountFiat,\n amountHuman,\n amountRaw,\n amountUsd,\n balanceFiat,\n balanceHuman,\n balanceRaw,\n balanceUsd,\n chainId,\n decimals: tokenDecimals,\n skipIfBalance: false,\n symbol,\n };\n}\n\n/**\n * Find token transfer data in a transaction.\n *\n * @param transactionMeta - Transaction metadata.\n * @returns - Token transfer data or undefined if not found.\n */\nfunction getTokenTransferData(transactionMeta: TransactionMeta):\n | {\n data: Hex;\n to: Hex;\n index?: number;\n }\n | undefined {\n const { nestedTransactions, txParams } = transactionMeta;\n const { data: singleData } = txParams;\n const singleTo = txParams?.to as Hex | undefined;\n\n if (singleData?.startsWith(FOUR_BYTE_TOKEN_TRANSFER) && singleTo) {\n return { data: singleData as Hex, to: singleTo, index: undefined };\n }\n\n const nestedCallIndex = nestedTransactions?.findIndex((call) =>\n call.data?.startsWith(FOUR_BYTE_TOKEN_TRANSFER),\n );\n\n const nestedCall =\n nestedCallIndex === undefined || nestedCallIndex === -1\n ? undefined\n : nestedTransactions?.[nestedCallIndex];\n\n if (nestedCall?.data && nestedCall.to) {\n return {\n data: nestedCall.data,\n to: nestedCall.to,\n index: nestedCallIndex,\n };\n }\n\n return undefined;\n}\n"]}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isPredictWithdrawTransaction = exports.collectTransactionIds = exports.updateTransaction = exports.waitForTransactionConfirmed = exports.
|
|
3
|
+
exports.isPredictWithdrawTransaction = exports.collectTransactionIds = exports.updateTransaction = exports.waitForTransactionConfirmed = exports.pollTransactionChanges = exports.getTransaction = exports.FINALIZED_STATUSES = void 0;
|
|
4
4
|
const transaction_controller_1 = require("@metamask/transaction-controller");
|
|
5
5
|
const utils_1 = require("@metamask/utils");
|
|
6
6
|
const lodash_1 = require("lodash");
|
|
7
7
|
const logger_1 = require("../logger.cjs");
|
|
8
|
-
const feature_flags_1 = require("./feature-flags.cjs");
|
|
9
8
|
const required_tokens_1 = require("./required-tokens.cjs");
|
|
10
9
|
const log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'transaction');
|
|
11
10
|
exports.FINALIZED_STATUSES = [
|
|
@@ -26,13 +25,13 @@ function getTransaction(transactionId, messenger) {
|
|
|
26
25
|
}
|
|
27
26
|
exports.getTransaction = getTransaction;
|
|
28
27
|
/**
|
|
29
|
-
*
|
|
28
|
+
* Poll for transaction changes and update the transaction data accordingly.
|
|
30
29
|
*
|
|
31
30
|
* @param messenger - Controller messenger.
|
|
32
31
|
* @param updateTransactionData - Callback to update transaction data.
|
|
33
32
|
* @param removeTransactionData - Callback to remove transaction data.
|
|
34
33
|
*/
|
|
35
|
-
function
|
|
34
|
+
function pollTransactionChanges(messenger, updateTransactionData, removeTransactionData) {
|
|
36
35
|
messenger.subscribe('TransactionController:stateChange', (transactions, previousTransactions) => {
|
|
37
36
|
const newTransactions = transactions.filter((tx) => !previousTransactions?.find((prevTx) => prevTx.id === tx.id));
|
|
38
37
|
const updatedTransactions = transactions.filter((tx) => {
|
|
@@ -51,39 +50,7 @@ function subscribeTransactionChanges(messenger, updateTransactionData, removeTra
|
|
|
51
50
|
[...newTransactions, ...updatedTransactions].forEach((tx) => onTransactionChange(tx, messenger, updateTransactionData));
|
|
52
51
|
}, (state) => state.transactions);
|
|
53
52
|
}
|
|
54
|
-
exports.
|
|
55
|
-
/**
|
|
56
|
-
* Subscribe to asset state changes and re-parse required tokens for
|
|
57
|
-
* in-flight transactions whose tokens have not yet resolved.
|
|
58
|
-
*
|
|
59
|
-
* @param messenger - Controller messenger.
|
|
60
|
-
* @param getControllerState - Callback returning the current controller state.
|
|
61
|
-
* @param updateTransactionData - Callback to update transaction data.
|
|
62
|
-
*/
|
|
63
|
-
function subscribeAssetChanges(messenger, getControllerState, updateTransactionData) {
|
|
64
|
-
const buildHandler = (source) => (_state, patches) => {
|
|
65
|
-
const { transactionData } = getControllerState();
|
|
66
|
-
for (const [transactionId, data] of Object.entries(transactionData)) {
|
|
67
|
-
if (data.tokens.length > 0) {
|
|
68
|
-
continue;
|
|
69
|
-
}
|
|
70
|
-
const transaction = getTransaction(transactionId, messenger);
|
|
71
|
-
if (!transaction || exports.FINALIZED_STATUSES.includes(transaction.status)) {
|
|
72
|
-
continue;
|
|
73
|
-
}
|
|
74
|
-
log('Asset data changed', { transactionId, source, patches });
|
|
75
|
-
onTransactionChange(transaction, messenger, updateTransactionData);
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
if ((0, feature_flags_1.getAssetsUnifyStateFeature)(messenger)) {
|
|
79
|
-
messenger.subscribe('AssetsController:stateChange', buildHandler('AssetsController'));
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
messenger.subscribe('TokensController:stateChange', buildHandler('TokensController'));
|
|
83
|
-
messenger.subscribe('TokenRatesController:stateChange', buildHandler('TokenRatesController'));
|
|
84
|
-
messenger.subscribe('CurrencyRateController:stateChange', buildHandler('CurrencyRateController'));
|
|
85
|
-
}
|
|
86
|
-
exports.subscribeAssetChanges = subscribeAssetChanges;
|
|
53
|
+
exports.pollTransactionChanges = pollTransactionChanges;
|
|
87
54
|
/**
|
|
88
55
|
* Wait for a transaction to be confirmed or fail.
|
|
89
56
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.cjs","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":";;;AAAA,6EAG0C;AAG1C,2CAAqD;AAErD,mCAAmC;AAEnC,0CAA0C;AAM1C,uDAA6D;AAC7D,2DAAwD;AAExD,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,aAAa,CAAC,CAAC;AAEhD,QAAA,kBAAkB,GAAG;IAChC,0CAAiB,CAAC,SAAS;IAC3B,0CAAiB,CAAC,OAAO;IACzB,0CAAiB,CAAC,MAAM;CACzB,CAAC;AAEF;;;;;;GAMG;AACH,SAAgB,cAAc,CAC5B,aAAqB,EACrB,SAA4C;IAE5C,MAAM,0BAA0B,GAAG,SAAS,CAAC,IAAI,CAC/C,gCAAgC,CACjC,CAAC;IAEF,OAAO,0BAA0B,CAAC,YAAY,CAAC,IAAI,CACjD,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,aAAa,CAChC,CAAC;AACJ,CAAC;AAXD,wCAWC;AAED;;;;;;GAMG;AACH,SAAgB,2BAA2B,CACzC,SAA4C,EAC5C,qBAAoD,EACpD,qBAAsD;IAEtD,SAAS,CAAC,SAAS,CACjB,mCAAmC,EACnC,CACE,YAA+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AAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,SAAS,sBAAsB,CAC7B,WAA4B,EAC5B,qBAAsD;IAEtD,GAAG,CAAC,uBAAuB,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC;IAC9C,qBAAqB,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import {\n TransactionStatus,\n TransactionType,\n} from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport type { Patch } from 'immer';\nimport { cloneDeep } from 'lodash';\n\nimport { projectLogger } from '../logger';\nimport type {\n TransactionPayControllerMessenger,\n TransactionPayControllerState,\n UpdateTransactionDataCallback,\n} from '../types';\nimport { getAssetsUnifyStateFeature } from './feature-flags';\nimport { parseRequiredTokens } from './required-tokens';\n\nconst log = createModuleLogger(projectLogger, 'transaction');\n\nexport const FINALIZED_STATUSES = [\n TransactionStatus.confirmed,\n TransactionStatus.dropped,\n TransactionStatus.failed,\n];\n\n/**\n * Retrieve transaction metadata by ID.\n *\n * @param transactionId - ID of the transaction to retrieve.\n * @param messenger - Controller messenger.\n * @returns The transaction metadata or undefined if not found.\n */\nexport function getTransaction(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): TransactionMeta | undefined {\n const transactionControllerState = messenger.call(\n 'TransactionController:getState',\n );\n\n return transactionControllerState.transactions.find(\n (tx) => tx.id === transactionId,\n );\n}\n\n/**\n * Subscribe to transaction changes and update the transaction data accordingly.\n *\n * @param messenger - Controller messenger.\n * @param updateTransactionData - Callback to update transaction data.\n * @param removeTransactionData - Callback to remove transaction data.\n */\nexport function subscribeTransactionChanges(\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n removeTransactionData: (transactionId: string) => void,\n): void {\n messenger.subscribe(\n 'TransactionController:stateChange',\n (\n transactions: TransactionMeta[],\n previousTransactions: TransactionMeta[] | undefined,\n ) => {\n const newTransactions = transactions.filter(\n (tx) => !previousTransactions?.find((prevTx) => prevTx.id === tx.id),\n );\n\n const updatedTransactions = transactions.filter((tx) => {\n const previousTransaction = previousTransactions?.find(\n (prevTx) => prevTx.id === tx.id,\n );\n\n return (\n previousTransaction &&\n previousTransaction?.txParams.data !== tx.txParams.data\n );\n });\n\n const finalizedTransactions = transactions.filter((tx) => {\n const previousTransaction = previousTransactions?.find(\n (prevTx) => prevTx.id === tx.id,\n );\n\n return (\n previousTransaction &&\n !FINALIZED_STATUSES.includes(previousTransaction.status) &&\n FINALIZED_STATUSES.includes(tx.status)\n );\n });\n\n const deletedTransactions = (previousTransactions ?? []).filter(\n (prevTx) => !transactions.find((tx) => tx.id === prevTx.id),\n );\n\n [...finalizedTransactions, ...deletedTransactions].forEach((tx) =>\n onTransactionFinalized(tx, removeTransactionData),\n );\n\n [...newTransactions, ...updatedTransactions].forEach((tx) =>\n onTransactionChange(tx, messenger, updateTransactionData),\n );\n },\n (state) => state.transactions,\n );\n}\n\n/**\n * Subscribe to asset state changes and re-parse required tokens for\n * in-flight transactions whose tokens have not yet resolved.\n *\n * @param messenger - Controller messenger.\n * @param getControllerState - Callback returning the current controller state.\n * @param updateTransactionData - Callback to update transaction data.\n */\nexport function subscribeAssetChanges(\n messenger: TransactionPayControllerMessenger,\n getControllerState: () => TransactionPayControllerState,\n updateTransactionData: UpdateTransactionDataCallback,\n): void {\n const buildHandler =\n (source: string) =>\n (_state: unknown, patches: Patch[] | undefined): void => {\n const { transactionData } = getControllerState();\n\n for (const [transactionId, data] of Object.entries(transactionData)) {\n if (data.tokens.length > 0) {\n continue;\n }\n\n const transaction = getTransaction(transactionId, messenger);\n\n if (!transaction || FINALIZED_STATUSES.includes(transaction.status)) {\n continue;\n }\n\n log('Asset data changed', { transactionId, source, patches });\n\n onTransactionChange(transaction, messenger, updateTransactionData);\n }\n };\n\n if (getAssetsUnifyStateFeature(messenger)) {\n messenger.subscribe(\n 'AssetsController:stateChange',\n buildHandler('AssetsController'),\n );\n return;\n }\n\n messenger.subscribe(\n 'TokensController:stateChange',\n buildHandler('TokensController'),\n );\n messenger.subscribe(\n 'TokenRatesController:stateChange',\n buildHandler('TokenRatesController'),\n );\n messenger.subscribe(\n 'CurrencyRateController:stateChange',\n buildHandler('CurrencyRateController'),\n );\n}\n\n/**\n * Wait for a transaction to be confirmed or fail.\n *\n * @param transactionId - ID of the transaction to wait for.\n * @param messenger - Controller messenger.\n * @returns A promise that resolves when the transaction is confirmed or rejects if it fails.\n */\nexport function waitForTransactionConfirmed(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const isConfirmed = (tx?: TransactionMeta, fn?: () => void): boolean => {\n log('Checking transaction status', tx?.status, tx?.type);\n\n if (tx?.status === TransactionStatus.confirmed) {\n fn?.();\n resolve();\n return true;\n }\n\n if (\n [TransactionStatus.dropped, TransactionStatus.failed].includes(\n tx?.status as TransactionStatus,\n )\n ) {\n fn?.();\n reject(\n new Error(`Transaction failed - ${tx?.type} - ${tx?.error?.message}`),\n );\n return true;\n }\n\n return false;\n };\n\n const initialState = messenger.call('TransactionController:getState');\n\n const initialTx = initialState.transactions.find(\n (singleTransaction) => singleTransaction.id === transactionId,\n );\n\n if (isConfirmed(initialTx)) {\n return;\n }\n\n const handler = (tx?: TransactionMeta): void => {\n const unsubscribe = (): void =>\n messenger.unsubscribe('TransactionController:stateChange', handler);\n\n isConfirmed(tx, unsubscribe);\n };\n\n messenger.subscribe('TransactionController:stateChange', handler, (state) =>\n state.transactions.find((tx) => tx.id === transactionId),\n );\n });\n}\n\n/**\n * Update a transaction by applying a function to its draft.\n *\n * @param request - Request object.\n * @param request.transactionId - ID of the transaction to update.\n * @param request.messenger - Controller messenger.\n * @param request.note - Note describing the update.\n * @param fn - Function that applies updates to the transaction draft.\n */\nexport function updateTransaction(\n {\n transactionId,\n messenger,\n note,\n }: {\n transactionId: string;\n messenger: TransactionPayControllerMessenger;\n note: string;\n },\n fn: (draft: TransactionMeta) => void,\n): void {\n const transaction = getTransaction(transactionId, messenger as never);\n\n if (!transaction) {\n throw new Error(`Transaction not found: ${transactionId}`);\n }\n\n const newTransaction = cloneDeep(transaction);\n\n fn(newTransaction);\n\n messenger.call(\n 'TransactionController:updateTransaction',\n newTransaction,\n note,\n );\n}\n\n/**\n * Collect all new transactions until `end` is called.\n *\n * @param chainId - The chain ID to filter transactions by.\n * @param from - The address to filter transactions by.\n * @param messenger - The controller messenger.\n * @param onTransaction - Callback called with each matching transaction ID.\n * @returns An object with an `end` method to stop collecting transactions.\n */\nexport function collectTransactionIds(\n chainId: Hex,\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n onTransaction: (transactionId: string) => void,\n): { end: () => void } {\n const listener = (tx: TransactionMeta): void => {\n if (\n tx.chainId !== chainId ||\n tx.txParams.from.toLowerCase() !== from.toLowerCase()\n ) {\n return;\n }\n\n onTransaction(tx.id);\n };\n\n messenger.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n listener,\n );\n\n const end = (): void => {\n messenger.unsubscribe(\n 'TransactionController:unapprovedTransactionAdded',\n listener,\n );\n };\n\n return { end };\n}\n\n/**\n * Check whether a transaction is a Predict withdrawal.\n *\n * Returns `true` when the transaction's own type is `predictWithdraw`, or\n * when any of its nested transactions has that type.\n *\n * @param transaction - Transaction metadata.\n * @returns `true` when the transaction is a Predict withdrawal.\n */\nexport function isPredictWithdrawTransaction(\n transaction: TransactionMeta,\n): boolean {\n return (\n transaction.type === TransactionType.predictWithdraw ||\n (transaction.nestedTransactions?.some(\n (nt) => nt.type === TransactionType.predictWithdraw,\n ) ??\n false)\n );\n}\n\n/**\n * Handle a transaction change by updating its associated data.\n *\n * @param transaction - Transaction metadata.\n * @param messenger - Controller messenger.\n * @param updateTransactionData - Callback to update transaction data.\n */\nfunction onTransactionChange(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n): void {\n const tokens = parseRequiredTokens(transaction, messenger);\n\n log('Transaction changed', { transaction, tokens });\n\n updateTransactionData(transaction.id, (data) => {\n data.tokens = tokens;\n });\n}\n\n/**\n * Handle a finalized transaction by removing its associated data.\n *\n * @param transaction - Transaction metadata.\n * @param removeTransactionData - Callback to remove transaction data.\n */\nfunction onTransactionFinalized(\n transaction: TransactionMeta,\n removeTransactionData: (transactionId: string) => void,\n): void {\n log('Transaction finalized', { transaction });\n removeTransactionData(transaction.id);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"transaction.cjs","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":";;;AAAA,6EAG0C;AAG1C,2CAAqD;AACrD,mCAAmC;AAEnC,0CAA0C;AAK1C,2DAAwD;AAExD,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,aAAa,CAAC,CAAC;AAEhD,QAAA,kBAAkB,GAAG;IAChC,0CAAiB,CAAC,SAAS;IAC3B,0CAAiB,CAAC,OAAO;IACzB,0CAAiB,CAAC,MAAM;CACzB,CAAC;AAEF;;;;;;GAMG;AACH,SAAgB,cAAc,CAC5B,aAAqB,EACrB,SAA4C;IAE5C,MAAM,0BAA0B,GAAG,SAAS,CAAC,IAAI,CAC/C,gCAAgC,CACjC,CAAC;IAEF,OAAO,0BAA0B,CAAC,YAAY,CAAC,IAAI,CACjD,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,aAAa,CAChC,CAAC;AACJ,CAAC;AAXD,wCAWC;AAED;;;;;;GAMG;AACH,SAAgB,sBAAsB,CACpC,SAA4C,EAC5C,qBAAoD,EACpD,qBAAsD;IAEtD,SAAS,CAAC,SAAS,CACjB,mCAAmC,EACnC,CACE,YAA+B,EAC/B,oBAAmD,EACnD,EAAE;QACF,MAAM,eAAe,GAAG,YAAY,CAAC,MAAM,CACzC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,oBAAoB,EAAE,IAAI,CAAC,CAAC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,CAAC;IAC9C,qBAAqB,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import {\n TransactionStatus,\n TransactionType,\n} from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { cloneDeep } from 'lodash';\n\nimport { projectLogger } from '../logger';\nimport type {\n TransactionPayControllerMessenger,\n UpdateTransactionDataCallback,\n} from '../types';\nimport { parseRequiredTokens } from './required-tokens';\n\nconst log = createModuleLogger(projectLogger, 'transaction');\n\nexport const FINALIZED_STATUSES = [\n TransactionStatus.confirmed,\n TransactionStatus.dropped,\n TransactionStatus.failed,\n];\n\n/**\n * Retrieve transaction metadata by ID.\n *\n * @param transactionId - ID of the transaction to retrieve.\n * @param messenger - Controller messenger.\n * @returns The transaction metadata or undefined if not found.\n */\nexport function getTransaction(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): TransactionMeta | undefined {\n const transactionControllerState = messenger.call(\n 'TransactionController:getState',\n );\n\n return transactionControllerState.transactions.find(\n (tx) => tx.id === transactionId,\n );\n}\n\n/**\n * Poll for transaction changes and update the transaction data accordingly.\n *\n * @param messenger - Controller messenger.\n * @param updateTransactionData - Callback to update transaction data.\n * @param removeTransactionData - Callback to remove transaction data.\n */\nexport function pollTransactionChanges(\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n removeTransactionData: (transactionId: string) => void,\n): void {\n messenger.subscribe(\n 'TransactionController:stateChange',\n (\n transactions: TransactionMeta[],\n previousTransactions: TransactionMeta[] | undefined,\n ) => {\n const newTransactions = transactions.filter(\n (tx) => !previousTransactions?.find((prevTx) => prevTx.id === tx.id),\n );\n\n const updatedTransactions = transactions.filter((tx) => {\n const previousTransaction = previousTransactions?.find(\n (prevTx) => prevTx.id === tx.id,\n );\n\n return (\n previousTransaction &&\n previousTransaction?.txParams.data !== tx.txParams.data\n );\n });\n\n const finalizedTransactions = transactions.filter((tx) => {\n const previousTransaction = previousTransactions?.find(\n (prevTx) => prevTx.id === tx.id,\n );\n\n return (\n previousTransaction &&\n !FINALIZED_STATUSES.includes(previousTransaction.status) &&\n FINALIZED_STATUSES.includes(tx.status)\n );\n });\n\n const deletedTransactions = (previousTransactions ?? []).filter(\n (prevTx) => !transactions.find((tx) => tx.id === prevTx.id),\n );\n\n [...finalizedTransactions, ...deletedTransactions].forEach((tx) =>\n onTransactionFinalized(tx, removeTransactionData),\n );\n\n [...newTransactions, ...updatedTransactions].forEach((tx) =>\n onTransactionChange(tx, messenger, updateTransactionData),\n );\n },\n (state) => state.transactions,\n );\n}\n\n/**\n * Wait for a transaction to be confirmed or fail.\n *\n * @param transactionId - ID of the transaction to wait for.\n * @param messenger - Controller messenger.\n * @returns A promise that resolves when the transaction is confirmed or rejects if it fails.\n */\nexport function waitForTransactionConfirmed(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const isConfirmed = (tx?: TransactionMeta, fn?: () => void): boolean => {\n log('Checking transaction status', tx?.status, tx?.type);\n\n if (tx?.status === TransactionStatus.confirmed) {\n fn?.();\n resolve();\n return true;\n }\n\n if (\n [TransactionStatus.dropped, TransactionStatus.failed].includes(\n tx?.status as TransactionStatus,\n )\n ) {\n fn?.();\n reject(\n new Error(`Transaction failed - ${tx?.type} - ${tx?.error?.message}`),\n );\n return true;\n }\n\n return false;\n };\n\n const initialState = messenger.call('TransactionController:getState');\n\n const initialTx = initialState.transactions.find(\n (singleTransaction) => singleTransaction.id === transactionId,\n );\n\n if (isConfirmed(initialTx)) {\n return;\n }\n\n const handler = (tx?: TransactionMeta): void => {\n const unsubscribe = (): void =>\n messenger.unsubscribe('TransactionController:stateChange', handler);\n\n isConfirmed(tx, unsubscribe);\n };\n\n messenger.subscribe('TransactionController:stateChange', handler, (state) =>\n state.transactions.find((tx) => tx.id === transactionId),\n );\n });\n}\n\n/**\n * Update a transaction by applying a function to its draft.\n *\n * @param request - Request object.\n * @param request.transactionId - ID of the transaction to update.\n * @param request.messenger - Controller messenger.\n * @param request.note - Note describing the update.\n * @param fn - Function that applies updates to the transaction draft.\n */\nexport function updateTransaction(\n {\n transactionId,\n messenger,\n note,\n }: {\n transactionId: string;\n messenger: TransactionPayControllerMessenger;\n note: string;\n },\n fn: (draft: TransactionMeta) => void,\n): void {\n const transaction = getTransaction(transactionId, messenger as never);\n\n if (!transaction) {\n throw new Error(`Transaction not found: ${transactionId}`);\n }\n\n const newTransaction = cloneDeep(transaction);\n\n fn(newTransaction);\n\n messenger.call(\n 'TransactionController:updateTransaction',\n newTransaction,\n note,\n );\n}\n\n/**\n * Collect all new transactions until `end` is called.\n *\n * @param chainId - The chain ID to filter transactions by.\n * @param from - The address to filter transactions by.\n * @param messenger - The controller messenger.\n * @param onTransaction - Callback called with each matching transaction ID.\n * @returns An object with an `end` method to stop collecting transactions.\n */\nexport function collectTransactionIds(\n chainId: Hex,\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n onTransaction: (transactionId: string) => void,\n): { end: () => void } {\n const listener = (tx: TransactionMeta): void => {\n if (\n tx.chainId !== chainId ||\n tx.txParams.from.toLowerCase() !== from.toLowerCase()\n ) {\n return;\n }\n\n onTransaction(tx.id);\n };\n\n messenger.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n listener,\n );\n\n const end = (): void => {\n messenger.unsubscribe(\n 'TransactionController:unapprovedTransactionAdded',\n listener,\n );\n };\n\n return { end };\n}\n\n/**\n * Check whether a transaction is a Predict withdrawal.\n *\n * Returns `true` when the transaction's own type is `predictWithdraw`, or\n * when any of its nested transactions has that type.\n *\n * @param transaction - Transaction metadata.\n * @returns `true` when the transaction is a Predict withdrawal.\n */\nexport function isPredictWithdrawTransaction(\n transaction: TransactionMeta,\n): boolean {\n return (\n transaction.type === TransactionType.predictWithdraw ||\n (transaction.nestedTransactions?.some(\n (nt) => nt.type === TransactionType.predictWithdraw,\n ) ??\n false)\n );\n}\n\n/**\n * Handle a transaction change by updating its associated data.\n *\n * @param transaction - Transaction metadata.\n * @param messenger - Controller messenger.\n * @param updateTransactionData - Callback to update transaction data.\n */\nfunction onTransactionChange(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n): void {\n const tokens = parseRequiredTokens(transaction, messenger);\n\n log('Transaction changed', { transaction, tokens });\n\n updateTransactionData(transaction.id, (data) => {\n data.tokens = tokens;\n });\n}\n\n/**\n * Handle a finalized transaction by removing its associated data.\n *\n * @param transaction - Transaction metadata.\n * @param removeTransactionData - Callback to remove transaction data.\n */\nfunction onTransactionFinalized(\n transaction: TransactionMeta,\n removeTransactionData: (transactionId: string) => void,\n): void {\n log('Transaction finalized', { transaction });\n removeTransactionData(transaction.id);\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { TransactionStatus } from "@metamask/transaction-controller";
|
|
2
2
|
import type { TransactionMeta } from "@metamask/transaction-controller";
|
|
3
3
|
import type { Hex } from "@metamask/utils";
|
|
4
|
-
import type { TransactionPayControllerMessenger,
|
|
4
|
+
import type { TransactionPayControllerMessenger, UpdateTransactionDataCallback } from "../types.cjs";
|
|
5
5
|
export declare const FINALIZED_STATUSES: TransactionStatus[];
|
|
6
6
|
/**
|
|
7
7
|
* Retrieve transaction metadata by ID.
|
|
@@ -12,22 +12,13 @@ export declare const FINALIZED_STATUSES: TransactionStatus[];
|
|
|
12
12
|
*/
|
|
13
13
|
export declare function getTransaction(transactionId: string, messenger: TransactionPayControllerMessenger): TransactionMeta | undefined;
|
|
14
14
|
/**
|
|
15
|
-
*
|
|
15
|
+
* Poll for transaction changes and update the transaction data accordingly.
|
|
16
16
|
*
|
|
17
17
|
* @param messenger - Controller messenger.
|
|
18
18
|
* @param updateTransactionData - Callback to update transaction data.
|
|
19
19
|
* @param removeTransactionData - Callback to remove transaction data.
|
|
20
20
|
*/
|
|
21
|
-
export declare function
|
|
22
|
-
/**
|
|
23
|
-
* Subscribe to asset state changes and re-parse required tokens for
|
|
24
|
-
* in-flight transactions whose tokens have not yet resolved.
|
|
25
|
-
*
|
|
26
|
-
* @param messenger - Controller messenger.
|
|
27
|
-
* @param getControllerState - Callback returning the current controller state.
|
|
28
|
-
* @param updateTransactionData - Callback to update transaction data.
|
|
29
|
-
*/
|
|
30
|
-
export declare function subscribeAssetChanges(messenger: TransactionPayControllerMessenger, getControllerState: () => TransactionPayControllerState, updateTransactionData: UpdateTransactionDataCallback): void;
|
|
21
|
+
export declare function pollTransactionChanges(messenger: TransactionPayControllerMessenger, updateTransactionData: UpdateTransactionDataCallback, removeTransactionData: (transactionId: string) => void): void;
|
|
31
22
|
/**
|
|
32
23
|
* Wait for a transaction to be confirmed or fail.
|
|
33
24
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.d.cts","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EAElB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;
|
|
1
|
+
{"version":3,"file":"transaction.d.cts","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EAElB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAK3C,OAAO,KAAK,EACV,iCAAiC,EACjC,6BAA6B,EAC9B,qBAAiB;AAKlB,eAAO,MAAM,kBAAkB,qBAI9B,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,aAAa,EAAE,MAAM,EACrB,SAAS,EAAE,iCAAiC,GAC3C,eAAe,GAAG,SAAS,CAQ7B;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,SAAS,EAAE,iCAAiC,EAC5C,qBAAqB,EAAE,6BAA6B,EACpD,qBAAqB,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,IAAI,GACrD,IAAI,CAgDN;AAED;;;;;;GAMG;AACH,wBAAgB,2BAA2B,CACzC,aAAa,EAAE,MAAM,EACrB,SAAS,EAAE,iCAAiC,GAC3C,OAAO,CAAC,IAAI,CAAC,CA+Cf;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAC/B,EACE,aAAa,EACb,SAAS,EACT,IAAI,GACL,EAAE;IACD,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,iCAAiC,CAAC;IAC7C,IAAI,EAAE,MAAM,CAAC;CACd,EACD,EAAE,EAAE,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,GACnC,IAAI,CAgBN;AAED;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,GAAG,EACZ,IAAI,EAAE,GAAG,EACT,SAAS,EAAE,iCAAiC,EAC5C,aAAa,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,IAAI,GAC7C;IAAE,GAAG,EAAE,MAAM,IAAI,CAAA;CAAE,CAyBrB;AAED;;;;;;;;GAQG;AACH,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,eAAe,GAC3B,OAAO,CAQT"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { TransactionStatus } from "@metamask/transaction-controller";
|
|
2
2
|
import type { TransactionMeta } from "@metamask/transaction-controller";
|
|
3
3
|
import type { Hex } from "@metamask/utils";
|
|
4
|
-
import type { TransactionPayControllerMessenger,
|
|
4
|
+
import type { TransactionPayControllerMessenger, UpdateTransactionDataCallback } from "../types.mjs";
|
|
5
5
|
export declare const FINALIZED_STATUSES: TransactionStatus[];
|
|
6
6
|
/**
|
|
7
7
|
* Retrieve transaction metadata by ID.
|
|
@@ -12,22 +12,13 @@ export declare const FINALIZED_STATUSES: TransactionStatus[];
|
|
|
12
12
|
*/
|
|
13
13
|
export declare function getTransaction(transactionId: string, messenger: TransactionPayControllerMessenger): TransactionMeta | undefined;
|
|
14
14
|
/**
|
|
15
|
-
*
|
|
15
|
+
* Poll for transaction changes and update the transaction data accordingly.
|
|
16
16
|
*
|
|
17
17
|
* @param messenger - Controller messenger.
|
|
18
18
|
* @param updateTransactionData - Callback to update transaction data.
|
|
19
19
|
* @param removeTransactionData - Callback to remove transaction data.
|
|
20
20
|
*/
|
|
21
|
-
export declare function
|
|
22
|
-
/**
|
|
23
|
-
* Subscribe to asset state changes and re-parse required tokens for
|
|
24
|
-
* in-flight transactions whose tokens have not yet resolved.
|
|
25
|
-
*
|
|
26
|
-
* @param messenger - Controller messenger.
|
|
27
|
-
* @param getControllerState - Callback returning the current controller state.
|
|
28
|
-
* @param updateTransactionData - Callback to update transaction data.
|
|
29
|
-
*/
|
|
30
|
-
export declare function subscribeAssetChanges(messenger: TransactionPayControllerMessenger, getControllerState: () => TransactionPayControllerState, updateTransactionData: UpdateTransactionDataCallback): void;
|
|
21
|
+
export declare function pollTransactionChanges(messenger: TransactionPayControllerMessenger, updateTransactionData: UpdateTransactionDataCallback, removeTransactionData: (transactionId: string) => void): void;
|
|
31
22
|
/**
|
|
32
23
|
* Wait for a transaction to be confirmed or fail.
|
|
33
24
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.d.mts","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EAElB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;
|
|
1
|
+
{"version":3,"file":"transaction.d.mts","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EAElB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,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