@metamask/transaction-controller 62.3.1 → 62.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -1
- package/dist/TransactionController.cjs.map +1 -1
- package/dist/TransactionController.d.cts.map +1 -1
- package/dist/TransactionController.d.mts.map +1 -1
- package/dist/TransactionController.mjs.map +1 -1
- package/dist/api/simulation-api.cjs.map +1 -1
- package/dist/api/simulation-api.d.cts +1 -1
- package/dist/api/simulation-api.d.cts.map +1 -1
- package/dist/api/simulation-api.d.mts +1 -1
- package/dist/api/simulation-api.d.mts.map +1 -1
- package/dist/api/simulation-api.mjs.map +1 -1
- package/dist/gas-flows/DefaultGasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/DefaultGasFeeFlow.d.cts.map +1 -1
- package/dist/gas-flows/DefaultGasFeeFlow.d.mts.map +1 -1
- package/dist/gas-flows/DefaultGasFeeFlow.mjs.map +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.d.cts.map +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.d.mts.map +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.mjs.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.cts.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.mts.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs.map +1 -1
- package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/OracleLayer1GasFeeFlow.d.cts.map +1 -1
- package/dist/gas-flows/OracleLayer1GasFeeFlow.d.mts.map +1 -1
- package/dist/gas-flows/OracleLayer1GasFeeFlow.mjs.map +1 -1
- package/dist/gas-flows/RandomisedEstimationsGasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/RandomisedEstimationsGasFeeFlow.d.cts +1 -1
- package/dist/gas-flows/RandomisedEstimationsGasFeeFlow.d.cts.map +1 -1
- package/dist/gas-flows/RandomisedEstimationsGasFeeFlow.d.mts +1 -1
- package/dist/gas-flows/RandomisedEstimationsGasFeeFlow.d.mts.map +1 -1
- package/dist/gas-flows/RandomisedEstimationsGasFeeFlow.mjs.map +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.cts +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.cts.map +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.mts +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.mts.map +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.mjs.map +1 -1
- package/dist/gas-flows/TestGasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/TestGasFeeFlow.d.cts +1 -1
- package/dist/gas-flows/TestGasFeeFlow.d.cts.map +1 -1
- package/dist/gas-flows/TestGasFeeFlow.d.mts +1 -1
- package/dist/gas-flows/TestGasFeeFlow.d.mts.map +1 -1
- package/dist/gas-flows/TestGasFeeFlow.mjs.map +1 -1
- package/dist/helpers/AccountsApiRemoteTransactionSource.cjs.map +1 -1
- package/dist/helpers/AccountsApiRemoteTransactionSource.mjs.map +1 -1
- package/dist/helpers/GasFeePoller.cjs.map +1 -1
- package/dist/helpers/GasFeePoller.d.cts.map +1 -1
- package/dist/helpers/GasFeePoller.d.mts.map +1 -1
- package/dist/helpers/GasFeePoller.mjs.map +1 -1
- package/dist/helpers/MultichainTrackingHelper.cjs.map +1 -1
- package/dist/helpers/MultichainTrackingHelper.d.cts.map +1 -1
- package/dist/helpers/MultichainTrackingHelper.d.mts.map +1 -1
- package/dist/helpers/MultichainTrackingHelper.mjs.map +1 -1
- package/dist/helpers/TransactionPoller.cjs.map +1 -1
- package/dist/helpers/TransactionPoller.d.cts +1 -1
- package/dist/helpers/TransactionPoller.d.cts.map +1 -1
- package/dist/helpers/TransactionPoller.d.mts +1 -1
- package/dist/helpers/TransactionPoller.d.mts.map +1 -1
- package/dist/helpers/TransactionPoller.mjs.map +1 -1
- package/dist/hooks/ExtraTransactionsPublishHook.cjs.map +1 -1
- package/dist/hooks/ExtraTransactionsPublishHook.d.cts.map +1 -1
- package/dist/hooks/ExtraTransactionsPublishHook.d.mts.map +1 -1
- package/dist/hooks/ExtraTransactionsPublishHook.mjs.map +1 -1
- package/dist/hooks/SequentialPublishBatchHook.cjs.map +1 -1
- package/dist/hooks/SequentialPublishBatchHook.d.cts +1 -1
- package/dist/hooks/SequentialPublishBatchHook.d.cts.map +1 -1
- package/dist/hooks/SequentialPublishBatchHook.d.mts +1 -1
- package/dist/hooks/SequentialPublishBatchHook.d.mts.map +1 -1
- package/dist/hooks/SequentialPublishBatchHook.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +2 -0
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +2 -0
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/balance-changes.cjs.map +1 -1
- package/dist/utils/balance-changes.d.cts +1 -1
- package/dist/utils/balance-changes.d.cts.map +1 -1
- package/dist/utils/balance-changes.d.mts +1 -1
- package/dist/utils/balance-changes.d.mts.map +1 -1
- package/dist/utils/balance-changes.mjs.map +1 -1
- package/dist/utils/batch.cjs +10 -3
- package/dist/utils/batch.cjs.map +1 -1
- package/dist/utils/batch.d.cts +2 -3
- package/dist/utils/batch.d.cts.map +1 -1
- package/dist/utils/batch.d.mts +2 -3
- package/dist/utils/batch.d.mts.map +1 -1
- package/dist/utils/batch.mjs +10 -3
- package/dist/utils/batch.mjs.map +1 -1
- package/dist/utils/eip7702.cjs.map +1 -1
- package/dist/utils/eip7702.d.cts +1 -1
- package/dist/utils/eip7702.d.cts.map +1 -1
- package/dist/utils/eip7702.d.mts +1 -1
- package/dist/utils/eip7702.d.mts.map +1 -1
- package/dist/utils/eip7702.mjs.map +1 -1
- package/dist/utils/external-transactions.cjs +1 -1
- package/dist/utils/external-transactions.cjs.map +1 -1
- package/dist/utils/external-transactions.mjs +1 -1
- package/dist/utils/external-transactions.mjs.map +1 -1
- package/dist/utils/feature-flags.cjs.map +1 -1
- package/dist/utils/feature-flags.d.cts +1 -1
- package/dist/utils/feature-flags.d.cts.map +1 -1
- package/dist/utils/feature-flags.d.mts +1 -1
- package/dist/utils/feature-flags.d.mts.map +1 -1
- package/dist/utils/feature-flags.mjs.map +1 -1
- package/dist/utils/first-time-interaction.cjs.map +1 -1
- package/dist/utils/first-time-interaction.d.cts +1 -1
- package/dist/utils/first-time-interaction.d.cts.map +1 -1
- package/dist/utils/first-time-interaction.d.mts +1 -1
- package/dist/utils/first-time-interaction.d.mts.map +1 -1
- package/dist/utils/first-time-interaction.mjs.map +1 -1
- package/dist/utils/gas-fee-tokens.cjs +3 -3
- package/dist/utils/gas-fee-tokens.cjs.map +1 -1
- package/dist/utils/gas-fee-tokens.mjs +3 -3
- package/dist/utils/gas-fee-tokens.mjs.map +1 -1
- package/dist/utils/gas-fees.cjs.map +1 -1
- package/dist/utils/gas-fees.mjs.map +1 -1
- package/dist/utils/gas-flow.cjs.map +1 -1
- package/dist/utils/gas-flow.d.cts +2 -2
- package/dist/utils/gas-flow.d.cts.map +1 -1
- package/dist/utils/gas-flow.d.mts +2 -2
- package/dist/utils/gas-flow.d.mts.map +1 -1
- package/dist/utils/gas-flow.mjs.map +1 -1
- package/dist/utils/gas.cjs +1 -1
- package/dist/utils/gas.cjs.map +1 -1
- package/dist/utils/gas.d.cts +1 -2
- package/dist/utils/gas.d.cts.map +1 -1
- package/dist/utils/gas.d.mts +1 -2
- package/dist/utils/gas.d.mts.map +1 -1
- package/dist/utils/gas.mjs +1 -1
- package/dist/utils/gas.mjs.map +1 -1
- package/dist/utils/layer1-gas-fee-flow.cjs.map +1 -1
- package/dist/utils/layer1-gas-fee-flow.d.cts +1 -1
- package/dist/utils/layer1-gas-fee-flow.d.cts.map +1 -1
- package/dist/utils/layer1-gas-fee-flow.d.mts +1 -1
- package/dist/utils/layer1-gas-fee-flow.d.mts.map +1 -1
- package/dist/utils/layer1-gas-fee-flow.mjs.map +1 -1
- package/dist/utils/retry.cjs.map +1 -1
- package/dist/utils/retry.d.cts +1 -2
- package/dist/utils/retry.d.cts.map +1 -1
- package/dist/utils/retry.d.mts +1 -2
- package/dist/utils/retry.d.mts.map +1 -1
- package/dist/utils/retry.mjs.map +1 -1
- package/dist/utils/transaction-type.cjs.map +1 -1
- package/dist/utils/transaction-type.d.cts +1 -1
- package/dist/utils/transaction-type.d.cts.map +1 -1
- package/dist/utils/transaction-type.d.mts +1 -1
- package/dist/utils/transaction-type.d.mts.map +1 -1
- package/dist/utils/transaction-type.mjs.map +1 -1
- package/dist/utils/utils.cjs.map +1 -1
- package/dist/utils/utils.mjs.map +1 -1
- package/dist/utils/validation.cjs +2 -4
- package/dist/utils/validation.cjs.map +1 -1
- package/dist/utils/validation.d.cts +2 -2
- package/dist/utils/validation.d.cts.map +1 -1
- package/dist/utils/validation.d.mts +2 -2
- package/dist/utils/validation.d.mts.map +1 -1
- package/dist/utils/validation.mjs +2 -4
- package/dist/utils/validation.mjs.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feature-flags.mjs","sourceRoot":"","sources":["../../src/utils/feature-flags.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAY,wBAAwB;AAE/D,OAAO,EAAE,gBAAgB,EAAE,wBAAoB;AAC/C,OAAO,EAAE,kBAAkB,EAAE,oBAAgB;AAC7C,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAG1C,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,qCAAqC,GAAG,EAAE,CAAC;AACjD,MAAM,uCAAuC,GAAG,CAAC,GAAG,IAAI,CAAC;AACzD,MAAM,2CAA2C,G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vB,2BAA2B,CAC5B,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,sCAAsC,CACpD,SAAyC;IAEzC,MAAM,YAAY,GAAG,eAAe,CAAC,SAAS,CAAC,CAAC;IAEhD,OAAO,CACL,YAAY,EAAE,CAAC,WAAW,CAAC,oBAAoB,CAAC,EAAE,iBAAiB;QACnE,iDAAiD,CAClD,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,eAAe,CACtB,SAAyC;IAEzC,MAAM,YAAY,GAAG,SAAS,CAAC,IAAI,CACjC,sCAAsC,CACvC,CAAC,kBAAkB,CAAC;IAErB,GAAG,CAAC,yBAAyB,EAAE,YAAY,CAAC,CAAC;IAE7C,OAAO,YAAiD,CAAC;AAC3D,CAAC","sourcesContent":["import { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport { isValidSignature } from './signature';\nimport { padHexToEvenLength } from './utils';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\n\nconst DEFAULT_BATCH_SIZE_LIMIT = 10;\nconst DEFAULT_ACCELERATED_POLLING_COUNT_MAX = 10;\nconst DEFAULT_ACCELERATED_POLLING_INTERVAL_MS = 3 * 1000;\nconst DEFAULT_GAS_ESTIMATE_FALLBACK_BLOCK_PERCENT = 35;\nconst DEFAULT_GAS_ESTIMATE_BUFFER = 1;\nconst DEFAULT_INCOMING_TRANSACTIONS_POLLING_INTERVAL_MS = 1000 * 60 * 4; // 4 Minutes\n\n/**\n * Feature flags supporting the transaction controller.\n */\nexport enum FeatureFlag {\n EIP7702 = 'confirmations_eip_7702',\n GasBuffer = 'confirmations_gas_buffer',\n IncomingTransactions = 'confirmations_incoming_transactions',\n Transactions = 'confirmations_transactions',\n}\n\ntype GasEstimateFallback = {\n /**\n * The fixed gas estimate fallback for a transaction.\n */\n fixed?: number;\n\n /**\n * The percentage multiplier gas estimate fallback for a transaction.\n */\n percentage?: number;\n};\n\nexport type TransactionControllerFeatureFlags = {\n /** Feature flags to support EIP-7702 / type-4 transactions. */\n [FeatureFlag.EIP7702]?: {\n /**\n * All contracts that support EIP-7702 batch transactions.\n * Keyed by chain ID.\n * First entry in each array is the contract that standard EOAs will be upgraded to.\n */\n contracts?: Record<\n Hex,\n {\n /** Address of the smart contract. */\n address: Hex;\n\n /** Signature to verify the contract is authentic. */\n signature: Hex;\n }[]\n >;\n\n /** Chains enabled for EIP-7702 batch transactions. */\n supportedChains?: Hex[];\n };\n\n /**\n * Buffers added to gas limit estimations.\n * Values are multipliers such as `1.5` meaning 150% of the original gas limit.\n */\n [FeatureFlag.GasBuffer]?: {\n /** Fallback buffer for all chains and transactions. */\n default?: number;\n\n /**\n * Buffer for included network RPCs only and not those added by user.\n * Takes priority over `default`.\n */\n included?: number;\n\n /** Buffers for specific chains. */\n perChainConfig?: {\n [chainId: Hex]: {\n /**\n * Buffer for the chain for all transactions.\n * Takes priority over non-chain `included`.\n */\n base?: number;\n\n /**\n * Buffer if network RPC is included and not added by user.\n * Takes priority over `base`.\n */\n included?: number;\n\n /**\n * Buffer for the chain for EIP-7702 / type 4 transactions only.\n * Only if `data` included and `to` matches `from`.\n * Takes priority over `included` and `base`.\n */\n eip7702?: number;\n };\n };\n };\n\n /** Incoming transaction configuration. */\n [FeatureFlag.IncomingTransactions]?: {\n /** Interval between requests to accounts API to retrieve incoming transactions. */\n pollingIntervalMs?: number;\n };\n\n /** Miscellaneous feature flags to support the transaction controller. */\n [FeatureFlag.Transactions]?: {\n /** Maximum number of transactions that can be in an external batch. */\n batchSizeLimit?: number;\n\n /**\n * Accelerated polling is used to speed up the polling process for\n * transactions that are not yet confirmed.\n */\n acceleratedPolling?: {\n /** Accelerated polling parameters on a per-chain basis. */\n perChainConfig?: {\n [chainId: Hex]: {\n /**\n * Maximum number of polling requests that can be made in a row, before\n * the normal polling resumes.\n */\n countMax?: number;\n\n /** Interval between polling requests in milliseconds. */\n intervalMs?: number;\n };\n };\n\n /** Default `countMax` in case no chain-specific parameter is set. */\n defaultCountMax?: number;\n\n /** Default `intervalMs` in case no chain-specific parameter is set. */\n defaultIntervalMs?: number;\n };\n\n gasFeeRandomisation?: {\n /** Randomised gas fee digits per chainId. */\n randomisedGasFeeDigits?: Record<Hex, number>;\n\n /** Number of digits to preserve for randomised gas fee digits. */\n preservedNumberOfDigits?: number;\n };\n\n /** Gas estimate fallback is used as a fallback in case of failure to obtain the gas estimate values. */\n gasEstimateFallback?: {\n /** Gas estimate fallback per-chain basis. */\n perChainConfig?: {\n [chainId: Hex]: GasEstimateFallback;\n };\n\n /**\n * Default gas estimate fallback.\n * This value is used when no specific gas estimate fallback is found for a chain ID.\n */\n default?: GasEstimateFallback;\n };\n };\n};\n\nconst log = createModuleLogger(projectLogger, 'feature-flags');\n\n/**\n * Retrieves the supported EIP-7702 chains.\n *\n * @param messenger - The controller messenger instance.\n * @returns The supported chains.\n */\nexport function getEIP7702SupportedChains(\n messenger: TransactionControllerMessenger,\n): Hex[] {\n const featureFlags = getFeatureFlags(messenger);\n return featureFlags?.[FeatureFlag.EIP7702]?.supportedChains ?? [];\n}\n\n/**\n * Retrieves the supported EIP-7702 contract addresses for a given chain ID.\n *\n * @param chainId - The chain ID.\n * @param messenger - The controller messenger instance.\n * @param publicKey - The public key used to validate the contract authenticity.\n * @returns The supported contract addresses.\n */\nexport function getEIP7702ContractAddresses(\n chainId: Hex,\n messenger: TransactionControllerMessenger,\n publicKey: Hex,\n): Hex[] {\n const featureFlags = getFeatureFlags(messenger);\n\n const contracts =\n featureFlags?.[FeatureFlag.EIP7702]?.contracts?.[\n chainId.toLowerCase() as Hex\n ] ?? [];\n\n return contracts\n .filter((contract) =>\n isValidSignature(\n [contract.address, padHexToEvenLength(chainId) as Hex],\n contract.signature,\n publicKey,\n ),\n )\n .map((contract) => contract.address);\n}\n\n/**\n * Retrieves the EIP-7702 upgrade contract address.\n *\n * @param chainId - The chain ID.\n * @param messenger - The controller messenger instance.\n * @param publicKey - The public key used to validate the contract authenticity.\n * @returns The upgrade contract address.\n */\nexport function getEIP7702UpgradeContractAddress(\n chainId: Hex,\n messenger: TransactionControllerMessenger,\n publicKey: Hex,\n): Hex | undefined {\n return getEIP7702ContractAddresses(chainId, messenger, publicKey)?.[0];\n}\n\n/**\n * Retrieves the batch size limit.\n * Defaults to 10 if not set.\n *\n * @param messenger - The controller messenger instance.\n * @returns The batch size limit.\n */\nexport function getBatchSizeLimit(\n messenger: TransactionControllerMessenger,\n): number {\n const featureFlags = getFeatureFlags(messenger);\n return (\n featureFlags?.[FeatureFlag.Transactions]?.batchSizeLimit ??\n DEFAULT_BATCH_SIZE_LIMIT\n );\n}\n\n/**\n * Retrieves the accelerated polling parameters for a given chain ID.\n *\n * @param chainId - The chain ID.\n * @param messenger - The controller messenger instance.\n * @returns The accelerated polling parameters: `countMax` and `intervalMs`.\n */\nexport function getAcceleratedPollingParams(\n chainId: Hex,\n messenger: TransactionControllerMessenger,\n): { countMax: number; intervalMs: number } {\n const featureFlags = getFeatureFlags(messenger);\n\n const acceleratedPollingParams =\n featureFlags?.[FeatureFlag.Transactions]?.acceleratedPolling;\n\n const countMax =\n acceleratedPollingParams?.perChainConfig?.[chainId]?.countMax ||\n acceleratedPollingParams?.defaultCountMax ||\n DEFAULT_ACCELERATED_POLLING_COUNT_MAX;\n\n const intervalMs =\n acceleratedPollingParams?.perChainConfig?.[chainId]?.intervalMs ||\n acceleratedPollingParams?.defaultIntervalMs ||\n DEFAULT_ACCELERATED_POLLING_INTERVAL_MS;\n\n return { countMax, intervalMs };\n}\n\n/**\n * Retrieves the gas fee randomisation parameters.\n *\n * @param messenger - The controller messenger instance.\n * @returns The gas fee randomisation parameters.\n */\nexport function getGasFeeRandomisation(\n messenger: TransactionControllerMessenger,\n): {\n randomisedGasFeeDigits: Record<Hex, number>;\n preservedNumberOfDigits: number | undefined;\n} {\n const featureFlags = getFeatureFlags(messenger);\n\n const gasFeeRandomisation =\n featureFlags?.[FeatureFlag.Transactions]?.gasFeeRandomisation || {};\n\n return {\n randomisedGasFeeDigits: gasFeeRandomisation.randomisedGasFeeDigits || {},\n preservedNumberOfDigits: gasFeeRandomisation.preservedNumberOfDigits,\n };\n}\n\n/**\n * Retrieves the gas estimate fallback for a given chain ID.\n * Defaults to the default gas estimate fallback if not set.\n *\n * @param chainId - The chain ID.\n * @param messenger - The controller messenger instance.\n * @returns The gas estimate fallback.\n */\nexport function getGasEstimateFallback(\n chainId: Hex,\n messenger: TransactionControllerMessenger,\n): {\n fixed?: number;\n percentage: number;\n} {\n const featureFlags = getFeatureFlags(messenger);\n\n const gasEstimateFallbackFlags =\n featureFlags?.[FeatureFlag.Transactions]?.gasEstimateFallback;\n\n const chainFlags = gasEstimateFallbackFlags?.perChainConfig?.[chainId];\n\n const percentage =\n chainFlags?.percentage ??\n gasEstimateFallbackFlags?.default?.percentage ??\n DEFAULT_GAS_ESTIMATE_FALLBACK_BLOCK_PERCENT;\n\n const fixed = chainFlags?.fixed ?? gasEstimateFallbackFlags?.default?.fixed;\n\n return { fixed, percentage };\n}\n\n/**\n * Retrieves the gas buffers for a given chain ID.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID.\n * @param request.isCustomRPC - Whether the network RPC is added by the user.\n * @param request.isUpgradeWithDataToSelf - Whether the transaction is an EIP-7702 upgrade with data to self.\n * @param request.messenger - The controller messenger instance.\n * @returns The gas buffers.\n */\nexport function getGasEstimateBuffer({\n chainId,\n isCustomRPC,\n isUpgradeWithDataToSelf,\n messenger,\n}: {\n chainId: Hex;\n isCustomRPC: boolean;\n isUpgradeWithDataToSelf: boolean;\n messenger: TransactionControllerMessenger;\n}): number {\n const featureFlags = getFeatureFlags(messenger);\n const gasBufferFlags = featureFlags?.[FeatureFlag.GasBuffer];\n const chainFlags = gasBufferFlags?.perChainConfig?.[chainId];\n const chainIncludedRPCBuffer = isCustomRPC ? undefined : chainFlags?.included;\n\n const defaultIncludedRPCBuffer = isCustomRPC\n ? undefined\n : gasBufferFlags?.included;\n\n const upgradeBuffer = isUpgradeWithDataToSelf\n ? chainFlags?.eip7702\n : undefined;\n\n return (\n upgradeBuffer ??\n chainIncludedRPCBuffer ??\n chainFlags?.base ??\n defaultIncludedRPCBuffer ??\n gasBufferFlags?.default ??\n DEFAULT_GAS_ESTIMATE_BUFFER\n );\n}\n\n/**\n * Retrieves the incoming transactions polling interval.\n * Defaults to 4 minutes if not set.\n *\n * @param messenger - The controller messenger instance.\n * @returns The incoming transactions polling interval in milliseconds.\n */\nexport function getIncomingTransactionsPollingInterval(\n messenger: TransactionControllerMessenger,\n): number {\n const featureFlags = getFeatureFlags(messenger);\n\n return (\n featureFlags?.[FeatureFlag.IncomingTransactions]?.pollingIntervalMs ??\n DEFAULT_INCOMING_TRANSACTIONS_POLLING_INTERVAL_MS\n );\n}\n\n/**\n * Retrieves the relevant feature flags from the remote feature flag controller.\n *\n * @param messenger - The messenger instance.\n * @returns The feature flags.\n */\nfunction getFeatureFlags(\n messenger: TransactionControllerMessenger,\n): TransactionControllerFeatureFlags {\n const featureFlags = messenger.call(\n 'RemoteFeatureFlagController:getState',\n ).remoteFeatureFlags;\n\n log('Retrieved feature flags', featureFlags);\n\n return featureFlags as TransactionControllerFeatureFlags;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"feature-flags.mjs","sourceRoot":"","sources":["../../src/utils/feature-flags.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAGrD,OAAO,EAAE,gBAAgB,EAAE,wBAAoB;AAC/C,OAAO,EAAE,kBAAkB,EAAE,oBAAgB;AAC7C,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAG1C,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,qCAAqC,GAAG,EAAE,CAAC;AACjD,MAAM,uCAAuC,GAAG,CAAC,GAAG,IAAI,CAAC;AACzD,MAAM,2CAA2C,GAAG,EAAE,CAAC;AACvD,MAAM,2BAA2B,GAAG,CAAC,CAAC;AACtC,MAAM,iDAAiD,GAAG,IAAI,GAAG,EA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zC,MAAM,YAAY,GAAG,eAAe,CAAC,SAAS,CAAC,CAAC;IAEhD,OAAO,CACL,YAAY,EAAE,CAAC,WAAW,CAAC,oBAAoB,CAAC,EAAE,iBAAiB;QACnE,iDAAiD,CAClD,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,eAAe,CACtB,SAAyC;IAEzC,MAAM,YAAY,GAAG,SAAS,CAAC,IAAI,CACjC,sCAAsC,CACvC,CAAC,kBAAkB,CAAC;IAErB,GAAG,CAAC,yBAAyB,EAAE,YAAY,CAAC,CAAC;IAE7C,OAAO,YAAiD,CAAC;AAC3D,CAAC","sourcesContent":["import { createModuleLogger } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { isValidSignature } from './signature';\nimport { padHexToEvenLength } from './utils';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\n\nconst DEFAULT_BATCH_SIZE_LIMIT = 10;\nconst DEFAULT_ACCELERATED_POLLING_COUNT_MAX = 10;\nconst DEFAULT_ACCELERATED_POLLING_INTERVAL_MS = 3 * 1000;\nconst DEFAULT_GAS_ESTIMATE_FALLBACK_BLOCK_PERCENT = 35;\nconst DEFAULT_GAS_ESTIMATE_BUFFER = 1;\nconst DEFAULT_INCOMING_TRANSACTIONS_POLLING_INTERVAL_MS = 1000 * 60 * 4; // 4 Minutes\n\n/**\n * Feature flags supporting the transaction controller.\n */\nexport enum FeatureFlag {\n EIP7702 = 'confirmations_eip_7702',\n GasBuffer = 'confirmations_gas_buffer',\n IncomingTransactions = 'confirmations_incoming_transactions',\n Transactions = 'confirmations_transactions',\n}\n\ntype GasEstimateFallback = {\n /**\n * The fixed gas estimate fallback for a transaction.\n */\n fixed?: number;\n\n /**\n * The percentage multiplier gas estimate fallback for a transaction.\n */\n percentage?: number;\n};\n\nexport type TransactionControllerFeatureFlags = {\n /** Feature flags to support EIP-7702 / type-4 transactions. */\n [FeatureFlag.EIP7702]?: {\n /**\n * All contracts that support EIP-7702 batch transactions.\n * Keyed by chain ID.\n * First entry in each array is the contract that standard EOAs will be upgraded to.\n */\n contracts?: Record<\n Hex,\n {\n /** Address of the smart contract. */\n address: Hex;\n\n /** Signature to verify the contract is authentic. */\n signature: Hex;\n }[]\n >;\n\n /** Chains enabled for EIP-7702 batch transactions. */\n supportedChains?: Hex[];\n };\n\n /**\n * Buffers added to gas limit estimations.\n * Values are multipliers such as `1.5` meaning 150% of the original gas limit.\n */\n [FeatureFlag.GasBuffer]?: {\n /** Fallback buffer for all chains and transactions. */\n default?: number;\n\n /**\n * Buffer for included network RPCs only and not those added by user.\n * Takes priority over `default`.\n */\n included?: number;\n\n /** Buffers for specific chains. */\n perChainConfig?: {\n [chainId: Hex]: {\n /**\n * Buffer for the chain for all transactions.\n * Takes priority over non-chain `included`.\n */\n base?: number;\n\n /**\n * Buffer if network RPC is included and not added by user.\n * Takes priority over `base`.\n */\n included?: number;\n\n /**\n * Buffer for the chain for EIP-7702 / type 4 transactions only.\n * Only if `data` included and `to` matches `from`.\n * Takes priority over `included` and `base`.\n */\n eip7702?: number;\n };\n };\n };\n\n /** Incoming transaction configuration. */\n [FeatureFlag.IncomingTransactions]?: {\n /** Interval between requests to accounts API to retrieve incoming transactions. */\n pollingIntervalMs?: number;\n };\n\n /** Miscellaneous feature flags to support the transaction controller. */\n [FeatureFlag.Transactions]?: {\n /** Maximum number of transactions that can be in an external batch. */\n batchSizeLimit?: number;\n\n /**\n * Accelerated polling is used to speed up the polling process for\n * transactions that are not yet confirmed.\n */\n acceleratedPolling?: {\n /** Accelerated polling parameters on a per-chain basis. */\n perChainConfig?: {\n [chainId: Hex]: {\n /**\n * Maximum number of polling requests that can be made in a row, before\n * the normal polling resumes.\n */\n countMax?: number;\n\n /** Interval between polling requests in milliseconds. */\n intervalMs?: number;\n };\n };\n\n /** Default `countMax` in case no chain-specific parameter is set. */\n defaultCountMax?: number;\n\n /** Default `intervalMs` in case no chain-specific parameter is set. */\n defaultIntervalMs?: number;\n };\n\n gasFeeRandomisation?: {\n /** Randomised gas fee digits per chainId. */\n randomisedGasFeeDigits?: Record<Hex, number>;\n\n /** Number of digits to preserve for randomised gas fee digits. */\n preservedNumberOfDigits?: number;\n };\n\n /** Gas estimate fallback is used as a fallback in case of failure to obtain the gas estimate values. */\n gasEstimateFallback?: {\n /** Gas estimate fallback per-chain basis. */\n perChainConfig?: {\n [chainId: Hex]: GasEstimateFallback;\n };\n\n /**\n * Default gas estimate fallback.\n * This value is used when no specific gas estimate fallback is found for a chain ID.\n */\n default?: GasEstimateFallback;\n };\n };\n};\n\nconst log = createModuleLogger(projectLogger, 'feature-flags');\n\n/**\n * Retrieves the supported EIP-7702 chains.\n *\n * @param messenger - The controller messenger instance.\n * @returns The supported chains.\n */\nexport function getEIP7702SupportedChains(\n messenger: TransactionControllerMessenger,\n): Hex[] {\n const featureFlags = getFeatureFlags(messenger);\n return featureFlags?.[FeatureFlag.EIP7702]?.supportedChains ?? [];\n}\n\n/**\n * Retrieves the supported EIP-7702 contract addresses for a given chain ID.\n *\n * @param chainId - The chain ID.\n * @param messenger - The controller messenger instance.\n * @param publicKey - The public key used to validate the contract authenticity.\n * @returns The supported contract addresses.\n */\nexport function getEIP7702ContractAddresses(\n chainId: Hex,\n messenger: TransactionControllerMessenger,\n publicKey: Hex,\n): Hex[] {\n const featureFlags = getFeatureFlags(messenger);\n\n const contracts =\n featureFlags?.[FeatureFlag.EIP7702]?.contracts?.[\n chainId.toLowerCase() as Hex\n ] ?? [];\n\n return contracts\n .filter((contract) =>\n isValidSignature(\n [contract.address, padHexToEvenLength(chainId) as Hex],\n contract.signature,\n publicKey,\n ),\n )\n .map((contract) => contract.address);\n}\n\n/**\n * Retrieves the EIP-7702 upgrade contract address.\n *\n * @param chainId - The chain ID.\n * @param messenger - The controller messenger instance.\n * @param publicKey - The public key used to validate the contract authenticity.\n * @returns The upgrade contract address.\n */\nexport function getEIP7702UpgradeContractAddress(\n chainId: Hex,\n messenger: TransactionControllerMessenger,\n publicKey: Hex,\n): Hex | undefined {\n return getEIP7702ContractAddresses(chainId, messenger, publicKey)?.[0];\n}\n\n/**\n * Retrieves the batch size limit.\n * Defaults to 10 if not set.\n *\n * @param messenger - The controller messenger instance.\n * @returns The batch size limit.\n */\nexport function getBatchSizeLimit(\n messenger: TransactionControllerMessenger,\n): number {\n const featureFlags = getFeatureFlags(messenger);\n return (\n featureFlags?.[FeatureFlag.Transactions]?.batchSizeLimit ??\n DEFAULT_BATCH_SIZE_LIMIT\n );\n}\n\n/**\n * Retrieves the accelerated polling parameters for a given chain ID.\n *\n * @param chainId - The chain ID.\n * @param messenger - The controller messenger instance.\n * @returns The accelerated polling parameters: `countMax` and `intervalMs`.\n */\nexport function getAcceleratedPollingParams(\n chainId: Hex,\n messenger: TransactionControllerMessenger,\n): { countMax: number; intervalMs: number } {\n const featureFlags = getFeatureFlags(messenger);\n\n const acceleratedPollingParams =\n featureFlags?.[FeatureFlag.Transactions]?.acceleratedPolling;\n\n const countMax =\n acceleratedPollingParams?.perChainConfig?.[chainId]?.countMax ||\n acceleratedPollingParams?.defaultCountMax ||\n DEFAULT_ACCELERATED_POLLING_COUNT_MAX;\n\n const intervalMs =\n acceleratedPollingParams?.perChainConfig?.[chainId]?.intervalMs ||\n acceleratedPollingParams?.defaultIntervalMs ||\n DEFAULT_ACCELERATED_POLLING_INTERVAL_MS;\n\n return { countMax, intervalMs };\n}\n\n/**\n * Retrieves the gas fee randomisation parameters.\n *\n * @param messenger - The controller messenger instance.\n * @returns The gas fee randomisation parameters.\n */\nexport function getGasFeeRandomisation(\n messenger: TransactionControllerMessenger,\n): {\n randomisedGasFeeDigits: Record<Hex, number>;\n preservedNumberOfDigits: number | undefined;\n} {\n const featureFlags = getFeatureFlags(messenger);\n\n const gasFeeRandomisation =\n featureFlags?.[FeatureFlag.Transactions]?.gasFeeRandomisation || {};\n\n return {\n randomisedGasFeeDigits: gasFeeRandomisation.randomisedGasFeeDigits || {},\n preservedNumberOfDigits: gasFeeRandomisation.preservedNumberOfDigits,\n };\n}\n\n/**\n * Retrieves the gas estimate fallback for a given chain ID.\n * Defaults to the default gas estimate fallback if not set.\n *\n * @param chainId - The chain ID.\n * @param messenger - The controller messenger instance.\n * @returns The gas estimate fallback.\n */\nexport function getGasEstimateFallback(\n chainId: Hex,\n messenger: TransactionControllerMessenger,\n): {\n fixed?: number;\n percentage: number;\n} {\n const featureFlags = getFeatureFlags(messenger);\n\n const gasEstimateFallbackFlags =\n featureFlags?.[FeatureFlag.Transactions]?.gasEstimateFallback;\n\n const chainFlags = gasEstimateFallbackFlags?.perChainConfig?.[chainId];\n\n const percentage =\n chainFlags?.percentage ??\n gasEstimateFallbackFlags?.default?.percentage ??\n DEFAULT_GAS_ESTIMATE_FALLBACK_BLOCK_PERCENT;\n\n const fixed = chainFlags?.fixed ?? gasEstimateFallbackFlags?.default?.fixed;\n\n return { fixed, percentage };\n}\n\n/**\n * Retrieves the gas buffers for a given chain ID.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID.\n * @param request.isCustomRPC - Whether the network RPC is added by the user.\n * @param request.isUpgradeWithDataToSelf - Whether the transaction is an EIP-7702 upgrade with data to self.\n * @param request.messenger - The controller messenger instance.\n * @returns The gas buffers.\n */\nexport function getGasEstimateBuffer({\n chainId,\n isCustomRPC,\n isUpgradeWithDataToSelf,\n messenger,\n}: {\n chainId: Hex;\n isCustomRPC: boolean;\n isUpgradeWithDataToSelf: boolean;\n messenger: TransactionControllerMessenger;\n}): number {\n const featureFlags = getFeatureFlags(messenger);\n const gasBufferFlags = featureFlags?.[FeatureFlag.GasBuffer];\n const chainFlags = gasBufferFlags?.perChainConfig?.[chainId];\n const chainIncludedRPCBuffer = isCustomRPC ? undefined : chainFlags?.included;\n\n const defaultIncludedRPCBuffer = isCustomRPC\n ? undefined\n : gasBufferFlags?.included;\n\n const upgradeBuffer = isUpgradeWithDataToSelf\n ? chainFlags?.eip7702\n : undefined;\n\n return (\n upgradeBuffer ??\n chainIncludedRPCBuffer ??\n chainFlags?.base ??\n defaultIncludedRPCBuffer ??\n gasBufferFlags?.default ??\n DEFAULT_GAS_ESTIMATE_BUFFER\n );\n}\n\n/**\n * Retrieves the incoming transactions polling interval.\n * Defaults to 4 minutes if not set.\n *\n * @param messenger - The controller messenger instance.\n * @returns The incoming transactions polling interval in milliseconds.\n */\nexport function getIncomingTransactionsPollingInterval(\n messenger: TransactionControllerMessenger,\n): number {\n const featureFlags = getFeatureFlags(messenger);\n\n return (\n featureFlags?.[FeatureFlag.IncomingTransactions]?.pollingIntervalMs ??\n DEFAULT_INCOMING_TRANSACTIONS_POLLING_INTERVAL_MS\n );\n}\n\n/**\n * Retrieves the relevant feature flags from the remote feature flag controller.\n *\n * @param messenger - The messenger instance.\n * @returns The feature flags.\n */\nfunction getFeatureFlags(\n messenger: TransactionControllerMessenger,\n): TransactionControllerFeatureFlags {\n const featureFlags = messenger.call(\n 'RemoteFeatureFlagController:getState',\n ).remoteFeatureFlags;\n\n log('Retrieved feature flags', featureFlags);\n\n return featureFlags as TransactionControllerFeatureFlags;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"first-time-interaction.cjs","sourceRoot":"","sources":["../../src/utils/first-time-interaction.ts"],"names":[],"mappings":";;;AAEA,2CAA8C;AAE9C,6DAA2D;AAC3D,iDAA+C;AAC/C,
|
|
1
|
+
{"version":3,"file":"first-time-interaction.cjs","sourceRoot":"","sources":["../../src/utils/first-time-interaction.ts"],"names":[],"mappings":";;;AAEA,2CAA8C;AAE9C,6DAA2D;AAC3D,iDAA+C;AAC/C,0DAAoE;AAEpE,0CAAiD;AACjD,wCAA2C;AAmB3C;;;;;;;;;;;;GAYG;AACI,KAAK,UAAU,0BAA0B,CAAC,EAC/C,oBAAoB,EACpB,cAAc,EACd,6BAA6B,EAC7B,KAAK,EACL,YAAY,EACZ,eAAe,EACf,iBAAiB,GACiB;IAClC,IAAI,CAAC,6BAA6B,EAAE,EAAE,CAAC;QACrC,OAAO;IACT,CAAC;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3B,EAAE,IAAI,EAAE,8BAA8B,EAAE,aAAa,EAAE,YAAY,EAAE,EACrE,GAAG,EAAE,CAAC,IAAA,4CAA6B,EAAC,OAAO,CAAC,CAC7C,CAAC;QAEF,MAAM,sBAAsB,GAC1B,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC;QAEhD,MAAM,oBAAoB,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;QAE3D,wBAAwB;QACxB,IAAI,CAAC,oBAAoB,EAAE,CAAC;YAC1B,IAAA,sBAAG,EACD,+DAA+D,EAC/D,aAAa,CACd,CAAC;YACF,OAAO;QACT,CAAC;QAED,iBAAiB,CACf;YACE,aAAa;YACb,IAAI,EAAE,8EAA8E;SACrF,EACD,CAAC,MAAM,EAAE,EAAE;YACT,MAAM,CAAC,sBAAsB,GAAG,sBAAsB,CAAC;QACzD,CAAC,CACF,CAAC;QAEF,IAAA,sBAAG,EAAC,gCAAgC,EAAE,aAAa,EAAE;YACnD,sBAAsB;SACvB,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAA,sBAAG,EACD,qFAAqF,EACrF,KAAK,CACN,CAAC;IACJ,CAAC;AACH,CAAC;AApGD,gEAoGC","sourcesContent":["import type { TransactionDescription } from '@ethersproject/abi';\nimport type { TraceContext, TraceCallback } from '@metamask/controller-utils';\nimport { hexToNumber } from '@metamask/utils';\n\nimport { decodeTransactionData } from './transaction-type';\nimport { validateParamTo } from './validation';\nimport { getAccountAddressRelationship } from '../api/accounts-api';\nimport type { GetAccountAddressRelationshipRequest } from '../api/accounts-api';\nimport { projectLogger as log } from '../logger';\nimport { TransactionType } from '../types';\nimport type { TransactionMeta } from '../types';\n\ntype UpdateFirstTimeInteractionRequest = {\n existingTransactions: TransactionMeta[];\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n isFirstTimeInteractionEnabled: () => boolean;\n trace: TraceCallback;\n traceContext?: TraceContext;\n transactionMeta: TransactionMeta;\n updateTransaction: (\n updateParams: {\n transactionId: string;\n note: string;\n },\n updater: (txMeta: TransactionMeta) => void,\n ) => void;\n};\n\n/**\n * Updates the first-time interaction status for a transaction.\n *\n * @param params - The parameters for updating first time interaction.\n * @param params.existingTransactions - The existing transactions.\n * @param params.getTransaction - Function to get a transaction by ID.\n * @param params.isFirstTimeInteractionEnabled - The function to check if first time interaction is enabled.\n * @param params.trace - The trace callback.\n * @param params.traceContext - The trace context.\n * @param params.transactionMeta - The transaction meta object.\n * @param params.updateTransaction - Function to update transaction internal state.\n * @returns Promise that resolves when the update is complete.\n */\nexport async function updateFirstTimeInteraction({\n existingTransactions,\n getTransaction,\n isFirstTimeInteractionEnabled,\n trace,\n traceContext,\n transactionMeta,\n updateTransaction,\n}: UpdateFirstTimeInteractionRequest): Promise<void> {\n if (!isFirstTimeInteractionEnabled()) {\n return;\n }\n\n const {\n chainId,\n id: transactionId,\n txParams: { data, from, to },\n type,\n } = transactionMeta;\n\n let recipient;\n if (\n data &&\n [\n TransactionType.tokenMethodTransfer,\n TransactionType.tokenMethodTransferFrom,\n ].includes(type as TransactionType)\n ) {\n const parsedData = decodeTransactionData(data) as TransactionDescription;\n // _to is for ERC20, ERC721 and USDC\n // to is for ERC1155\n recipient = parsedData?.args?._to || parsedData?.args?.to;\n }\n\n if (!recipient) {\n // Use as fallback if no recipient is found from decode or no data is present\n recipient = to;\n }\n\n const request: GetAccountAddressRelationshipRequest = {\n chainId: hexToNumber(chainId),\n to: recipient as string,\n from,\n };\n\n validateParamTo(recipient);\n\n const existingTransaction = existingTransactions.find(\n (tx) =>\n tx.chainId === chainId &&\n tx.txParams.from.toLowerCase() === from.toLowerCase() &&\n tx.txParams.to?.toLowerCase() === to?.toLowerCase() &&\n tx.id !== transactionId,\n );\n\n // Check if there is an existing transaction with the same from, to, and chainId\n // else we continue to check the account address relationship from API\n if (existingTransaction) {\n return;\n }\n\n try {\n const { count } = await trace(\n { name: 'Account Address Relationship', parentContext: traceContext },\n () => getAccountAddressRelationship(request),\n );\n\n const isFirstTimeInteraction =\n count === undefined ? undefined : count === 0;\n\n const finalTransactionMeta = getTransaction(transactionId);\n\n /* istanbul ignore if */\n if (!finalTransactionMeta) {\n log(\n 'Cannot update first time interaction as transaction not found',\n transactionId,\n );\n return;\n }\n\n updateTransaction(\n {\n transactionId,\n note: 'TransactionController#updateFirstInteraction - Update first time interaction',\n },\n (txMeta) => {\n txMeta.isFirstTimeInteraction = isFirstTimeInteraction;\n },\n );\n\n log('Updated first time interaction', transactionId, {\n isFirstTimeInteraction,\n });\n } catch (error) {\n log(\n 'Error fetching account address relationship, skipping first time interaction update',\n error,\n );\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { TraceContext, TraceCallback } from "@metamask/controller-utils";
|
|
2
|
-
import {
|
|
2
|
+
import type { TransactionMeta } from "../types.cjs";
|
|
3
3
|
type UpdateFirstTimeInteractionRequest = {
|
|
4
4
|
existingTransactions: TransactionMeta[];
|
|
5
5
|
getTransaction: (transactionId: string) => TransactionMeta | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"first-time-interaction.d.cts","sourceRoot":"","sources":["../../src/utils/first-time-interaction.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,mCAAmC;
|
|
1
|
+
{"version":3,"file":"first-time-interaction.d.cts","sourceRoot":"","sources":["../../src/utils/first-time-interaction.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,mCAAmC;AAS9E,OAAO,KAAK,EAAE,eAAe,EAAE,qBAAiB;AAEhD,KAAK,iCAAiC,GAAG;IACvC,oBAAoB,EAAE,eAAe,EAAE,CAAC;IACxC,cAAc,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,eAAe,GAAG,SAAS,CAAC;IACvE,6BAA6B,EAAE,MAAM,OAAO,CAAC;IAC7C,KAAK,EAAE,aAAa,CAAC;IACrB,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,eAAe,EAAE,eAAe,CAAC;IACjC,iBAAiB,EAAE,CACjB,YAAY,EAAE;QACZ,aAAa,EAAE,MAAM,CAAC;QACtB,IAAI,EAAE,MAAM,CAAC;KACd,EACD,OAAO,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,KACvC,IAAI,CAAC;CACX,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAsB,0BAA0B,CAAC,EAC/C,oBAAoB,EACpB,cAAc,EACd,6BAA6B,EAC7B,KAAK,EACL,YAAY,EACZ,eAAe,EACf,iBAAiB,GAClB,EAAE,iCAAiC,GAAG,OAAO,CAAC,IAAI,CAAC,CA4FnD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { TraceContext, TraceCallback } from "@metamask/controller-utils";
|
|
2
|
-
import {
|
|
2
|
+
import type { TransactionMeta } from "../types.mjs";
|
|
3
3
|
type UpdateFirstTimeInteractionRequest = {
|
|
4
4
|
existingTransactions: TransactionMeta[];
|
|
5
5
|
getTransaction: (transactionId: string) => TransactionMeta | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"first-time-interaction.d.mts","sourceRoot":"","sources":["../../src/utils/first-time-interaction.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,mCAAmC;
|
|
1
|
+
{"version":3,"file":"first-time-interaction.d.mts","sourceRoot":"","sources":["../../src/utils/first-time-interaction.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,mCAAmC;AAS9E,OAAO,KAAK,EAAE,eAAe,EAAE,qBAAiB;AAEhD,KAAK,iCAAiC,GAAG;IACvC,oBAAoB,EAAE,eAAe,EAAE,CAAC;IACxC,cAAc,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,eAAe,GAAG,SAAS,CAAC;IACvE,6BAA6B,EAAE,MAAM,OAAO,CAAC;IAC7C,KAAK,EAAE,aAAa,CAAC;IACrB,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,eAAe,EAAE,eAAe,CAAC;IACjC,iBAAiB,EAAE,CACjB,YAAY,EAAE;QACZ,aAAa,EAAE,MAAM,CAAC;QACtB,IAAI,EAAE,MAAM,CAAC;KACd,EACD,OAAO,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,KACvC,IAAI,CAAC;CACX,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAsB,0BAA0B,CAAC,EAC/C,oBAAoB,EACpB,cAAc,EACd,6BAA6B,EAC7B,KAAK,EACL,YAAY,EACZ,eAAe,EACf,iBAAiB,GAClB,EAAE,iCAAiC,GAAG,OAAO,CAAC,IAAI,CAAC,CA4FnD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"first-time-interaction.mjs","sourceRoot":"","sources":["../../src/utils/first-time-interaction.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAE9C,OAAO,EAAE,qBAAqB,EAAE,+BAA2B;AAC3D,OAAO,EAAE,eAAe,EAAE,yBAAqB;AAC/C,OAAO,
|
|
1
|
+
{"version":3,"file":"first-time-interaction.mjs","sourceRoot":"","sources":["../../src/utils/first-time-interaction.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAE9C,OAAO,EAAE,qBAAqB,EAAE,+BAA2B;AAC3D,OAAO,EAAE,eAAe,EAAE,yBAAqB;AAC/C,OAAO,EAAE,6BAA6B,EAAE,gCAA4B;AAEpE,OAAO,EAAE,aAAa,IAAI,GAAG,EAAE,sBAAkB;AACjD,OAAO,EAAE,eAAe,EAAE,qBAAiB;AAmB3C;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAAC,EAC/C,oBAAoB,EACpB,cAAc,EACd,6BAA6B,EAC7B,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C;QACxB,OAAO;IACT,CAAC;IAED,IAAI,CAAC;QACH,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,KAAK,CAC3B,EAAE,IAAI,EAAE,8BAA8B,EAAE,aAAa,EAAE,YAAY,EAAE,EACrE,GAAG,EAAE,CAAC,6BAA6B,CAAC,OAAO,CAAC,CAC7C,CAAC;QAEF,MAAM,sBAAsB,GAC1B,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC;QAEhD,MAAM,oBAAoB,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;QAE3D,wBAAwB;QACxB,IAAI,CAAC,oBAAoB,EAAE,CAAC;YAC1B,GAAG,CACD,+DAA+D,EAC/D,aAAa,CACd,CAAC;YACF,OAAO;QACT,CAAC;QAED,iBAAiB,CACf;YACE,aAAa;YACb,IAAI,EAAE,8EAA8E;SACrF,EACD,CAAC,MAAM,EAAE,EAAE;YACT,MAAM,CAAC,sBAAsB,GAAG,sBAAsB,CAAC;QACzD,CAAC,CACF,CAAC;QAEF,GAAG,CAAC,gCAAgC,EAAE,aAAa,EAAE;YACnD,sBAAsB;SACvB,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CACD,qFAAqF,EACrF,KAAK,CACN,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type { TransactionDescription } from '@ethersproject/abi';\nimport type { TraceContext, TraceCallback } from '@metamask/controller-utils';\nimport { hexToNumber } from '@metamask/utils';\n\nimport { decodeTransactionData } from './transaction-type';\nimport { validateParamTo } from './validation';\nimport { getAccountAddressRelationship } from '../api/accounts-api';\nimport type { GetAccountAddressRelationshipRequest } from '../api/accounts-api';\nimport { projectLogger as log } from '../logger';\nimport { TransactionType } from '../types';\nimport type { TransactionMeta } from '../types';\n\ntype UpdateFirstTimeInteractionRequest = {\n existingTransactions: TransactionMeta[];\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n isFirstTimeInteractionEnabled: () => boolean;\n trace: TraceCallback;\n traceContext?: TraceContext;\n transactionMeta: TransactionMeta;\n updateTransaction: (\n updateParams: {\n transactionId: string;\n note: string;\n },\n updater: (txMeta: TransactionMeta) => void,\n ) => void;\n};\n\n/**\n * Updates the first-time interaction status for a transaction.\n *\n * @param params - The parameters for updating first time interaction.\n * @param params.existingTransactions - The existing transactions.\n * @param params.getTransaction - Function to get a transaction by ID.\n * @param params.isFirstTimeInteractionEnabled - The function to check if first time interaction is enabled.\n * @param params.trace - The trace callback.\n * @param params.traceContext - The trace context.\n * @param params.transactionMeta - The transaction meta object.\n * @param params.updateTransaction - Function to update transaction internal state.\n * @returns Promise that resolves when the update is complete.\n */\nexport async function updateFirstTimeInteraction({\n existingTransactions,\n getTransaction,\n isFirstTimeInteractionEnabled,\n trace,\n traceContext,\n transactionMeta,\n updateTransaction,\n}: UpdateFirstTimeInteractionRequest): Promise<void> {\n if (!isFirstTimeInteractionEnabled()) {\n return;\n }\n\n const {\n chainId,\n id: transactionId,\n txParams: { data, from, to },\n type,\n } = transactionMeta;\n\n let recipient;\n if (\n data &&\n [\n TransactionType.tokenMethodTransfer,\n TransactionType.tokenMethodTransferFrom,\n ].includes(type as TransactionType)\n ) {\n const parsedData = decodeTransactionData(data) as TransactionDescription;\n // _to is for ERC20, ERC721 and USDC\n // to is for ERC1155\n recipient = parsedData?.args?._to || parsedData?.args?.to;\n }\n\n if (!recipient) {\n // Use as fallback if no recipient is found from decode or no data is present\n recipient = to;\n }\n\n const request: GetAccountAddressRelationshipRequest = {\n chainId: hexToNumber(chainId),\n to: recipient as string,\n from,\n };\n\n validateParamTo(recipient);\n\n const existingTransaction = existingTransactions.find(\n (tx) =>\n tx.chainId === chainId &&\n tx.txParams.from.toLowerCase() === from.toLowerCase() &&\n tx.txParams.to?.toLowerCase() === to?.toLowerCase() &&\n tx.id !== transactionId,\n );\n\n // Check if there is an existing transaction with the same from, to, and chainId\n // else we continue to check the account address relationship from API\n if (existingTransaction) {\n return;\n }\n\n try {\n const { count } = await trace(\n { name: 'Account Address Relationship', parentContext: traceContext },\n () => getAccountAddressRelationship(request),\n );\n\n const isFirstTimeInteraction =\n count === undefined ? undefined : count === 0;\n\n const finalTransactionMeta = getTransaction(transactionId);\n\n /* istanbul ignore if */\n if (!finalTransactionMeta) {\n log(\n 'Cannot update first time interaction as transaction not found',\n transactionId,\n );\n return;\n }\n\n updateTransaction(\n {\n transactionId,\n note: 'TransactionController#updateFirstInteraction - Update first time interaction',\n },\n (txMeta) => {\n txMeta.isFirstTimeInteraction = isFirstTimeInteraction;\n },\n );\n\n log('Updated first time interaction', transactionId, {\n isFirstTimeInteraction,\n });\n } catch (error) {\n log(\n 'Error fetching account address relationship, skipping first time interaction update',\n error,\n );\n }\n}\n"]}
|
|
@@ -34,12 +34,12 @@ async function getGasFeeTokens({ chainId, isEIP7702GasFeeTokensEnabled, messenge
|
|
|
34
34
|
const with7702 = is7702GasFeeTokensEnabled && (0, eip7702_1.doesChainSupportEIP7702)(chainId, messenger);
|
|
35
35
|
let authorizationList = authorizationListRequest?.map((authorization) => ({
|
|
36
36
|
address: authorization.address,
|
|
37
|
-
from
|
|
37
|
+
from,
|
|
38
38
|
}));
|
|
39
39
|
if (with7702 && !delegationAddress && !authorizationList) {
|
|
40
40
|
authorizationList = buildAuthorizationList({
|
|
41
41
|
chainId,
|
|
42
|
-
from
|
|
42
|
+
from,
|
|
43
43
|
messenger,
|
|
44
44
|
publicKeyEIP7702,
|
|
45
45
|
});
|
|
@@ -163,7 +163,7 @@ function buildAuthorizationList({ chainId, from, messenger, publicKeyEIP7702, })
|
|
|
163
163
|
return [
|
|
164
164
|
{
|
|
165
165
|
address: upgradeAddress,
|
|
166
|
-
from
|
|
166
|
+
from,
|
|
167
167
|
},
|
|
168
168
|
];
|
|
169
169
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas-fee-tokens.cjs","sourceRoot":"","sources":["../../src/utils/gas-f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,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YACzC,MAAM,EAAE,QAAQ,CAAC,kBAAkB;YACnC,OAAO,EAAE,QAAQ,CAAC,mBAAmB;YACrC,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,QAAQ;YACjC,GAAG,EAAE,QAAQ,CAAC,UAAU;YACxB,GAAG,EAAE,QAAQ,CAAC,GAAG;YACjB,WAAW,EAAE,QAAQ,CAAC,gBAAgB;YACtC,YAAY,EAAE,QAAQ,CAAC,YAAY;YACnC,oBAAoB,EAAE,QAAQ,CAAC,oBAAoB;YACnD,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,SAAS,EAAE,QAAQ,CAAC,YAAY;YAChC,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC,MAAM;YAC7B,YAAY,EAAE,QAAQ,CAAC,KAAK,CAAC,OAAO;SACrC,CAAC,CAAC;QACH,iBAAiB;KAClB,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,sBAAsB,CAAC,EAC9B,OAAO,EACP,IAAI,EACJ,SAAS,EACT,gBAAgB,GAMjB;IACC,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,MAAM,sBAAS,CAAC,QAAQ,CAAC,iCAAuB,CAAC,CAAC;IACpD,CAAC;IAED,MAAM,cAAc,GAAG,IAAA,gDAAgC,EACrD,OAAO,EACP,SAAS,EACT,gBAAgB,CACjB,CAAC;IAEF,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,MAAM,sBAAS,CAAC,QAAQ,CAAC,yCAAiC,CAAC,CAAC;IAC9D,CAAC;IAED,OAAO;QACL;YACE,OAAO,EAAE,cAAc;YACvB,IAAI,EAAE,IAAW;SAClB;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type EthQuery from '@metamask/eth-query';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { isNativeBalanceSufficientForGas } from './balance';\nimport { ERROR_MESSAGE_NO_UPGRADE_CONTRACT } from './batch';\nimport { ERROR_MESSGE_PUBLIC_KEY, doesChainSupportEIP7702 } from './eip7702';\nimport { getEIP7702UpgradeContractAddress } from './feature-flags';\nimport type {\n GasFeeToken,\n TransactionControllerMessenger,\n TransactionMeta,\n} from '..';\nimport type { SimulationRequestTransaction } from '../api/simulation-api';\nimport {\n simulateTransactions,\n type SimulationResponse,\n type SimulationResponseTransaction,\n} from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { GetSimulationConfig } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'gas-fee-tokens');\n\nexport type GetGasFeeTokensRequest = {\n chainId: Hex;\n isEIP7702GasFeeTokensEnabled: (\n transactionMeta: TransactionMeta,\n ) => Promise<boolean>;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n transactionMeta: TransactionMeta;\n};\n\n/**\n * Get gas fee tokens for a transaction.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID of the transaction.\n * @param request.isEIP7702GasFeeTokensEnabled - Callback to check if EIP-7702 gas fee tokens are enabled.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - Public key to validate EIP-7702 contract signatures.\n * @param request.transactionMeta - The transaction metadata.\n * @param request.getSimulationConfig - Optional transaction simulation parameters.\n * @returns An array of gas fee tokens.\n */\nexport async function getGasFeeTokens({\n chainId,\n isEIP7702GasFeeTokensEnabled,\n messenger,\n publicKeyEIP7702,\n transactionMeta,\n getSimulationConfig,\n}: GetGasFeeTokensRequest) {\n const { delegationAddress, txParams } = transactionMeta;\n const { authorizationList: authorizationListRequest } = txParams;\n const data = txParams.data as Hex;\n const from = txParams.from as Hex;\n const to = txParams.to as Hex;\n const value = txParams.value as Hex;\n\n log('Request', { chainId, txParams });\n\n const is7702GasFeeTokensEnabled =\n await isEIP7702GasFeeTokensEnabled(transactionMeta);\n\n const with7702 =\n is7702GasFeeTokensEnabled && doesChainSupportEIP7702(chainId, messenger);\n\n let authorizationList:\n | SimulationRequestTransaction['authorizationList']\n | undefined = authorizationListRequest?.map((authorization) => ({\n address: authorization.address,\n from: from as Hex,\n }));\n\n if (with7702 && !delegationAddress && !authorizationList) {\n authorizationList = buildAuthorizationList({\n chainId,\n from: from as Hex,\n messenger,\n publicKeyEIP7702,\n });\n }\n\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n authorizationList,\n data,\n from,\n to,\n value,\n },\n ],\n suggestFees: {\n withTransfer: true,\n withFeeTransfer: true,\n with7702,\n },\n });\n\n log('Response', response);\n\n const result = parseGasFeeTokens(response);\n\n log('Gas fee tokens', result);\n\n return result;\n } catch (error) {\n log('Failed to gas fee tokens', error);\n return { gasFeeTokens: [], isGasFeeSponsored: false };\n }\n}\n\n/**\n * Check and update gas fee token selection before publishing a transaction.\n *\n * @param request - Request object.\n * @param request.ethQuery - EthQuery instance.\n * @param request.fetchGasFeeTokens - Function to fetch gas fee tokens.\n * @param request.transaction - Transaction metadata.\n * @param request.updateTransaction - Function to update the transaction.\n */\nexport async function checkGasFeeTokenBeforePublish({\n ethQuery,\n fetchGasFeeTokens,\n transaction,\n updateTransaction,\n}: {\n ethQuery: EthQuery;\n fetchGasFeeTokens: (transaction: TransactionMeta) => Promise<GasFeeToken[]>;\n transaction: TransactionMeta;\n updateTransaction: (\n transactionId: string,\n fn: (tx: TransactionMeta) => void,\n ) => void;\n}) {\n const { isGasFeeTokenIgnoredIfBalance, selectedGasFeeToken } = transaction;\n\n if (!selectedGasFeeToken || !isGasFeeTokenIgnoredIfBalance) {\n return;\n }\n\n log('Checking gas fee token before publish', { selectedGasFeeToken });\n\n const hasNativeBalance = await isNativeBalanceSufficientForGas(\n transaction,\n ethQuery,\n );\n\n if (hasNativeBalance) {\n log(\n 'Ignoring gas fee token before publish due to sufficient native balance',\n );\n\n updateTransaction(transaction.id, (tx) => {\n tx.isExternalSign = false;\n tx.selectedGasFeeToken = undefined;\n });\n\n return;\n }\n\n const gasFeeTokens = await fetchGasFeeTokens({\n ...transaction,\n isExternalSign: true,\n });\n\n updateTransaction(transaction.id, (tx) => {\n tx.gasFeeTokens = gasFeeTokens;\n tx.isExternalSign = true;\n tx.txParams.nonce = undefined;\n });\n\n log('Updated gas fee tokens before publish', gasFeeTokens);\n\n if (\n !gasFeeTokens?.some(\n (t) => t.tokenAddress.toLowerCase() === selectedGasFeeToken.toLowerCase(),\n )\n ) {\n throw new Error('Gas fee token not found and insufficient native balance');\n }\n\n log('Publishing with selected gas fee token', { selectedGasFeeToken });\n}\n\n/**\n * Extract gas fee tokens from a simulation response.\n *\n * @param response - The simulation response.\n * @returns gasFeeTokens: An array of gas fee tokens. isGasFeeSponsored: Whether the transaction is sponsored\n */\nfunction parseGasFeeTokens(response: SimulationResponse): {\n gasFeeTokens: GasFeeToken[];\n isGasFeeSponsored: boolean;\n} {\n const feeLevel = response.transactions?.[0]\n ?.fees?.[0] as Required<SimulationResponseTransaction>['fees'][0];\n\n const isGasFeeSponsored = response.sponsorship?.isSponsored ?? false;\n\n const tokenFees = feeLevel?.tokenFees ?? [];\n\n return {\n gasFeeTokens: tokenFees.map((tokenFee) => ({\n amount: tokenFee.balanceNeededToken,\n balance: tokenFee.currentBalanceToken,\n decimals: tokenFee.token.decimals,\n fee: tokenFee.serviceFee,\n gas: feeLevel.gas,\n gasTransfer: tokenFee.transferEstimate,\n maxFeePerGas: feeLevel.maxFeePerGas,\n maxPriorityFeePerGas: feeLevel.maxPriorityFeePerGas,\n rateWei: tokenFee.rateWei,\n recipient: tokenFee.feeRecipient,\n symbol: tokenFee.token.symbol,\n tokenAddress: tokenFee.token.address,\n })),\n isGasFeeSponsored,\n };\n}\n\n/**\n * Generate the authorization list for the request.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID.\n * @param request.from - The sender's address.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - The public key for EIP-7702.\n * @returns The authorization list.\n */\nfunction buildAuthorizationList({\n chainId,\n from,\n messenger,\n publicKeyEIP7702,\n}: {\n chainId: Hex;\n from: Hex;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n}): SimulationRequestTransaction['authorizationList'] | undefined {\n if (!publicKeyEIP7702) {\n throw rpcErrors.internal(ERROR_MESSGE_PUBLIC_KEY);\n }\n\n const upgradeAddress = getEIP7702UpgradeContractAddress(\n chainId,\n messenger,\n publicKeyEIP7702,\n );\n\n if (!upgradeAddress) {\n throw rpcErrors.internal(ERROR_MESSAGE_NO_UPGRADE_CONTRACT);\n }\n\n return [\n {\n address: upgradeAddress,\n from: from as Hex,\n },\n ];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gas-fee-tokens.cjs","sourceRoot":"","sources":["../../src/utils/gas-fee-tokens.ts"],"names":[],"mappings":";;;AACA,qDAAiD;AAEjD,2CAAqD;AAErD,2CAA4D;AAC5D,uCAA4D;AAC5D,2CAA6E;AAC7E,uDAAmE;AAMnE,8DAA6D;AAM7D,0CAA0C;AAG1C,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,gBAAgB,CAAC,CAAC;AAahE;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,eAAe,CAAC,EACpC,OAAO,EACP,4BAA4B,EAC5B,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,mBAAmB,GACI;IACvB,MAAM,EAAE,iBAAiB,EAAE,QAAQ,EAAE,GAAG,eAAe,CAAC;IACxD,MAAM,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,GAAG,QAAQ,CAAC;IACjE,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAW,CAAC;IAClC,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAW,CAAC;IAClC,MAAM,EAAE,GAAG,QAAQ,CAAC,EAAS,CAAC;IAC9B,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAY,CAAC;IAEpC,GAAG,CAAC,SAAS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B,EAAE,CAAC;QACtB,MAAM,sBAAS,CAAC,QAAQ,CAAC,iCAAuB,CAAC,CAAC;IACpD,CAAC;IAED,MAAM,cAAc,GAAG,IAAA,gDAAgC,EACrD,OAAO,EACP,SAAS,EACT,gBAAgB,CACjB,CAAC;IAEF,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,MAAM,sBAAS,CAAC,QAAQ,CAAC,yCAAiC,CAAC,CAAC;IAC9D,CAAC;IAED,OAAO;QACL;YACE,OAAO,EAAE,cAAc;YACvB,IAAI;SACL;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type EthQuery from '@metamask/eth-query';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { isNativeBalanceSufficientForGas } from './balance';\nimport { ERROR_MESSAGE_NO_UPGRADE_CONTRACT } from './batch';\nimport { ERROR_MESSGE_PUBLIC_KEY, doesChainSupportEIP7702 } from './eip7702';\nimport { getEIP7702UpgradeContractAddress } from './feature-flags';\nimport type {\n GasFeeToken,\n TransactionControllerMessenger,\n TransactionMeta,\n} from '..';\nimport { simulateTransactions } from '../api/simulation-api';\nimport type { SimulationRequestTransaction } from '../api/simulation-api';\nimport type {\n SimulationResponse,\n SimulationResponseTransaction,\n} from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { GetSimulationConfig } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'gas-fee-tokens');\n\nexport type GetGasFeeTokensRequest = {\n chainId: Hex;\n isEIP7702GasFeeTokensEnabled: (\n transactionMeta: TransactionMeta,\n ) => Promise<boolean>;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n transactionMeta: TransactionMeta;\n};\n\n/**\n * Get gas fee tokens for a transaction.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID of the transaction.\n * @param request.isEIP7702GasFeeTokensEnabled - Callback to check if EIP-7702 gas fee tokens are enabled.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - Public key to validate EIP-7702 contract signatures.\n * @param request.transactionMeta - The transaction metadata.\n * @param request.getSimulationConfig - Optional transaction simulation parameters.\n * @returns An array of gas fee tokens.\n */\nexport async function getGasFeeTokens({\n chainId,\n isEIP7702GasFeeTokensEnabled,\n messenger,\n publicKeyEIP7702,\n transactionMeta,\n getSimulationConfig,\n}: GetGasFeeTokensRequest) {\n const { delegationAddress, txParams } = transactionMeta;\n const { authorizationList: authorizationListRequest } = txParams;\n const data = txParams.data as Hex;\n const from = txParams.from as Hex;\n const to = txParams.to as Hex;\n const value = txParams.value as Hex;\n\n log('Request', { chainId, txParams });\n\n const is7702GasFeeTokensEnabled =\n await isEIP7702GasFeeTokensEnabled(transactionMeta);\n\n const with7702 =\n is7702GasFeeTokensEnabled && doesChainSupportEIP7702(chainId, messenger);\n\n let authorizationList:\n | SimulationRequestTransaction['authorizationList']\n | undefined = authorizationListRequest?.map((authorization) => ({\n address: authorization.address,\n from,\n }));\n\n if (with7702 && !delegationAddress && !authorizationList) {\n authorizationList = buildAuthorizationList({\n chainId,\n from,\n messenger,\n publicKeyEIP7702,\n });\n }\n\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n authorizationList,\n data,\n from,\n to,\n value,\n },\n ],\n suggestFees: {\n withTransfer: true,\n withFeeTransfer: true,\n with7702,\n },\n });\n\n log('Response', response);\n\n const result = parseGasFeeTokens(response);\n\n log('Gas fee tokens', result);\n\n return result;\n } catch (error) {\n log('Failed to gas fee tokens', error);\n return { gasFeeTokens: [], isGasFeeSponsored: false };\n }\n}\n\n/**\n * Check and update gas fee token selection before publishing a transaction.\n *\n * @param request - Request object.\n * @param request.ethQuery - EthQuery instance.\n * @param request.fetchGasFeeTokens - Function to fetch gas fee tokens.\n * @param request.transaction - Transaction metadata.\n * @param request.updateTransaction - Function to update the transaction.\n */\nexport async function checkGasFeeTokenBeforePublish({\n ethQuery,\n fetchGasFeeTokens,\n transaction,\n updateTransaction,\n}: {\n ethQuery: EthQuery;\n fetchGasFeeTokens: (transaction: TransactionMeta) => Promise<GasFeeToken[]>;\n transaction: TransactionMeta;\n updateTransaction: (\n transactionId: string,\n fn: (tx: TransactionMeta) => void,\n ) => void;\n}) {\n const { isGasFeeTokenIgnoredIfBalance, selectedGasFeeToken } = transaction;\n\n if (!selectedGasFeeToken || !isGasFeeTokenIgnoredIfBalance) {\n return;\n }\n\n log('Checking gas fee token before publish', { selectedGasFeeToken });\n\n const hasNativeBalance = await isNativeBalanceSufficientForGas(\n transaction,\n ethQuery,\n );\n\n if (hasNativeBalance) {\n log(\n 'Ignoring gas fee token before publish due to sufficient native balance',\n );\n\n updateTransaction(transaction.id, (tx) => {\n tx.isExternalSign = false;\n tx.selectedGasFeeToken = undefined;\n });\n\n return;\n }\n\n const gasFeeTokens = await fetchGasFeeTokens({\n ...transaction,\n isExternalSign: true,\n });\n\n updateTransaction(transaction.id, (tx) => {\n tx.gasFeeTokens = gasFeeTokens;\n tx.isExternalSign = true;\n tx.txParams.nonce = undefined;\n });\n\n log('Updated gas fee tokens before publish', gasFeeTokens);\n\n if (\n !gasFeeTokens?.some(\n (t) => t.tokenAddress.toLowerCase() === selectedGasFeeToken.toLowerCase(),\n )\n ) {\n throw new Error('Gas fee token not found and insufficient native balance');\n }\n\n log('Publishing with selected gas fee token', { selectedGasFeeToken });\n}\n\n/**\n * Extract gas fee tokens from a simulation response.\n *\n * @param response - The simulation response.\n * @returns gasFeeTokens: An array of gas fee tokens. isGasFeeSponsored: Whether the transaction is sponsored\n */\nfunction parseGasFeeTokens(response: SimulationResponse): {\n gasFeeTokens: GasFeeToken[];\n isGasFeeSponsored: boolean;\n} {\n const feeLevel = response.transactions?.[0]\n ?.fees?.[0] as Required<SimulationResponseTransaction>['fees'][0];\n\n const isGasFeeSponsored = response.sponsorship?.isSponsored ?? false;\n\n const tokenFees = feeLevel?.tokenFees ?? [];\n\n return {\n gasFeeTokens: tokenFees.map((tokenFee) => ({\n amount: tokenFee.balanceNeededToken,\n balance: tokenFee.currentBalanceToken,\n decimals: tokenFee.token.decimals,\n fee: tokenFee.serviceFee,\n gas: feeLevel.gas,\n gasTransfer: tokenFee.transferEstimate,\n maxFeePerGas: feeLevel.maxFeePerGas,\n maxPriorityFeePerGas: feeLevel.maxPriorityFeePerGas,\n rateWei: tokenFee.rateWei,\n recipient: tokenFee.feeRecipient,\n symbol: tokenFee.token.symbol,\n tokenAddress: tokenFee.token.address,\n })),\n isGasFeeSponsored,\n };\n}\n\n/**\n * Generate the authorization list for the request.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID.\n * @param request.from - The sender's address.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - The public key for EIP-7702.\n * @returns The authorization list.\n */\nfunction buildAuthorizationList({\n chainId,\n from,\n messenger,\n publicKeyEIP7702,\n}: {\n chainId: Hex;\n from: Hex;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n}): SimulationRequestTransaction['authorizationList'] | undefined {\n if (!publicKeyEIP7702) {\n throw rpcErrors.internal(ERROR_MESSGE_PUBLIC_KEY);\n }\n\n const upgradeAddress = getEIP7702UpgradeContractAddress(\n chainId,\n messenger,\n publicKeyEIP7702,\n );\n\n if (!upgradeAddress) {\n throw rpcErrors.internal(ERROR_MESSAGE_NO_UPGRADE_CONTRACT);\n }\n\n return [\n {\n address: upgradeAddress,\n from,\n },\n ];\n}\n"]}
|
|
@@ -31,12 +31,12 @@ export async function getGasFeeTokens({ chainId, isEIP7702GasFeeTokensEnabled, m
|
|
|
31
31
|
const with7702 = is7702GasFeeTokensEnabled && doesChainSupportEIP7702(chainId, messenger);
|
|
32
32
|
let authorizationList = authorizationListRequest?.map((authorization) => ({
|
|
33
33
|
address: authorization.address,
|
|
34
|
-
from
|
|
34
|
+
from,
|
|
35
35
|
}));
|
|
36
36
|
if (with7702 && !delegationAddress && !authorizationList) {
|
|
37
37
|
authorizationList = buildAuthorizationList({
|
|
38
38
|
chainId,
|
|
39
|
-
from
|
|
39
|
+
from,
|
|
40
40
|
messenger,
|
|
41
41
|
publicKeyEIP7702,
|
|
42
42
|
});
|
|
@@ -158,7 +158,7 @@ function buildAuthorizationList({ chainId, from, messenger, publicKeyEIP7702, })
|
|
|
158
158
|
return [
|
|
159
159
|
{
|
|
160
160
|
address: upgradeAddress,
|
|
161
|
-
from
|
|
161
|
+
from,
|
|
162
162
|
},
|
|
163
163
|
];
|
|
164
164
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas-fee-tokens.mjs","sourceRoot":"","sources":["../../src/utils/gas-fee-tokens.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAErD,OAAO,EAAE,+BAA+B,EAAE,sBAAkB;AAC5D,OAAO,EAAE,iCAAiC,EAAE,oBAAgB;AAC5D,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,sBAAkB;AAC7E,OAAO,EAAE,gCAAgC,EAAE,4BAAwB;AAOnE,OAAO,EACL,oBAAoB,EAGrB,kCAA8B;AAC/B,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAG1C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC;AAahE;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,EACpC,OAAO,EACP,4BAA4B,EAC5B,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,mBAAmB,GACI;IACvB,MAAM,EAAE,iBAAiB,EAAE,QAAQ,EAAE,GAAG,eAAe,CAAC;IACxD,MAAM,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,GAAG,QAAQ,CAAC;IACjE,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAW,CAAC;IAClC,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAW,CAAC;IAClC,MAA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AACH,SAAS,sBAAsB,CAAC,EAC9B,OAAO,EACP,IAAI,EACJ,SAAS,EACT,gBAAgB,GAMjB;IACC,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,MAAM,SAAS,CAAC,QAAQ,CAAC,uBAAuB,CAAC,CAAC;IACpD,CAAC;IAED,MAAM,cAAc,GAAG,gCAAgC,CACrD,OAAO,EACP,SAAS,EACT,gBAAgB,CACjB,CAAC;IAEF,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,MAAM,SAAS,CAAC,QAAQ,CAAC,iCAAiC,CAAC,CAAC;IAC9D,CAAC;IAED,OAAO;QACL;YACE,OAAO,EAAE,cAAc;YACvB,IAAI,EAAE,IAAW;SAClB;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type EthQuery from '@metamask/eth-query';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { isNativeBalanceSufficientForGas } from './balance';\nimport { ERROR_MESSAGE_NO_UPGRADE_CONTRACT } from './batch';\nimport { ERROR_MESSGE_PUBLIC_KEY, doesChainSupportEIP7702 } from './eip7702';\nimport { getEIP7702UpgradeContractAddress } from './feature-flags';\nimport type {\n GasFeeToken,\n TransactionControllerMessenger,\n TransactionMeta,\n} from '..';\nimport type { SimulationRequestTransaction } from '../api/simulation-api';\nimport {\n simulateTransactions,\n type SimulationResponse,\n type SimulationResponseTransaction,\n} from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { GetSimulationConfig } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'gas-fee-tokens');\n\nexport type GetGasFeeTokensRequest = {\n chainId: Hex;\n isEIP7702GasFeeTokensEnabled: (\n transactionMeta: TransactionMeta,\n ) => Promise<boolean>;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n transactionMeta: TransactionMeta;\n};\n\n/**\n * Get gas fee tokens for a transaction.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID of the transaction.\n * @param request.isEIP7702GasFeeTokensEnabled - Callback to check if EIP-7702 gas fee tokens are enabled.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - Public key to validate EIP-7702 contract signatures.\n * @param request.transactionMeta - The transaction metadata.\n * @param request.getSimulationConfig - Optional transaction simulation parameters.\n * @returns An array of gas fee tokens.\n */\nexport async function getGasFeeTokens({\n chainId,\n isEIP7702GasFeeTokensEnabled,\n messenger,\n publicKeyEIP7702,\n transactionMeta,\n getSimulationConfig,\n}: GetGasFeeTokensRequest) {\n const { delegationAddress, txParams } = transactionMeta;\n const { authorizationList: authorizationListRequest } = txParams;\n const data = txParams.data as Hex;\n const from = txParams.from as Hex;\n const to = txParams.to as Hex;\n const value = txParams.value as Hex;\n\n log('Request', { chainId, txParams });\n\n const is7702GasFeeTokensEnabled =\n await isEIP7702GasFeeTokensEnabled(transactionMeta);\n\n const with7702 =\n is7702GasFeeTokensEnabled && doesChainSupportEIP7702(chainId, messenger);\n\n let authorizationList:\n | SimulationRequestTransaction['authorizationList']\n | undefined = authorizationListRequest?.map((authorization) => ({\n address: authorization.address,\n from: from as Hex,\n }));\n\n if (with7702 && !delegationAddress && !authorizationList) {\n authorizationList = buildAuthorizationList({\n chainId,\n from: from as Hex,\n messenger,\n publicKeyEIP7702,\n });\n }\n\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n authorizationList,\n data,\n from,\n to,\n value,\n },\n ],\n suggestFees: {\n withTransfer: true,\n withFeeTransfer: true,\n with7702,\n },\n });\n\n log('Response', response);\n\n const result = parseGasFeeTokens(response);\n\n log('Gas fee tokens', result);\n\n return result;\n } catch (error) {\n log('Failed to gas fee tokens', error);\n return { gasFeeTokens: [], isGasFeeSponsored: false };\n }\n}\n\n/**\n * Check and update gas fee token selection before publishing a transaction.\n *\n * @param request - Request object.\n * @param request.ethQuery - EthQuery instance.\n * @param request.fetchGasFeeTokens - Function to fetch gas fee tokens.\n * @param request.transaction - Transaction metadata.\n * @param request.updateTransaction - Function to update the transaction.\n */\nexport async function checkGasFeeTokenBeforePublish({\n ethQuery,\n fetchGasFeeTokens,\n transaction,\n updateTransaction,\n}: {\n ethQuery: EthQuery;\n fetchGasFeeTokens: (transaction: TransactionMeta) => Promise<GasFeeToken[]>;\n transaction: TransactionMeta;\n updateTransaction: (\n transactionId: string,\n fn: (tx: TransactionMeta) => void,\n ) => void;\n}) {\n const { isGasFeeTokenIgnoredIfBalance, selectedGasFeeToken } = transaction;\n\n if (!selectedGasFeeToken || !isGasFeeTokenIgnoredIfBalance) {\n return;\n }\n\n log('Checking gas fee token before publish', { selectedGasFeeToken });\n\n const hasNativeBalance = await isNativeBalanceSufficientForGas(\n transaction,\n ethQuery,\n );\n\n if (hasNativeBalance) {\n log(\n 'Ignoring gas fee token before publish due to sufficient native balance',\n );\n\n updateTransaction(transaction.id, (tx) => {\n tx.isExternalSign = false;\n tx.selectedGasFeeToken = undefined;\n });\n\n return;\n }\n\n const gasFeeTokens = await fetchGasFeeTokens({\n ...transaction,\n isExternalSign: true,\n });\n\n updateTransaction(transaction.id, (tx) => {\n tx.gasFeeTokens = gasFeeTokens;\n tx.isExternalSign = true;\n tx.txParams.nonce = undefined;\n });\n\n log('Updated gas fee tokens before publish', gasFeeTokens);\n\n if (\n !gasFeeTokens?.some(\n (t) => t.tokenAddress.toLowerCase() === selectedGasFeeToken.toLowerCase(),\n )\n ) {\n throw new Error('Gas fee token not found and insufficient native balance');\n }\n\n log('Publishing with selected gas fee token', { selectedGasFeeToken });\n}\n\n/**\n * Extract gas fee tokens from a simulation response.\n *\n * @param response - The simulation response.\n * @returns gasFeeTokens: An array of gas fee tokens. isGasFeeSponsored: Whether the transaction is sponsored\n */\nfunction parseGasFeeTokens(response: SimulationResponse): {\n gasFeeTokens: GasFeeToken[];\n isGasFeeSponsored: boolean;\n} {\n const feeLevel = response.transactions?.[0]\n ?.fees?.[0] as Required<SimulationResponseTransaction>['fees'][0];\n\n const isGasFeeSponsored = response.sponsorship?.isSponsored ?? false;\n\n const tokenFees = feeLevel?.tokenFees ?? [];\n\n return {\n gasFeeTokens: tokenFees.map((tokenFee) => ({\n amount: tokenFee.balanceNeededToken,\n balance: tokenFee.currentBalanceToken,\n decimals: tokenFee.token.decimals,\n fee: tokenFee.serviceFee,\n gas: feeLevel.gas,\n gasTransfer: tokenFee.transferEstimate,\n maxFeePerGas: feeLevel.maxFeePerGas,\n maxPriorityFeePerGas: feeLevel.maxPriorityFeePerGas,\n rateWei: tokenFee.rateWei,\n recipient: tokenFee.feeRecipient,\n symbol: tokenFee.token.symbol,\n tokenAddress: tokenFee.token.address,\n })),\n isGasFeeSponsored,\n };\n}\n\n/**\n * Generate the authorization list for the request.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID.\n * @param request.from - The sender's address.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - The public key for EIP-7702.\n * @returns The authorization list.\n */\nfunction buildAuthorizationList({\n chainId,\n from,\n messenger,\n publicKeyEIP7702,\n}: {\n chainId: Hex;\n from: Hex;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n}): SimulationRequestTransaction['authorizationList'] | undefined {\n if (!publicKeyEIP7702) {\n throw rpcErrors.internal(ERROR_MESSGE_PUBLIC_KEY);\n }\n\n const upgradeAddress = getEIP7702UpgradeContractAddress(\n chainId,\n messenger,\n publicKeyEIP7702,\n );\n\n if (!upgradeAddress) {\n throw rpcErrors.internal(ERROR_MESSAGE_NO_UPGRADE_CONTRACT);\n }\n\n return [\n {\n address: upgradeAddress,\n from: from as Hex,\n },\n ];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gas-fee-tokens.mjs","sourceRoot":"","sources":["../../src/utils/gas-fee-tokens.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAErD,OAAO,EAAE,+BAA+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CAAC;IAE5C,OAAO;QACL,YAAY,EAAE,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YACzC,MAAM,EAAE,QAAQ,CAAC,kBAAkB;YACnC,OAAO,EAAE,QAAQ,CAAC,mBAAmB;YACrC,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,QAAQ;YACjC,GAAG,EAAE,QAAQ,CAAC,UAAU;YACxB,GAAG,EAAE,QAAQ,CAAC,GAAG;YACjB,WAAW,EAAE,QAAQ,CAAC,gBAAgB;YACtC,YAAY,EAAE,QAAQ,CAAC,YAAY;YACnC,oBAAoB,EAAE,QAAQ,CAAC,oBAAoB;YACnD,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,SAAS,EAAE,QAAQ,CAAC,YAAY;YAChC,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC,MAAM;YAC7B,YAAY,EAAE,QAAQ,CAAC,KAAK,CAAC,OAAO;SACrC,CAAC,CAAC;QACH,iBAAiB;KAClB,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,sBAAsB,CAAC,EAC9B,OAAO,EACP,IAAI,EACJ,SAAS,EACT,gBAAgB,GAMjB;IACC,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,MAAM,SAAS,CAAC,QAAQ,CAAC,uBAAuB,CAAC,CAAC;IACpD,CAAC;IAED,MAAM,cAAc,GAAG,gCAAgC,CACrD,OAAO,EACP,SAAS,EACT,gBAAgB,CACjB,CAAC;IAEF,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,MAAM,SAAS,CAAC,QAAQ,CAAC,iCAAiC,CAAC,CAAC;IAC9D,CAAC;IAED,OAAO;QACL;YACE,OAAO,EAAE,cAAc;YACvB,IAAI;SACL;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type EthQuery from '@metamask/eth-query';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { isNativeBalanceSufficientForGas } from './balance';\nimport { ERROR_MESSAGE_NO_UPGRADE_CONTRACT } from './batch';\nimport { ERROR_MESSGE_PUBLIC_KEY, doesChainSupportEIP7702 } from './eip7702';\nimport { getEIP7702UpgradeContractAddress } from './feature-flags';\nimport type {\n GasFeeToken,\n TransactionControllerMessenger,\n TransactionMeta,\n} from '..';\nimport { simulateTransactions } from '../api/simulation-api';\nimport type { SimulationRequestTransaction } from '../api/simulation-api';\nimport type {\n SimulationResponse,\n SimulationResponseTransaction,\n} from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { GetSimulationConfig } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'gas-fee-tokens');\n\nexport type GetGasFeeTokensRequest = {\n chainId: Hex;\n isEIP7702GasFeeTokensEnabled: (\n transactionMeta: TransactionMeta,\n ) => Promise<boolean>;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n transactionMeta: TransactionMeta;\n};\n\n/**\n * Get gas fee tokens for a transaction.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID of the transaction.\n * @param request.isEIP7702GasFeeTokensEnabled - Callback to check if EIP-7702 gas fee tokens are enabled.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - Public key to validate EIP-7702 contract signatures.\n * @param request.transactionMeta - The transaction metadata.\n * @param request.getSimulationConfig - Optional transaction simulation parameters.\n * @returns An array of gas fee tokens.\n */\nexport async function getGasFeeTokens({\n chainId,\n isEIP7702GasFeeTokensEnabled,\n messenger,\n publicKeyEIP7702,\n transactionMeta,\n getSimulationConfig,\n}: GetGasFeeTokensRequest) {\n const { delegationAddress, txParams } = transactionMeta;\n const { authorizationList: authorizationListRequest } = txParams;\n const data = txParams.data as Hex;\n const from = txParams.from as Hex;\n const to = txParams.to as Hex;\n const value = txParams.value as Hex;\n\n log('Request', { chainId, txParams });\n\n const is7702GasFeeTokensEnabled =\n await isEIP7702GasFeeTokensEnabled(transactionMeta);\n\n const with7702 =\n is7702GasFeeTokensEnabled && doesChainSupportEIP7702(chainId, messenger);\n\n let authorizationList:\n | SimulationRequestTransaction['authorizationList']\n | undefined = authorizationListRequest?.map((authorization) => ({\n address: authorization.address,\n from,\n }));\n\n if (with7702 && !delegationAddress && !authorizationList) {\n authorizationList = buildAuthorizationList({\n chainId,\n from,\n messenger,\n publicKeyEIP7702,\n });\n }\n\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n authorizationList,\n data,\n from,\n to,\n value,\n },\n ],\n suggestFees: {\n withTransfer: true,\n withFeeTransfer: true,\n with7702,\n },\n });\n\n log('Response', response);\n\n const result = parseGasFeeTokens(response);\n\n log('Gas fee tokens', result);\n\n return result;\n } catch (error) {\n log('Failed to gas fee tokens', error);\n return { gasFeeTokens: [], isGasFeeSponsored: false };\n }\n}\n\n/**\n * Check and update gas fee token selection before publishing a transaction.\n *\n * @param request - Request object.\n * @param request.ethQuery - EthQuery instance.\n * @param request.fetchGasFeeTokens - Function to fetch gas fee tokens.\n * @param request.transaction - Transaction metadata.\n * @param request.updateTransaction - Function to update the transaction.\n */\nexport async function checkGasFeeTokenBeforePublish({\n ethQuery,\n fetchGasFeeTokens,\n transaction,\n updateTransaction,\n}: {\n ethQuery: EthQuery;\n fetchGasFeeTokens: (transaction: TransactionMeta) => Promise<GasFeeToken[]>;\n transaction: TransactionMeta;\n updateTransaction: (\n transactionId: string,\n fn: (tx: TransactionMeta) => void,\n ) => void;\n}) {\n const { isGasFeeTokenIgnoredIfBalance, selectedGasFeeToken } = transaction;\n\n if (!selectedGasFeeToken || !isGasFeeTokenIgnoredIfBalance) {\n return;\n }\n\n log('Checking gas fee token before publish', { selectedGasFeeToken });\n\n const hasNativeBalance = await isNativeBalanceSufficientForGas(\n transaction,\n ethQuery,\n );\n\n if (hasNativeBalance) {\n log(\n 'Ignoring gas fee token before publish due to sufficient native balance',\n );\n\n updateTransaction(transaction.id, (tx) => {\n tx.isExternalSign = false;\n tx.selectedGasFeeToken = undefined;\n });\n\n return;\n }\n\n const gasFeeTokens = await fetchGasFeeTokens({\n ...transaction,\n isExternalSign: true,\n });\n\n updateTransaction(transaction.id, (tx) => {\n tx.gasFeeTokens = gasFeeTokens;\n tx.isExternalSign = true;\n tx.txParams.nonce = undefined;\n });\n\n log('Updated gas fee tokens before publish', gasFeeTokens);\n\n if (\n !gasFeeTokens?.some(\n (t) => t.tokenAddress.toLowerCase() === selectedGasFeeToken.toLowerCase(),\n )\n ) {\n throw new Error('Gas fee token not found and insufficient native balance');\n }\n\n log('Publishing with selected gas fee token', { selectedGasFeeToken });\n}\n\n/**\n * Extract gas fee tokens from a simulation response.\n *\n * @param response - The simulation response.\n * @returns gasFeeTokens: An array of gas fee tokens. isGasFeeSponsored: Whether the transaction is sponsored\n */\nfunction parseGasFeeTokens(response: SimulationResponse): {\n gasFeeTokens: GasFeeToken[];\n isGasFeeSponsored: boolean;\n} {\n const feeLevel = response.transactions?.[0]\n ?.fees?.[0] as Required<SimulationResponseTransaction>['fees'][0];\n\n const isGasFeeSponsored = response.sponsorship?.isSponsored ?? false;\n\n const tokenFees = feeLevel?.tokenFees ?? [];\n\n return {\n gasFeeTokens: tokenFees.map((tokenFee) => ({\n amount: tokenFee.balanceNeededToken,\n balance: tokenFee.currentBalanceToken,\n decimals: tokenFee.token.decimals,\n fee: tokenFee.serviceFee,\n gas: feeLevel.gas,\n gasTransfer: tokenFee.transferEstimate,\n maxFeePerGas: feeLevel.maxFeePerGas,\n maxPriorityFeePerGas: feeLevel.maxPriorityFeePerGas,\n rateWei: tokenFee.rateWei,\n recipient: tokenFee.feeRecipient,\n symbol: tokenFee.token.symbol,\n tokenAddress: tokenFee.token.address,\n })),\n isGasFeeSponsored,\n };\n}\n\n/**\n * Generate the authorization list for the request.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID.\n * @param request.from - The sender's address.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - The public key for EIP-7702.\n * @returns The authorization list.\n */\nfunction buildAuthorizationList({\n chainId,\n from,\n messenger,\n publicKeyEIP7702,\n}: {\n chainId: Hex;\n from: Hex;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n}): SimulationRequestTransaction['authorizationList'] | undefined {\n if (!publicKeyEIP7702) {\n throw rpcErrors.internal(ERROR_MESSGE_PUBLIC_KEY);\n }\n\n const upgradeAddress = getEIP7702UpgradeContractAddress(\n chainId,\n messenger,\n publicKeyEIP7702,\n );\n\n if (!upgradeAddress) {\n throw rpcErrors.internal(ERROR_MESSAGE_NO_UPGRADE_CONTRACT);\n }\n\n return [\n {\n address: upgradeAddress,\n from,\n },\n ];\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas-fees.cjs","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":";;;AAAA,iEAKoC;AAOpC,2CAA4D;AAE5D,6CAA2C;AAC3C,uCAAiD;AACjD,0CAA0C;AAS1C,wCAA4D;AA0B5D,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,UAAU,CAAC,CAAC;AAE1D;;;;GAIG;AACI,KAAK,UAAU,aAAa,CAAC,OAA6B;IAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC3B,MAAM,aAAa,GAAG,EAAE,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;IAE7C,MAAM,MAAM,GAAG,8BAAsB,CAAC,QAAQ,CAC5C,MAAM,CAAC,IAAuB,CAC/B,CAAC;IACF,MAAM,YAAY,GAAG,MAAM;QACzB,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAE5C,MAAM,gBAAgB,GAAG,MAAM,mBAAmB,CAAC,OAAO,CAAC,CAAC;IAE5D,GAAG,CAAC,oBAAoB,EAAE,gBAAgB,CAAC,CAA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C,CAAC,IAAA,aAAK,EAAC,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACrC,CAAC,CAAC,SAAS,CAAC;IAEd,OAAO,EAAE,QAAQ,EAAE,CAAC;AACtB,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n gweiDecToWEIBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type {\n FetchGasFeeEstimateOptions,\n GasFeeState,\n} from '@metamask/gas-fee-controller';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\n\nimport { getGasFeeFlow } from './gas-flow';\nimport { SWAP_TRANSACTION_TYPES } from './swaps';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n SavedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionType,\n GasFeeFlow,\n} from '../types';\nimport { GasFeeEstimateType, UserFeeLevel } from '../types';\n\nexport type UpdateGasFeesRequest = {\n eip1559: boolean;\n ethQuery: EthQuery;\n gasFeeFlows: GasFeeFlow[];\n getGasFeeEstimates: (\n options: FetchGasFeeEstimateOptions,\n ) => Promise<GasFeeState>;\n getSavedGasFees: (chainId: Hex) => SavedGasFees | undefined;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport type GetGasFeeRequest = UpdateGasFeesRequest & {\n initialParams: TransactionParams;\n savedGasFees?: SavedGasFees;\n suggestedGasFees: SuggestedGasFees;\n};\n\ntype SuggestedGasFees = {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n gasPrice?: string;\n};\n\nconst log = createModuleLogger(projectLogger, 'gas-fees');\n\n/**\n * Update the gas fee properties of the provided transaction meta.\n *\n * @param request - The request object.\n */\nexport async function updateGasFees(request: UpdateGasFeesRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const isSwap = SWAP_TRANSACTION_TYPES.includes(\n txMeta.type as TransactionType,\n );\n const savedGasFees = isSwap\n ? undefined\n : request.getSavedGasFees(txMeta.chainId);\n\n const suggestedGasFees = await getSuggestedGasFees(request);\n\n log('Suggested gas fees', suggestedGasFees);\n\n const getGasFeeRequest: GetGasFeeRequest = {\n ...request,\n initialParams,\n savedGasFees,\n suggestedGasFees,\n };\n\n txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.maxPriorityFeePerGas =\n getMaxPriorityFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.gasPrice = getGasPrice(getGasFeeRequest);\n txMeta.userFeeLevel = getUserFeeLevel(getGasFeeRequest);\n\n log('Updated gas fee properties', {\n maxFeePerGas: txMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: txMeta.txParams.maxPriorityFeePerGas,\n gasPrice: txMeta.txParams.gasPrice,\n });\n\n if (txMeta.txParams.maxFeePerGas || txMeta.txParams.maxPriorityFeePerGas) {\n delete txMeta.txParams.gasPrice;\n }\n\n if (txMeta.txParams.gasPrice) {\n delete txMeta.txParams.maxFeePerGas;\n delete txMeta.txParams.maxPriorityFeePerGas;\n }\n\n updateDefaultGasEstimates(txMeta);\n}\n\n/**\n * Convert GWEI from decimal string to WEI as hex string.\n *\n * @param value - The GWEI value as a decimal string.\n * @returns The WEI value in hex.\n */\nexport function gweiDecimalToWeiHex(value: string) {\n return toHex(gweiDecToWEIBN(value));\n}\n\n/**\n * Converts a value from Gwei decimal representation to Wei decimal representation\n *\n * @param gweiDecimal - The value in Gwei as a string or number\n * @returns The value in Wei as a string\n *\n * @example\n * // Convert 1.5 Gwei to Wei\n * gweiDecimalToWeiDecimal(\"1.5\")\n * // Returns \"1500000000\"\n */\nexport function gweiDecimalToWeiDecimal(gweiDecimal: string | number): string {\n const weiValue = Number(gweiDecimal) * 1e9;\n\n return weiValue.toString().split('.')[0];\n}\n\n/**\n * Determine the maxFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxFeePerGas value.\n */\nfunction getMaxFeePerGas(request: GetGasFeeRequest): string | undefined {\n const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee as string);\n log('Using maxFeePerGas from savedGasFees', maxFeePerGas);\n return maxFeePerGas;\n }\n\n if (initialParams.maxFeePerGas) {\n log('Using maxFeePerGas from request', initialParams.maxFeePerGas);\n return initialParams.maxFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxPriorityFeePerGas) {\n log(\n 'Setting maxFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log(\n 'Setting maxFeePerGas to suggested gasPrice',\n suggestedGasFees.gasPrice,\n );\n return suggestedGasFees.gasPrice;\n }\n\n log('maxFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the maxPriorityFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxPriorityFeePerGas value.\n */\nfunction getMaxPriorityFeePerGas(\n request: GetGasFeeRequest,\n): string | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);\n log(\n 'Using maxPriorityFeePerGas from savedGasFees.priorityFee',\n maxPriorityFeePerGas,\n );\n return maxPriorityFeePerGas;\n }\n\n if (initialParams.maxPriorityFeePerGas) {\n log(\n 'Using maxPriorityFeePerGas from request',\n initialParams.maxPriorityFeePerGas,\n );\n return initialParams.maxPriorityFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxPriorityFeePerGas) {\n log(\n 'Using suggested maxPriorityFeePerGas',\n suggestedGasFees.maxPriorityFeePerGas,\n );\n return suggestedGasFees.maxPriorityFeePerGas;\n }\n\n if (txMeta.txParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to maxFeePerGas',\n txMeta.txParams.maxFeePerGas,\n );\n return txMeta.txParams.maxFeePerGas;\n }\n\n log('maxPriorityFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the gasPrice value for the transaction.\n *\n * @param request - The request object.\n * @returns The gasPrice value.\n */\nfunction getGasPrice(request: GetGasFeeRequest): string | undefined {\n const { eip1559, initialParams, suggestedGasFees } = request;\n\n if (eip1559) {\n return undefined;\n }\n\n if (initialParams.gasPrice) {\n log('Using gasPrice from request', initialParams.gasPrice);\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log('Using suggested gasPrice', suggestedGasFees.gasPrice);\n return suggestedGasFees.gasPrice;\n }\n\n log('gasPrice not set');\n return undefined;\n}\n\n/**\n * Determine the user fee level.\n *\n * @param request - The request object.\n * @returns The user fee level.\n */\nfunction getUserFeeLevel(request: GetGasFeeRequest): UserFeeLevel | undefined {\n const { initialParams, savedGasFees, suggestedGasFees, txMeta } = request;\n\n if (savedGasFees) {\n return UserFeeLevel.CUSTOM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n initialParams.gasPrice\n ) {\n return txMeta.origin === ORIGIN_METAMASK\n ? UserFeeLevel.CUSTOM\n : UserFeeLevel.DAPP_SUGGESTED;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.maxFeePerGas &&\n suggestedGasFees.maxPriorityFeePerGas\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.gasPrice\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (txMeta.origin === ORIGIN_METAMASK) {\n return UserFeeLevel.MEDIUM;\n }\n\n return UserFeeLevel.DAPP_SUGGESTED;\n}\n\n/**\n * Update the default gas estimates for the provided transaction.\n *\n * @param txMeta - The transaction metadata.\n */\nfunction updateDefaultGasEstimates(txMeta: TransactionMeta) {\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.maxFeePerGas = txMeta.txParams.maxFeePerGas;\n\n txMeta.defaultGasEstimates.maxPriorityFeePerGas =\n txMeta.txParams.maxPriorityFeePerGas;\n\n txMeta.defaultGasEstimates.gasPrice = txMeta.txParams.gasPrice;\n txMeta.defaultGasEstimates.estimateType = txMeta.userFeeLevel;\n}\n\n/**\n * Retrieve the suggested gas fees using the gas fee flows.\n *\n * @param request - The request object.\n * @returns The suggested gas fees.\n */\nasync function getSuggestedGasFees(\n request: UpdateGasFeesRequest,\n): Promise<SuggestedGasFees> {\n const {\n eip1559,\n ethQuery,\n gasFeeFlows,\n getGasFeeEstimates,\n messenger,\n txMeta,\n } = request;\n\n const { networkClientId } = txMeta;\n\n if (\n (!eip1559 && txMeta.txParams.gasPrice) ||\n (eip1559 &&\n txMeta.txParams.maxFeePerGas &&\n txMeta.txParams.maxPriorityFeePerGas)\n ) {\n return {};\n }\n\n const gasFeeFlow = getGasFeeFlow(\n txMeta,\n gasFeeFlows,\n messenger,\n ) as GasFeeFlow;\n\n try {\n const gasFeeControllerData = await getGasFeeEstimates({ networkClientId });\n\n const response = await gasFeeFlow.getGasFees({\n ethQuery,\n gasFeeControllerData,\n messenger,\n transactionMeta: txMeta,\n });\n\n const gasFeeEstimateType = response.estimates?.type;\n\n switch (gasFeeEstimateType) {\n case GasFeeEstimateType.FeeMarket:\n return response.estimates.medium;\n case GasFeeEstimateType.Legacy:\n return {\n gasPrice: response.estimates.medium,\n };\n case GasFeeEstimateType.GasPrice:\n return { gasPrice: response.estimates.gasPrice };\n default:\n throw new Error(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Unsupported gas fee estimate type returned from flow: ${gasFeeEstimateType}`,\n );\n }\n } catch (error) {\n log('Failed to get suggested gas fees', error);\n }\n\n const gasPriceDecimal = (await query(ethQuery, 'gasPrice')) as number;\n\n const gasPrice = gasPriceDecimal\n ? add0x(gasPriceDecimal.toString(16))\n : undefined;\n\n return { gasPrice };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gas-fees.cjs","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":";;;AAAA,iEAKoC;AAOpC,2CAA4D;AAE5D,6CAA2C;AAC3C,uCAAiD;AACjD,0CAA0C;AAS1C,wCAA4D;AA0B5D,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,UAAU,CAAC,CAAC;AAE1D;;;;GAIG;AACI,KAAK,UAAU,aAAa,CAAC,OAA6B;IAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC3B,MAAM,aAAa,GAAG,EAAE,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;IAE7C,MAAM,MAAM,GAAG,8BAAsB,CAAC,QAAQ,CAC5C,MAAM,CAAC,IAAuB,CAC/B,CAAC;IACF,MAAM,YAAY,GAAG,MAAM;QACzB,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAE5C,MAAM,gBAAgB,GAAG,MAAM,mBAAmB,CAAC,OAAO,CAAC,CAAC;IAE5D,GAAG,CAAC,oBAAoB,EAAE,gBAAgB,CAAC,CAAC;IAE5C,MAAM,gBAAgB,GAAqB;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AAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACrC,CAAC,CAAC,SAAS,CAAC;IAEd,OAAO,EAAE,QAAQ,EAAE,CAAC;AACtB,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n gweiDecToWEIBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type {\n FetchGasFeeEstimateOptions,\n GasFeeState,\n} from '@metamask/gas-fee-controller';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\n\nimport { getGasFeeFlow } from './gas-flow';\nimport { SWAP_TRANSACTION_TYPES } from './swaps';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n SavedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionType,\n GasFeeFlow,\n} from '../types';\nimport { GasFeeEstimateType, UserFeeLevel } from '../types';\n\nexport type UpdateGasFeesRequest = {\n eip1559: boolean;\n ethQuery: EthQuery;\n gasFeeFlows: GasFeeFlow[];\n getGasFeeEstimates: (\n options: FetchGasFeeEstimateOptions,\n ) => Promise<GasFeeState>;\n getSavedGasFees: (chainId: Hex) => SavedGasFees | undefined;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport type GetGasFeeRequest = UpdateGasFeesRequest & {\n initialParams: TransactionParams;\n savedGasFees?: SavedGasFees;\n suggestedGasFees: SuggestedGasFees;\n};\n\ntype SuggestedGasFees = {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n gasPrice?: string;\n};\n\nconst log = createModuleLogger(projectLogger, 'gas-fees');\n\n/**\n * Update the gas fee properties of the provided transaction meta.\n *\n * @param request - The request object.\n */\nexport async function updateGasFees(request: UpdateGasFeesRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const isSwap = SWAP_TRANSACTION_TYPES.includes(\n txMeta.type as TransactionType,\n );\n const savedGasFees = isSwap\n ? undefined\n : request.getSavedGasFees(txMeta.chainId);\n\n const suggestedGasFees = await getSuggestedGasFees(request);\n\n log('Suggested gas fees', suggestedGasFees);\n\n const getGasFeeRequest: GetGasFeeRequest = {\n ...request,\n initialParams,\n savedGasFees,\n suggestedGasFees,\n };\n\n txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.maxPriorityFeePerGas =\n getMaxPriorityFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.gasPrice = getGasPrice(getGasFeeRequest);\n txMeta.userFeeLevel = getUserFeeLevel(getGasFeeRequest);\n\n log('Updated gas fee properties', {\n maxFeePerGas: txMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: txMeta.txParams.maxPriorityFeePerGas,\n gasPrice: txMeta.txParams.gasPrice,\n });\n\n if (txMeta.txParams.maxFeePerGas || txMeta.txParams.maxPriorityFeePerGas) {\n delete txMeta.txParams.gasPrice;\n }\n\n if (txMeta.txParams.gasPrice) {\n delete txMeta.txParams.maxFeePerGas;\n delete txMeta.txParams.maxPriorityFeePerGas;\n }\n\n updateDefaultGasEstimates(txMeta);\n}\n\n/**\n * Convert GWEI from decimal string to WEI as hex string.\n *\n * @param value - The GWEI value as a decimal string.\n * @returns The WEI value in hex.\n */\nexport function gweiDecimalToWeiHex(value: string) {\n return toHex(gweiDecToWEIBN(value));\n}\n\n/**\n * Converts a value from Gwei decimal representation to Wei decimal representation\n *\n * @param gweiDecimal - The value in Gwei as a string or number\n * @returns The value in Wei as a string\n *\n * @example\n * // Convert 1.5 Gwei to Wei\n * gweiDecimalToWeiDecimal(\"1.5\")\n * // Returns \"1500000000\"\n */\nexport function gweiDecimalToWeiDecimal(gweiDecimal: string | number): string {\n const weiValue = Number(gweiDecimal) * 1e9;\n\n return weiValue.toString().split('.')[0];\n}\n\n/**\n * Determine the maxFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxFeePerGas value.\n */\nfunction getMaxFeePerGas(request: GetGasFeeRequest): string | undefined {\n const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee);\n log('Using maxFeePerGas from savedGasFees', maxFeePerGas);\n return maxFeePerGas;\n }\n\n if (initialParams.maxFeePerGas) {\n log('Using maxFeePerGas from request', initialParams.maxFeePerGas);\n return initialParams.maxFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxPriorityFeePerGas) {\n log(\n 'Setting maxFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log(\n 'Setting maxFeePerGas to suggested gasPrice',\n suggestedGasFees.gasPrice,\n );\n return suggestedGasFees.gasPrice;\n }\n\n log('maxFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the maxPriorityFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxPriorityFeePerGas value.\n */\nfunction getMaxPriorityFeePerGas(\n request: GetGasFeeRequest,\n): string | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);\n log(\n 'Using maxPriorityFeePerGas from savedGasFees.priorityFee',\n maxPriorityFeePerGas,\n );\n return maxPriorityFeePerGas;\n }\n\n if (initialParams.maxPriorityFeePerGas) {\n log(\n 'Using maxPriorityFeePerGas from request',\n initialParams.maxPriorityFeePerGas,\n );\n return initialParams.maxPriorityFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxPriorityFeePerGas) {\n log(\n 'Using suggested maxPriorityFeePerGas',\n suggestedGasFees.maxPriorityFeePerGas,\n );\n return suggestedGasFees.maxPriorityFeePerGas;\n }\n\n if (txMeta.txParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to maxFeePerGas',\n txMeta.txParams.maxFeePerGas,\n );\n return txMeta.txParams.maxFeePerGas;\n }\n\n log('maxPriorityFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the gasPrice value for the transaction.\n *\n * @param request - The request object.\n * @returns The gasPrice value.\n */\nfunction getGasPrice(request: GetGasFeeRequest): string | undefined {\n const { eip1559, initialParams, suggestedGasFees } = request;\n\n if (eip1559) {\n return undefined;\n }\n\n if (initialParams.gasPrice) {\n log('Using gasPrice from request', initialParams.gasPrice);\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log('Using suggested gasPrice', suggestedGasFees.gasPrice);\n return suggestedGasFees.gasPrice;\n }\n\n log('gasPrice not set');\n return undefined;\n}\n\n/**\n * Determine the user fee level.\n *\n * @param request - The request object.\n * @returns The user fee level.\n */\nfunction getUserFeeLevel(request: GetGasFeeRequest): UserFeeLevel | undefined {\n const { initialParams, savedGasFees, suggestedGasFees, txMeta } = request;\n\n if (savedGasFees) {\n return UserFeeLevel.CUSTOM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n initialParams.gasPrice\n ) {\n return txMeta.origin === ORIGIN_METAMASK\n ? UserFeeLevel.CUSTOM\n : UserFeeLevel.DAPP_SUGGESTED;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.maxFeePerGas &&\n suggestedGasFees.maxPriorityFeePerGas\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.gasPrice\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (txMeta.origin === ORIGIN_METAMASK) {\n return UserFeeLevel.MEDIUM;\n }\n\n return UserFeeLevel.DAPP_SUGGESTED;\n}\n\n/**\n * Update the default gas estimates for the provided transaction.\n *\n * @param txMeta - The transaction metadata.\n */\nfunction updateDefaultGasEstimates(txMeta: TransactionMeta) {\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.maxFeePerGas = txMeta.txParams.maxFeePerGas;\n\n txMeta.defaultGasEstimates.maxPriorityFeePerGas =\n txMeta.txParams.maxPriorityFeePerGas;\n\n txMeta.defaultGasEstimates.gasPrice = txMeta.txParams.gasPrice;\n txMeta.defaultGasEstimates.estimateType = txMeta.userFeeLevel;\n}\n\n/**\n * Retrieve the suggested gas fees using the gas fee flows.\n *\n * @param request - The request object.\n * @returns The suggested gas fees.\n */\nasync function getSuggestedGasFees(\n request: UpdateGasFeesRequest,\n): Promise<SuggestedGasFees> {\n const {\n eip1559,\n ethQuery,\n gasFeeFlows,\n getGasFeeEstimates,\n messenger,\n txMeta,\n } = request;\n\n const { networkClientId } = txMeta;\n\n if (\n (!eip1559 && txMeta.txParams.gasPrice) ||\n (eip1559 &&\n txMeta.txParams.maxFeePerGas &&\n txMeta.txParams.maxPriorityFeePerGas)\n ) {\n return {};\n }\n\n const gasFeeFlow = getGasFeeFlow(\n txMeta,\n gasFeeFlows,\n messenger,\n ) as GasFeeFlow;\n\n try {\n const gasFeeControllerData = await getGasFeeEstimates({ networkClientId });\n\n const response = await gasFeeFlow.getGasFees({\n ethQuery,\n gasFeeControllerData,\n messenger,\n transactionMeta: txMeta,\n });\n\n const gasFeeEstimateType = response.estimates?.type;\n\n switch (gasFeeEstimateType) {\n case GasFeeEstimateType.FeeMarket:\n return response.estimates.medium;\n case GasFeeEstimateType.Legacy:\n return {\n gasPrice: response.estimates.medium,\n };\n case GasFeeEstimateType.GasPrice:\n return { gasPrice: response.estimates.gasPrice };\n default:\n throw new Error(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Unsupported gas fee estimate type returned from flow: ${gasFeeEstimateType}`,\n );\n }\n } catch (error) {\n log('Failed to get suggested gas fees', error);\n }\n\n const gasPriceDecimal = (await query(ethQuery, 'gasPrice')) as number;\n\n const gasPrice = gasPriceDecimal\n ? add0x(gasPriceDecimal.toString(16))\n : undefined;\n\n return { gasPrice };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas-fees.mjs","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,cAAc,EACd,KAAK,EACL,KAAK,EACN,mCAAmC;AAOpC,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,wBAAwB;AAE5D,OAAO,EAAE,aAAa,EAAE,uBAAmB;AAC3C,OAAO,EAAE,sBAAsB,EAAE,oBAAgB;AACjD,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAS1C,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,qBAAiB;AA0B5D,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,UAAU,CAAC,CAAC;AAE1D;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,OAA6B;IAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC3B,MAAM,aAAa,GAAG,EAAE,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;IAE7C,MAAM,MAAM,GAAG,sBAAsB,CAAC,QAAQ,CAC5C,MAAM,CAAC,IAAuB,CAC/B,CAAC;IACF,MAAM,YAAY,GAAG,MAAM;QACzB,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,OAAO,CAA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AK,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAW,CAAC;IAEtE,MAAM,QAAQ,GAAG,eAAe;QAC9B,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACrC,CAAC,CAAC,SAAS,CAAC;IAEd,OAAO,EAAE,QAAQ,EAAE,CAAC;AACtB,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n gweiDecToWEIBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type {\n FetchGasFeeEstimateOptions,\n GasFeeState,\n} from '@metamask/gas-fee-controller';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\n\nimport { getGasFeeFlow } from './gas-flow';\nimport { SWAP_TRANSACTION_TYPES } from './swaps';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n SavedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionType,\n GasFeeFlow,\n} from '../types';\nimport { GasFeeEstimateType, UserFeeLevel } from '../types';\n\nexport type UpdateGasFeesRequest = {\n eip1559: boolean;\n ethQuery: EthQuery;\n gasFeeFlows: GasFeeFlow[];\n getGasFeeEstimates: (\n options: FetchGasFeeEstimateOptions,\n ) => Promise<GasFeeState>;\n getSavedGasFees: (chainId: Hex) => SavedGasFees | undefined;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport type GetGasFeeRequest = UpdateGasFeesRequest & {\n initialParams: TransactionParams;\n savedGasFees?: SavedGasFees;\n suggestedGasFees: SuggestedGasFees;\n};\n\ntype SuggestedGasFees = {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n gasPrice?: string;\n};\n\nconst log = createModuleLogger(projectLogger, 'gas-fees');\n\n/**\n * Update the gas fee properties of the provided transaction meta.\n *\n * @param request - The request object.\n */\nexport async function updateGasFees(request: UpdateGasFeesRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const isSwap = SWAP_TRANSACTION_TYPES.includes(\n txMeta.type as TransactionType,\n );\n const savedGasFees = isSwap\n ? undefined\n : request.getSavedGasFees(txMeta.chainId);\n\n const suggestedGasFees = await getSuggestedGasFees(request);\n\n log('Suggested gas fees', suggestedGasFees);\n\n const getGasFeeRequest: GetGasFeeRequest = {\n ...request,\n initialParams,\n savedGasFees,\n suggestedGasFees,\n };\n\n txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.maxPriorityFeePerGas =\n getMaxPriorityFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.gasPrice = getGasPrice(getGasFeeRequest);\n txMeta.userFeeLevel = getUserFeeLevel(getGasFeeRequest);\n\n log('Updated gas fee properties', {\n maxFeePerGas: txMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: txMeta.txParams.maxPriorityFeePerGas,\n gasPrice: txMeta.txParams.gasPrice,\n });\n\n if (txMeta.txParams.maxFeePerGas || txMeta.txParams.maxPriorityFeePerGas) {\n delete txMeta.txParams.gasPrice;\n }\n\n if (txMeta.txParams.gasPrice) {\n delete txMeta.txParams.maxFeePerGas;\n delete txMeta.txParams.maxPriorityFeePerGas;\n }\n\n updateDefaultGasEstimates(txMeta);\n}\n\n/**\n * Convert GWEI from decimal string to WEI as hex string.\n *\n * @param value - The GWEI value as a decimal string.\n * @returns The WEI value in hex.\n */\nexport function gweiDecimalToWeiHex(value: string) {\n return toHex(gweiDecToWEIBN(value));\n}\n\n/**\n * Converts a value from Gwei decimal representation to Wei decimal representation\n *\n * @param gweiDecimal - The value in Gwei as a string or number\n * @returns The value in Wei as a string\n *\n * @example\n * // Convert 1.5 Gwei to Wei\n * gweiDecimalToWeiDecimal(\"1.5\")\n * // Returns \"1500000000\"\n */\nexport function gweiDecimalToWeiDecimal(gweiDecimal: string | number): string {\n const weiValue = Number(gweiDecimal) * 1e9;\n\n return weiValue.toString().split('.')[0];\n}\n\n/**\n * Determine the maxFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxFeePerGas value.\n */\nfunction getMaxFeePerGas(request: GetGasFeeRequest): string | undefined {\n const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee as string);\n log('Using maxFeePerGas from savedGasFees', maxFeePerGas);\n return maxFeePerGas;\n }\n\n if (initialParams.maxFeePerGas) {\n log('Using maxFeePerGas from request', initialParams.maxFeePerGas);\n return initialParams.maxFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxPriorityFeePerGas) {\n log(\n 'Setting maxFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log(\n 'Setting maxFeePerGas to suggested gasPrice',\n suggestedGasFees.gasPrice,\n );\n return suggestedGasFees.gasPrice;\n }\n\n log('maxFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the maxPriorityFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxPriorityFeePerGas value.\n */\nfunction getMaxPriorityFeePerGas(\n request: GetGasFeeRequest,\n): string | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);\n log(\n 'Using maxPriorityFeePerGas from savedGasFees.priorityFee',\n maxPriorityFeePerGas,\n );\n return maxPriorityFeePerGas;\n }\n\n if (initialParams.maxPriorityFeePerGas) {\n log(\n 'Using maxPriorityFeePerGas from request',\n initialParams.maxPriorityFeePerGas,\n );\n return initialParams.maxPriorityFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxPriorityFeePerGas) {\n log(\n 'Using suggested maxPriorityFeePerGas',\n suggestedGasFees.maxPriorityFeePerGas,\n );\n return suggestedGasFees.maxPriorityFeePerGas;\n }\n\n if (txMeta.txParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to maxFeePerGas',\n txMeta.txParams.maxFeePerGas,\n );\n return txMeta.txParams.maxFeePerGas;\n }\n\n log('maxPriorityFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the gasPrice value for the transaction.\n *\n * @param request - The request object.\n * @returns The gasPrice value.\n */\nfunction getGasPrice(request: GetGasFeeRequest): string | undefined {\n const { eip1559, initialParams, suggestedGasFees } = request;\n\n if (eip1559) {\n return undefined;\n }\n\n if (initialParams.gasPrice) {\n log('Using gasPrice from request', initialParams.gasPrice);\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log('Using suggested gasPrice', suggestedGasFees.gasPrice);\n return suggestedGasFees.gasPrice;\n }\n\n log('gasPrice not set');\n return undefined;\n}\n\n/**\n * Determine the user fee level.\n *\n * @param request - The request object.\n * @returns The user fee level.\n */\nfunction getUserFeeLevel(request: GetGasFeeRequest): UserFeeLevel | undefined {\n const { initialParams, savedGasFees, suggestedGasFees, txMeta } = request;\n\n if (savedGasFees) {\n return UserFeeLevel.CUSTOM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n initialParams.gasPrice\n ) {\n return txMeta.origin === ORIGIN_METAMASK\n ? UserFeeLevel.CUSTOM\n : UserFeeLevel.DAPP_SUGGESTED;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.maxFeePerGas &&\n suggestedGasFees.maxPriorityFeePerGas\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.gasPrice\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (txMeta.origin === ORIGIN_METAMASK) {\n return UserFeeLevel.MEDIUM;\n }\n\n return UserFeeLevel.DAPP_SUGGESTED;\n}\n\n/**\n * Update the default gas estimates for the provided transaction.\n *\n * @param txMeta - The transaction metadata.\n */\nfunction updateDefaultGasEstimates(txMeta: TransactionMeta) {\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.maxFeePerGas = txMeta.txParams.maxFeePerGas;\n\n txMeta.defaultGasEstimates.maxPriorityFeePerGas =\n txMeta.txParams.maxPriorityFeePerGas;\n\n txMeta.defaultGasEstimates.gasPrice = txMeta.txParams.gasPrice;\n txMeta.defaultGasEstimates.estimateType = txMeta.userFeeLevel;\n}\n\n/**\n * Retrieve the suggested gas fees using the gas fee flows.\n *\n * @param request - The request object.\n * @returns The suggested gas fees.\n */\nasync function getSuggestedGasFees(\n request: UpdateGasFeesRequest,\n): Promise<SuggestedGasFees> {\n const {\n eip1559,\n ethQuery,\n gasFeeFlows,\n getGasFeeEstimates,\n messenger,\n txMeta,\n } = request;\n\n const { networkClientId } = txMeta;\n\n if (\n (!eip1559 && txMeta.txParams.gasPrice) ||\n (eip1559 &&\n txMeta.txParams.maxFeePerGas &&\n txMeta.txParams.maxPriorityFeePerGas)\n ) {\n return {};\n }\n\n const gasFeeFlow = getGasFeeFlow(\n txMeta,\n gasFeeFlows,\n messenger,\n ) as GasFeeFlow;\n\n try {\n const gasFeeControllerData = await getGasFeeEstimates({ networkClientId });\n\n const response = await gasFeeFlow.getGasFees({\n ethQuery,\n gasFeeControllerData,\n messenger,\n transactionMeta: txMeta,\n });\n\n const gasFeeEstimateType = response.estimates?.type;\n\n switch (gasFeeEstimateType) {\n case GasFeeEstimateType.FeeMarket:\n return response.estimates.medium;\n case GasFeeEstimateType.Legacy:\n return {\n gasPrice: response.estimates.medium,\n };\n case GasFeeEstimateType.GasPrice:\n return { gasPrice: response.estimates.gasPrice };\n default:\n throw new Error(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Unsupported gas fee estimate type returned from flow: ${gasFeeEstimateType}`,\n );\n }\n } catch (error) {\n log('Failed to get suggested gas fees', error);\n }\n\n const gasPriceDecimal = (await query(ethQuery, 'gasPrice')) as number;\n\n const gasPrice = gasPriceDecimal\n ? add0x(gasPriceDecimal.toString(16))\n : undefined;\n\n return { gasPrice };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gas-fees.mjs","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,cAAc,EACd,KAAK,EACL,KAAK,EACN,mCAAmC;AAOpC,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,wBAAwB;AAE5D,OAAO,EAAE,aAAa,EAAE,uBAAmB;AAC3C,OAAO,EAAE,sBAAsB,EAAE,oBAAgB;AACjD,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAS1C,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,qBAAiB;AA0B5D,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,UAAU,CAAC,CAAC;AAE1D;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,OAA6B;IAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC3B,MAAM,aAAa,GAAG,EAAE,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;IAE7C,MAAM,MAAM,GAAG,sBAAsB,CAAC,QAAQ,CAC5C,MAAM,CAAC,I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f,GAAG,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC;IAED,MAAM,eAAe,GAAG,CAAC,MAAM,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAW,CAAC;IAEtE,MAAM,QAAQ,GAAG,eAAe;QAC9B,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACrC,CAAC,CAAC,SAAS,CAAC;IAEd,OAAO,EAAE,QAAQ,EAAE,CAAC;AACtB,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n gweiDecToWEIBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type {\n FetchGasFeeEstimateOptions,\n GasFeeState,\n} from '@metamask/gas-fee-controller';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\n\nimport { getGasFeeFlow } from './gas-flow';\nimport { SWAP_TRANSACTION_TYPES } from './swaps';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n SavedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionType,\n GasFeeFlow,\n} from '../types';\nimport { GasFeeEstimateType, UserFeeLevel } from '../types';\n\nexport type UpdateGasFeesRequest = {\n eip1559: boolean;\n ethQuery: EthQuery;\n gasFeeFlows: GasFeeFlow[];\n getGasFeeEstimates: (\n options: FetchGasFeeEstimateOptions,\n ) => Promise<GasFeeState>;\n getSavedGasFees: (chainId: Hex) => SavedGasFees | undefined;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport type GetGasFeeRequest = UpdateGasFeesRequest & {\n initialParams: TransactionParams;\n savedGasFees?: SavedGasFees;\n suggestedGasFees: SuggestedGasFees;\n};\n\ntype SuggestedGasFees = {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n gasPrice?: string;\n};\n\nconst log = createModuleLogger(projectLogger, 'gas-fees');\n\n/**\n * Update the gas fee properties of the provided transaction meta.\n *\n * @param request - The request object.\n */\nexport async function updateGasFees(request: UpdateGasFeesRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const isSwap = SWAP_TRANSACTION_TYPES.includes(\n txMeta.type as TransactionType,\n );\n const savedGasFees = isSwap\n ? undefined\n : request.getSavedGasFees(txMeta.chainId);\n\n const suggestedGasFees = await getSuggestedGasFees(request);\n\n log('Suggested gas fees', suggestedGasFees);\n\n const getGasFeeRequest: GetGasFeeRequest = {\n ...request,\n initialParams,\n savedGasFees,\n suggestedGasFees,\n };\n\n txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.maxPriorityFeePerGas =\n getMaxPriorityFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.gasPrice = getGasPrice(getGasFeeRequest);\n txMeta.userFeeLevel = getUserFeeLevel(getGasFeeRequest);\n\n log('Updated gas fee properties', {\n maxFeePerGas: txMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: txMeta.txParams.maxPriorityFeePerGas,\n gasPrice: txMeta.txParams.gasPrice,\n });\n\n if (txMeta.txParams.maxFeePerGas || txMeta.txParams.maxPriorityFeePerGas) {\n delete txMeta.txParams.gasPrice;\n }\n\n if (txMeta.txParams.gasPrice) {\n delete txMeta.txParams.maxFeePerGas;\n delete txMeta.txParams.maxPriorityFeePerGas;\n }\n\n updateDefaultGasEstimates(txMeta);\n}\n\n/**\n * Convert GWEI from decimal string to WEI as hex string.\n *\n * @param value - The GWEI value as a decimal string.\n * @returns The WEI value in hex.\n */\nexport function gweiDecimalToWeiHex(value: string) {\n return toHex(gweiDecToWEIBN(value));\n}\n\n/**\n * Converts a value from Gwei decimal representation to Wei decimal representation\n *\n * @param gweiDecimal - The value in Gwei as a string or number\n * @returns The value in Wei as a string\n *\n * @example\n * // Convert 1.5 Gwei to Wei\n * gweiDecimalToWeiDecimal(\"1.5\")\n * // Returns \"1500000000\"\n */\nexport function gweiDecimalToWeiDecimal(gweiDecimal: string | number): string {\n const weiValue = Number(gweiDecimal) * 1e9;\n\n return weiValue.toString().split('.')[0];\n}\n\n/**\n * Determine the maxFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxFeePerGas value.\n */\nfunction getMaxFeePerGas(request: GetGasFeeRequest): string | undefined {\n const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee);\n log('Using maxFeePerGas from savedGasFees', maxFeePerGas);\n return maxFeePerGas;\n }\n\n if (initialParams.maxFeePerGas) {\n log('Using maxFeePerGas from request', initialParams.maxFeePerGas);\n return initialParams.maxFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxPriorityFeePerGas) {\n log(\n 'Setting maxFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log(\n 'Setting maxFeePerGas to suggested gasPrice',\n suggestedGasFees.gasPrice,\n );\n return suggestedGasFees.gasPrice;\n }\n\n log('maxFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the maxPriorityFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxPriorityFeePerGas value.\n */\nfunction getMaxPriorityFeePerGas(\n request: GetGasFeeRequest,\n): string | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);\n log(\n 'Using maxPriorityFeePerGas from savedGasFees.priorityFee',\n maxPriorityFeePerGas,\n );\n return maxPriorityFeePerGas;\n }\n\n if (initialParams.maxPriorityFeePerGas) {\n log(\n 'Using maxPriorityFeePerGas from request',\n initialParams.maxPriorityFeePerGas,\n );\n return initialParams.maxPriorityFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxPriorityFeePerGas) {\n log(\n 'Using suggested maxPriorityFeePerGas',\n suggestedGasFees.maxPriorityFeePerGas,\n );\n return suggestedGasFees.maxPriorityFeePerGas;\n }\n\n if (txMeta.txParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to maxFeePerGas',\n txMeta.txParams.maxFeePerGas,\n );\n return txMeta.txParams.maxFeePerGas;\n }\n\n log('maxPriorityFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the gasPrice value for the transaction.\n *\n * @param request - The request object.\n * @returns The gasPrice value.\n */\nfunction getGasPrice(request: GetGasFeeRequest): string | undefined {\n const { eip1559, initialParams, suggestedGasFees } = request;\n\n if (eip1559) {\n return undefined;\n }\n\n if (initialParams.gasPrice) {\n log('Using gasPrice from request', initialParams.gasPrice);\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log('Using suggested gasPrice', suggestedGasFees.gasPrice);\n return suggestedGasFees.gasPrice;\n }\n\n log('gasPrice not set');\n return undefined;\n}\n\n/**\n * Determine the user fee level.\n *\n * @param request - The request object.\n * @returns The user fee level.\n */\nfunction getUserFeeLevel(request: GetGasFeeRequest): UserFeeLevel | undefined {\n const { initialParams, savedGasFees, suggestedGasFees, txMeta } = request;\n\n if (savedGasFees) {\n return UserFeeLevel.CUSTOM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n initialParams.gasPrice\n ) {\n return txMeta.origin === ORIGIN_METAMASK\n ? UserFeeLevel.CUSTOM\n : UserFeeLevel.DAPP_SUGGESTED;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.maxFeePerGas &&\n suggestedGasFees.maxPriorityFeePerGas\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.gasPrice\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (txMeta.origin === ORIGIN_METAMASK) {\n return UserFeeLevel.MEDIUM;\n }\n\n return UserFeeLevel.DAPP_SUGGESTED;\n}\n\n/**\n * Update the default gas estimates for the provided transaction.\n *\n * @param txMeta - The transaction metadata.\n */\nfunction updateDefaultGasEstimates(txMeta: TransactionMeta) {\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.maxFeePerGas = txMeta.txParams.maxFeePerGas;\n\n txMeta.defaultGasEstimates.maxPriorityFeePerGas =\n txMeta.txParams.maxPriorityFeePerGas;\n\n txMeta.defaultGasEstimates.gasPrice = txMeta.txParams.gasPrice;\n txMeta.defaultGasEstimates.estimateType = txMeta.userFeeLevel;\n}\n\n/**\n * Retrieve the suggested gas fees using the gas fee flows.\n *\n * @param request - The request object.\n * @returns The suggested gas fees.\n */\nasync function getSuggestedGasFees(\n request: UpdateGasFeesRequest,\n): Promise<SuggestedGasFees> {\n const {\n eip1559,\n ethQuery,\n gasFeeFlows,\n getGasFeeEstimates,\n messenger,\n txMeta,\n } = request;\n\n const { networkClientId } = txMeta;\n\n if (\n (!eip1559 && txMeta.txParams.gasPrice) ||\n (eip1559 &&\n txMeta.txParams.maxFeePerGas &&\n txMeta.txParams.maxPriorityFeePerGas)\n ) {\n return {};\n }\n\n const gasFeeFlow = getGasFeeFlow(\n txMeta,\n gasFeeFlows,\n messenger,\n ) as GasFeeFlow;\n\n try {\n const gasFeeControllerData = await getGasFeeEstimates({ networkClientId });\n\n const response = await gasFeeFlow.getGasFees({\n ethQuery,\n gasFeeControllerData,\n messenger,\n transactionMeta: txMeta,\n });\n\n const gasFeeEstimateType = response.estimates?.type;\n\n switch (gasFeeEstimateType) {\n case GasFeeEstimateType.FeeMarket:\n return response.estimates.medium;\n case GasFeeEstimateType.Legacy:\n return {\n gasPrice: response.estimates.medium,\n };\n case GasFeeEstimateType.GasPrice:\n return { gasPrice: response.estimates.gasPrice };\n default:\n throw new Error(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Unsupported gas fee estimate type returned from flow: ${gasFeeEstimateType}`,\n );\n }\n } catch (error) {\n log('Failed to get suggested gas fees', error);\n }\n\n const gasPriceDecimal = (await query(ethQuery, 'gasPrice')) as number;\n\n const gasPrice = gasPriceDecimal\n ? add0x(gasPriceDecimal.toString(16))\n : undefined;\n\n return { gasPrice };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas-flow.cjs","sourceRoot":"","sources":["../../src/utils/gas-flow.ts"],"names":[],"mappings":";;;AAAA,iEAA6D;
|
|
1
|
+
{"version":3,"file":"gas-flow.cjs","sourceRoot":"","sources":["../../src/utils/gas-flow.ts"],"names":[],"mappings":";;;AAAA,iEAA6D;AAU7D,wCAAmE;AAuBnE;;;;;;;GAOG;AACH,SAAgB,aAAa,CAC3B,eAAgC,EAChC,WAAyB,EACzB,SAAyC;IAEzC,OAAO,WAAW,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CACrC,UAAU,CAAC,kBAAkB,CAAC,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC,CAC9D,CAAC;AACJ,CAAC;AARD,sCAQC;AAED;;;;;;;GAOG;AACH,SAAgB,oBAAoB,CAAC,EACnC,yBAAyB,EACzB,0BAA0B,GACE;IAC5B,MAAM,uBAAuB,GAAG,0BAA0B,CAAC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B,OAAO,IAAA,kCAAe,EAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED;;;;;GAKG;AACH,SAAS,mBAAmB,CAC1B,yBAAkD;IAElD,OAAO,IAAA,kCAAe,EAAC,yBAAyB,CAAC,QAAQ,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { weiHexToGweiDec } from '@metamask/controller-utils';\nimport type {\n Eip1559GasFee,\n EthGasPriceEstimate,\n GasFeeEstimates,\n LegacyGasPriceEstimate,\n} from '@metamask/gas-fee-controller';\nimport type { GasFeeState } from '@metamask/gas-fee-controller';\n\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport { GasFeeEstimateLevel, GasFeeEstimateType } from '../types';\nimport type {\n FeeMarketGasFeeEstimates,\n GasPriceGasFeeEstimates,\n LegacyGasFeeEstimates,\n} from '../types';\nimport type {\n GasFeeFlow,\n TransactionMeta,\n FeeMarketGasFeeEstimateForLevel,\n} from '../types';\n\ntype MergeGasFeeEstimatesRequest = {\n gasFeeControllerEstimates:\n | GasFeeEstimates\n | LegacyGasPriceEstimate\n | EthGasPriceEstimate;\n transactionGasFeeEstimates:\n | FeeMarketGasFeeEstimates\n | LegacyGasFeeEstimates\n | GasPriceGasFeeEstimates;\n};\n\n/**\n * Returns the first gas fee flow that matches the transaction.\n *\n * @param transactionMeta - The transaction metadata to find a gas fee flow for.\n * @param gasFeeFlows - The gas fee flows to search.\n * @param messenger - The messenger instance.\n * @returns The first gas fee flow that matches the transaction, or undefined if none match.\n */\nexport function getGasFeeFlow(\n transactionMeta: TransactionMeta,\n gasFeeFlows: GasFeeFlow[],\n messenger: TransactionControllerMessenger,\n): GasFeeFlow | undefined {\n return gasFeeFlows.find((gasFeeFlow) =>\n gasFeeFlow.matchesTransaction({ transactionMeta, messenger }),\n );\n}\n\n/**\n * Merge the gas fee estimates from the gas fee controller with the gas fee estimates from a transaction.\n *\n * @param request - Data required to merge gas fee estimates.\n * @param request.gasFeeControllerEstimates - Gas fee estimates from the GasFeeController.\n * @param request.transactionGasFeeEstimates - Gas fee estimates from the transaction.\n * @returns The merged gas fee estimates.\n */\nexport function mergeGasFeeEstimates({\n gasFeeControllerEstimates,\n transactionGasFeeEstimates,\n}: MergeGasFeeEstimatesRequest): GasFeeState['gasFeeEstimates'] {\n const transactionEstimateType = transactionGasFeeEstimates.type;\n\n if (transactionEstimateType === GasFeeEstimateType.FeeMarket) {\n return Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: mergeFeeMarketEstimate(\n (gasFeeControllerEstimates as GasFeeEstimates)?.[level],\n transactionGasFeeEstimates[level],\n ),\n }),\n { ...gasFeeControllerEstimates } as GasFeeEstimates,\n );\n }\n\n if (transactionEstimateType === GasFeeEstimateType.Legacy) {\n return Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: getLegacyEstimate(transactionGasFeeEstimates, level),\n }),\n {} as LegacyGasPriceEstimate,\n );\n }\n\n if (transactionEstimateType === GasFeeEstimateType.GasPrice) {\n return {\n gasPrice: getGasPriceEstimate(transactionGasFeeEstimates),\n };\n }\n\n return gasFeeControllerEstimates;\n}\n\n/**\n * Merge a specific priority level of EIP-1559 gas fee estimates.\n *\n * @param gasFeeControllerEstimate - The gas fee estimate from the gas fee controller.\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @returns The merged gas fee estimate.\n */\nfunction mergeFeeMarketEstimate(\n gasFeeControllerEstimate: Eip1559GasFee | undefined,\n transactionGasFeeEstimate: FeeMarketGasFeeEstimateForLevel,\n): Eip1559GasFee {\n return {\n ...gasFeeControllerEstimate,\n suggestedMaxFeePerGas: weiHexToGweiDec(\n transactionGasFeeEstimate.maxFeePerGas,\n ),\n suggestedMaxPriorityFeePerGas: weiHexToGweiDec(\n transactionGasFeeEstimate.maxPriorityFeePerGas,\n ),\n } as Eip1559GasFee;\n}\n\n/**\n * Generate a specific priority level for a legacy gas fee estimate.\n *\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @param level - The gas fee estimate level.\n * @returns The legacy gas fee estimate.\n */\nfunction getLegacyEstimate(\n transactionGasFeeEstimate: LegacyGasFeeEstimates,\n level: GasFeeEstimateLevel,\n): string {\n return weiHexToGweiDec(transactionGasFeeEstimate[level]);\n}\n\n/**\n * Generate the value for a gas price gas fee estimate.\n *\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @returns The legacy gas fee estimate.\n */\nfunction getGasPriceEstimate(\n transactionGasFeeEstimate: GasPriceGasFeeEstimates,\n): string {\n return weiHexToGweiDec(transactionGasFeeEstimate.gasPrice);\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { EthGasPriceEstimate, GasFeeEstimates, LegacyGasPriceEstimate } from "@metamask/gas-fee-controller";
|
|
2
|
-
import {
|
|
2
|
+
import type { GasFeeState } from "@metamask/gas-fee-controller";
|
|
3
3
|
import type { TransactionControllerMessenger } from "../TransactionController.cjs";
|
|
4
4
|
import type { FeeMarketGasFeeEstimates, GasPriceGasFeeEstimates, LegacyGasFeeEstimates } from "../types.cjs";
|
|
5
|
-
import {
|
|
5
|
+
import type { GasFeeFlow, TransactionMeta } from "../types.cjs";
|
|
6
6
|
type MergeGasFeeEstimatesRequest = {
|
|
7
7
|
gasFeeControllerEstimates: GasFeeEstimates | LegacyGasPriceEstimate | EthGasPriceEstimate;
|
|
8
8
|
transactionGasFeeEstimates: FeeMarketGasFeeEstimates | LegacyGasFeeEstimates | GasPriceGasFeeEstimates;
|