@metamask/transaction-controller 32.0.0 → 33.0.1
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 +30 -1
- package/dist/TransactionController.js +17 -17
- package/dist/TransactionController.mjs +16 -16
- package/dist/{chunk-7MKQDZKY.js → chunk-2EU6346V.js} +3 -3
- package/dist/{chunk-Y7ENNK7L.mjs → chunk-3ZV5YEUV.mjs} +6 -5
- package/dist/chunk-3ZV5YEUV.mjs.map +1 -0
- package/dist/{chunk-AZ4WIRH3.mjs → chunk-4V4XIPCI.mjs} +5 -2
- package/dist/chunk-4V4XIPCI.mjs.map +1 -0
- package/dist/{chunk-NM6OYEPP.mjs → chunk-5ZEJT5SN.mjs} +6 -2
- package/dist/chunk-5ZEJT5SN.mjs.map +1 -0
- package/dist/{chunk-5YES3V2R.mjs → chunk-6B5BEO3R.mjs} +1 -1
- package/dist/chunk-6B5BEO3R.mjs.map +1 -0
- package/dist/{chunk-PUESYN62.js → chunk-6OLJWLKK.js} +6 -3
- package/dist/chunk-6OLJWLKK.js.map +1 -0
- package/dist/{chunk-METHOFMG.mjs → chunk-6SJYXSF3.mjs} +6 -6
- package/dist/chunk-6SJYXSF3.mjs.map +1 -0
- package/dist/{chunk-IT3SYNZ6.js → chunk-74W7X6BE.js} +1 -1
- package/dist/chunk-74W7X6BE.js.map +1 -0
- package/dist/{chunk-DLOQPH4M.js → chunk-76FONEDA.js} +4 -4
- package/dist/{chunk-EQT25RSP.js → chunk-7NMV2NPM.js} +6 -4
- package/dist/chunk-7NMV2NPM.js.map +1 -0
- package/dist/{chunk-Q6Q44V4W.js → chunk-ARZHJFVG.js} +6 -6
- package/dist/{chunk-RAOYRJ25.js → chunk-AYTU4HU5.js} +6 -6
- package/dist/chunk-AYTU4HU5.js.map +1 -0
- package/dist/{chunk-3ZRHCVVS.js → chunk-C3WC4OJ3.js} +7 -5
- package/dist/chunk-C3WC4OJ3.js.map +1 -0
- package/dist/{chunk-QZLPYOGC.mjs → chunk-EGQCE3FK.mjs} +1 -1
- package/dist/chunk-EGQCE3FK.mjs.map +1 -0
- package/dist/{chunk-CPMTUMMZ.mjs → chunk-EKJXGERC.mjs} +4 -2
- package/dist/chunk-EKJXGERC.mjs.map +1 -0
- package/dist/{chunk-AHSDUIMT.mjs → chunk-EVL6KODQ.mjs} +1 -1
- package/dist/chunk-EVL6KODQ.mjs.map +1 -0
- package/dist/{chunk-IJ5GUKRO.mjs → chunk-GNAL5HC2.mjs} +2 -2
- package/dist/{chunk-V6HVF4EN.mjs → chunk-H2KZOK3J.mjs} +3 -3
- package/dist/chunk-H2KZOK3J.mjs.map +1 -0
- package/dist/{chunk-CDF4QNJA.mjs → chunk-JXXTNVU4.mjs} +2 -2
- package/dist/{chunk-UGFBA4GV.js → chunk-OZ6UB42C.js} +5 -1
- package/dist/chunk-OZ6UB42C.js.map +1 -0
- package/dist/{chunk-J56A7UCK.mjs → chunk-Q56I5ONX.mjs} +5 -1
- package/dist/chunk-Q56I5ONX.mjs.map +1 -0
- package/dist/{chunk-UT4M4XI3.js → chunk-QH2H4W3N.js} +5 -5
- package/dist/{chunk-YXSCBWTU.js → chunk-QTKXIDGE.js} +9 -9
- package/dist/{chunk-YXSCBWTU.js.map → chunk-QTKXIDGE.js.map} +1 -1
- package/dist/{chunk-DTDTOMTB.js → chunk-RHDPOIS4.js} +6 -5
- package/dist/chunk-RHDPOIS4.js.map +1 -0
- package/dist/{chunk-VH47Q6TS.js → chunk-RXIUMVA5.js} +7 -3
- package/dist/chunk-RXIUMVA5.js.map +1 -0
- package/dist/{chunk-PBYK4OMK.js → chunk-S7Q622IS.js} +83 -71
- package/dist/chunk-S7Q622IS.js.map +1 -0
- package/dist/{chunk-NRQUBP3S.mjs → chunk-SFFTNB2X.mjs} +2 -2
- package/dist/{chunk-2TUDWNEI.mjs → chunk-UHG2LLVV.mjs} +3 -3
- package/dist/{chunk-PQCHA5KF.mjs → chunk-UKV5HIMT.mjs} +38 -26
- package/dist/chunk-UKV5HIMT.mjs.map +1 -0
- package/dist/{chunk-5KMU2IAT.js → chunk-ULD4JC3Q.js} +1 -1
- package/dist/chunk-ULD4JC3Q.js.map +1 -0
- package/dist/{chunk-G5U6ABRU.mjs → chunk-VXNPVIYL.mjs} +5 -3
- package/dist/{chunk-G5U6ABRU.mjs.map → chunk-VXNPVIYL.mjs.map} +1 -1
- package/dist/{chunk-FDUCRHYT.js → chunk-XVYXRCRL.js} +1 -1
- package/dist/chunk-XVYXRCRL.js.map +1 -0
- package/dist/errors.js +1 -1
- package/dist/errors.mjs +1 -1
- package/dist/gas-flows/DefaultGasFeeFlow.js +7 -7
- package/dist/gas-flows/DefaultGasFeeFlow.mjs +6 -6
- package/dist/gas-flows/LineaGasFeeFlow.js +8 -8
- package/dist/gas-flows/LineaGasFeeFlow.mjs +7 -7
- package/dist/gas-flows/TestGasFeeFlow.js +1 -1
- package/dist/gas-flows/TestGasFeeFlow.mjs +1 -1
- package/dist/helpers/EtherscanRemoteTransactionSource.js +4 -4
- package/dist/helpers/EtherscanRemoteTransactionSource.mjs +3 -3
- package/dist/helpers/GasFeePoller.js +4 -4
- package/dist/helpers/GasFeePoller.mjs +3 -3
- package/dist/helpers/IncomingTransactionHelper.js +2 -2
- package/dist/helpers/IncomingTransactionHelper.mjs +1 -1
- package/dist/helpers/MultichainTrackingHelper.js +5 -5
- package/dist/helpers/MultichainTrackingHelper.mjs +4 -4
- package/dist/helpers/PendingTransactionTracker.js +3 -3
- package/dist/helpers/PendingTransactionTracker.mjs +2 -2
- package/dist/index.js +17 -17
- package/dist/index.mjs +16 -16
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/TransactionController.d.ts +3 -5
- package/dist/types/TransactionController.d.ts.map +1 -1
- package/dist/types/gas-flows/DefaultGasFeeFlow.d.ts.map +1 -1
- package/dist/types/helpers/EtherscanRemoteTransactionSource.d.ts.map +1 -1
- package/dist/types/helpers/IncomingTransactionHelper.d.ts +2 -1
- package/dist/types/helpers/IncomingTransactionHelper.d.ts.map +1 -1
- package/dist/types/helpers/MultichainTrackingHelper.d.ts.map +1 -1
- package/dist/types/helpers/PendingTransactionTracker.d.ts.map +1 -1
- package/dist/types/types.d.ts +45 -9
- package/dist/types/types.d.ts.map +1 -1
- package/dist/types/utils/etherscan.d.ts.map +1 -1
- package/dist/types/utils/simulation.d.ts.map +1 -1
- package/dist/types/utils/utils.d.ts.map +1 -1
- package/dist/types.js +2 -2
- package/dist/types.mjs +1 -1
- package/dist/utils/etherscan.js +2 -2
- package/dist/utils/etherscan.mjs +1 -1
- package/dist/utils/external-transactions.js +1 -1
- package/dist/utils/external-transactions.mjs +1 -1
- package/dist/utils/gas-fees.js +6 -6
- package/dist/utils/gas-fees.mjs +5 -5
- package/dist/utils/gas-flow.js +3 -3
- package/dist/utils/gas-flow.mjs +2 -2
- package/dist/utils/simulation-api.js +1 -1
- package/dist/utils/simulation-api.mjs +1 -1
- package/dist/utils/simulation.js +3 -3
- package/dist/utils/simulation.mjs +2 -2
- package/dist/utils/swaps.js +4 -4
- package/dist/utils/swaps.mjs +3 -3
- package/dist/utils/transaction-type.js +1 -1
- package/dist/utils/transaction-type.mjs +1 -1
- package/dist/utils/utils.js +3 -3
- package/dist/utils/utils.mjs +2 -2
- package/dist/utils/validation.js +4 -4
- package/dist/utils/validation.mjs +3 -3
- package/package.json +5 -1
- package/dist/chunk-3ZRHCVVS.js.map +0 -1
- package/dist/chunk-5KMU2IAT.js.map +0 -1
- package/dist/chunk-5YES3V2R.mjs.map +0 -1
- package/dist/chunk-AHSDUIMT.mjs.map +0 -1
- package/dist/chunk-AZ4WIRH3.mjs.map +0 -1
- package/dist/chunk-CPMTUMMZ.mjs.map +0 -1
- package/dist/chunk-DTDTOMTB.js.map +0 -1
- package/dist/chunk-EQT25RSP.js.map +0 -1
- package/dist/chunk-FDUCRHYT.js.map +0 -1
- package/dist/chunk-IT3SYNZ6.js.map +0 -1
- package/dist/chunk-J56A7UCK.mjs.map +0 -1
- package/dist/chunk-METHOFMG.mjs.map +0 -1
- package/dist/chunk-NM6OYEPP.mjs.map +0 -1
- package/dist/chunk-PBYK4OMK.js.map +0 -1
- package/dist/chunk-PQCHA5KF.mjs.map +0 -1
- package/dist/chunk-PUESYN62.js.map +0 -1
- package/dist/chunk-QZLPYOGC.mjs.map +0 -1
- package/dist/chunk-RAOYRJ25.js.map +0 -1
- package/dist/chunk-UGFBA4GV.js.map +0 -1
- package/dist/chunk-V6HVF4EN.mjs.map +0 -1
- package/dist/chunk-VH47Q6TS.js.map +0 -1
- package/dist/chunk-Y7ENNK7L.mjs.map +0 -1
- /package/dist/{chunk-7MKQDZKY.js.map → chunk-2EU6346V.js.map} +0 -0
- /package/dist/{chunk-DLOQPH4M.js.map → chunk-76FONEDA.js.map} +0 -0
- /package/dist/{chunk-Q6Q44V4W.js.map → chunk-ARZHJFVG.js.map} +0 -0
- /package/dist/{chunk-IJ5GUKRO.mjs.map → chunk-GNAL5HC2.mjs.map} +0 -0
- /package/dist/{chunk-CDF4QNJA.mjs.map → chunk-JXXTNVU4.mjs.map} +0 -0
- /package/dist/{chunk-UT4M4XI3.js.map → chunk-QH2H4W3N.js.map} +0 -0
- /package/dist/{chunk-NRQUBP3S.mjs.map → chunk-SFFTNB2X.mjs.map} +0 -0
- /package/dist/{chunk-2TUDWNEI.mjs.map → chunk-UHG2LLVV.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/simulation.ts"],"sourcesContent":["import type { Fragment, LogDescription, Result } from '@ethersproject/abi';\nimport { Interface } from '@ethersproject/abi';\nimport { hexToBN, toHex } from '@metamask/controller-utils';\nimport { abiERC20, abiERC721, abiERC1155 } from '@metamask/metamask-eth-abis';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport {\n ABI_SIMULATION_ERC20_WRAPPED,\n ABI_SIMULATION_ERC721_LEGACY,\n} from '../constants';\nimport {\n SimulationError,\n SimulationInvalidResponseError,\n SimulationRevertedError,\n} from '../errors';\nimport { projectLogger } from '../logger';\nimport type {\n SimulationBalanceChange,\n SimulationData,\n SimulationTokenBalanceChange,\n SimulationToken,\n} from '../types';\nimport { SimulationTokenStandard } from '../types';\nimport { simulateTransactions } from './simulation-api';\nimport type {\n SimulationResponseLog,\n SimulationRequestTransaction,\n SimulationResponse,\n SimulationResponseCallTrace,\n SimulationResponseTransaction,\n} from './simulation-api';\n\nexport enum SupportedToken {\n ERC20 = 'erc20',\n ERC721 = 'erc721',\n ERC1155 = 'erc1155',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ERC20_WRAPPED = 'erc20Wrapped',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ERC721_LEGACY = 'erc721Legacy',\n}\n\ntype ABI = Fragment[];\n\nexport type GetSimulationDataRequest = {\n chainId: Hex;\n from: Hex;\n to?: Hex;\n value?: Hex;\n data?: Hex;\n};\n\ntype ParsedEvent = {\n contractAddress: Hex;\n tokenStandard: SimulationTokenStandard;\n name: string;\n args: Record<string, Hex | Hex[]>;\n abi: ABI;\n};\n\nconst log = createModuleLogger(projectLogger, 'simulation');\n\nconst SUPPORTED_EVENTS = [\n 'Transfer',\n 'TransferSingle',\n 'TransferBatch',\n 'Deposit',\n 'Withdrawal',\n];\n\nconst SUPPORTED_TOKEN_ABIS = {\n [SupportedToken.ERC20]: {\n abi: abiERC20,\n standard: SimulationTokenStandard.erc20,\n },\n [SupportedToken.ERC721]: {\n abi: abiERC721,\n standard: SimulationTokenStandard.erc721,\n },\n [SupportedToken.ERC1155]: {\n abi: abiERC1155,\n standard: SimulationTokenStandard.erc1155,\n },\n [SupportedToken.ERC20_WRAPPED]: {\n abi: ABI_SIMULATION_ERC20_WRAPPED,\n standard: SimulationTokenStandard.erc20,\n },\n [SupportedToken.ERC721_LEGACY]: {\n abi: ABI_SIMULATION_ERC721_LEGACY,\n standard: SimulationTokenStandard.erc721,\n },\n};\n\nconst REVERTED_ERRORS = ['execution reverted', 'insufficient funds for gas'];\n\ntype BalanceTransactionMap = Map<SimulationToken, SimulationRequestTransaction>;\n\n/**\n * Generate simulation data for a transaction.\n * @param request - The transaction to simulate.\n * @param request.chainId - The chain ID of the transaction.\n * @param request.from - The sender of the transaction.\n * @param request.to - The recipient of the transaction.\n * @param request.value - The value of the transaction.\n * @param request.data - The data of the transaction.\n * @returns The simulation data.\n */\nexport async function getSimulationData(\n request: GetSimulationDataRequest,\n): Promise<SimulationData> {\n const { chainId, from, to, value, data } = request;\n\n log('Getting simulation data', request);\n\n try {\n const response = await simulateTransactions(chainId, {\n transactions: [\n {\n data,\n from,\n maxFeePerGas: '0x0',\n maxPriorityFeePerGas: '0x0',\n to,\n value,\n },\n ],\n withCallTrace: true,\n withLogs: true,\n });\n\n const transactionError = response.transactions?.[0]?.error;\n\n if (transactionError) {\n throw new SimulationError(transactionError);\n }\n\n const nativeBalanceChange = getNativeBalanceChange(request.from, response);\n const events = getEvents(response);\n\n log('Parsed events', events);\n\n const tokenBalanceChanges = await getTokenBalanceChanges(request, events);\n\n return {\n nativeBalanceChange,\n tokenBalanceChanges,\n };\n } catch (error) {\n log('Failed to get simulation data', error, request);\n\n let simulationError = error as SimulationError;\n\n if (\n REVERTED_ERRORS.some((revertErrorMessage) =>\n simulationError.message?.includes(revertErrorMessage),\n )\n ) {\n simulationError = new SimulationRevertedError();\n }\n\n const { code, message } = simulationError;\n\n return {\n tokenBalanceChanges: [],\n error: {\n code,\n message,\n },\n };\n }\n}\n\n/**\n * Extract the native balance change from a simulation response.\n * @param userAddress - The user's account address.\n * @param response - The simulation response.\n * @returns The native balance change or undefined if unchanged.\n */\nfunction getNativeBalanceChange(\n userAddress: Hex,\n response: SimulationResponse,\n): SimulationBalanceChange | undefined {\n const transactionResponse = response.transactions[0];\n\n /* istanbul ignore next */\n if (!transactionResponse) {\n return undefined;\n }\n\n const { stateDiff } = transactionResponse;\n const previousBalance = stateDiff?.pre?.[userAddress]?.balance;\n const newBalance = stateDiff?.post?.[userAddress]?.balance;\n\n if (!previousBalance || !newBalance) {\n return undefined;\n }\n\n return getSimulationBalanceChange(previousBalance, newBalance);\n}\n\n/**\n * Extract events from a simulation response.\n * @param response - The simulation response.\n * @returns The parsed events.\n */\nexport function getEvents(response: SimulationResponse): ParsedEvent[] {\n /* istanbul ignore next */\n const logs = extractLogs(\n response.transactions[0]?.callTrace ?? ({} as SimulationResponseCallTrace),\n );\n\n log('Extracted logs', logs);\n\n const interfaces = getContractInterfaces();\n\n return logs\n .map((currentLog) => {\n const event = parseLog(currentLog, interfaces);\n\n if (!event) {\n log('Failed to parse log', currentLog);\n return undefined;\n }\n\n /* istanbul ignore next */\n const inputs = event.abi.find((e) => e.name === event.name)?.inputs;\n\n /* istanbul ignore if */\n if (!inputs) {\n log('Failed to find inputs for event', event);\n return undefined;\n }\n\n const args = parseEventArgs(event.args, inputs);\n\n return {\n contractAddress: currentLog.address,\n tokenStandard: event.standard,\n name: event.name,\n args,\n abi: event.abi,\n };\n })\n .filter((e) => e !== undefined) as ParsedEvent[];\n}\n\n/**\n * Parse event arguments using ABI input definitions.\n * @param args - The raw event arguments.\n * @param abiInputs - The ABI input definitions.\n * @returns The parsed event arguments.\n */\nfunction parseEventArgs(\n args: Result,\n abiInputs: { name: string }[],\n): Record<string, Hex | Hex[]> {\n return args.reduce((result, arg, index) => {\n const name = abiInputs[index].name.replace('_', '');\n const value = parseEventArgValue(arg);\n\n result[name] = value;\n\n return result;\n }, {});\n}\n\n/**\n * Parse an event argument value.\n * @param value - The event argument value.\n * @returns The parsed event argument value.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction parseEventArgValue(value: any): Hex | Hex[] {\n if (Array.isArray(value)) {\n return value.map(parseEventArgValue) as Hex[];\n }\n\n return (value.toHexString?.() ?? value).toLowerCase();\n}\n\n/**\n * Generate token balance changes from parsed events.\n * @param request - The transaction that was simulated.\n * @param events - The parsed events.\n * @returns An array of token balance changes.\n */\nasync function getTokenBalanceChanges(\n request: GetSimulationDataRequest,\n events: ParsedEvent[],\n): Promise<SimulationTokenBalanceChange[]> {\n const balanceTxs = getTokenBalanceTransactions(request, events);\n\n log('Generated balance transactions', [...balanceTxs.after.values()]);\n\n const transactions = [\n ...balanceTxs.before.values(),\n request,\n ...balanceTxs.after.values(),\n ];\n\n if (transactions.length === 1) {\n return [];\n }\n\n const response = await simulateTransactions(request.chainId as Hex, {\n transactions,\n });\n\n log('Balance simulation response', response);\n\n if (response.transactions.length !== transactions.length) {\n throw new SimulationInvalidResponseError();\n }\n\n let prevBalanceTxIndex = 0;\n return [...balanceTxs.after.keys()]\n .map((token, index) => {\n const previousBalanceCheckSkipped = !balanceTxs.before.get(token);\n const previousBalance = previousBalanceCheckSkipped\n ? '0x0'\n : getValueFromBalanceTransaction(\n request.from,\n token,\n // eslint-disable-next-line no-plusplus\n response.transactions[prevBalanceTxIndex++],\n );\n\n const newBalance = getValueFromBalanceTransaction(\n request.from,\n token,\n response.transactions[index + balanceTxs.before.size + 1],\n );\n\n const balanceChange = getSimulationBalanceChange(\n previousBalance,\n newBalance,\n );\n\n if (!balanceChange) {\n return undefined;\n }\n\n return {\n ...token,\n ...balanceChange,\n };\n })\n .filter((change) => change !== undefined) as SimulationTokenBalanceChange[];\n}\n\n/**\n * Generate transactions to check token balances.\n * @param request - The transaction that was simulated.\n * @param events - The parsed events.\n * @returns A map of token balance transactions keyed by token.\n */\nfunction getTokenBalanceTransactions(\n request: GetSimulationDataRequest,\n events: ParsedEvent[],\n): {\n before: BalanceTransactionMap;\n after: BalanceTransactionMap;\n} {\n const tokenKeys = new Set();\n const before = new Map();\n const after = new Map();\n\n const userEvents = events.filter(\n (event) =>\n SUPPORTED_EVENTS.includes(event.name) &&\n [event.args.from, event.args.to].includes(request.from),\n );\n\n log('Filtered user events', userEvents);\n\n for (const event of userEvents) {\n const tokenIds = getEventTokenIds(event);\n\n log('Extracted token ids', tokenIds);\n\n for (const tokenId of tokenIds) {\n const simulationToken: SimulationToken = {\n address: event.contractAddress,\n standard: event.tokenStandard,\n id: tokenId,\n };\n\n const tokenKey = JSON.stringify(simulationToken);\n\n if (tokenKeys.has(tokenKey)) {\n log(\n 'Ignoring additional event with same contract and token ID',\n simulationToken,\n );\n continue;\n }\n\n tokenKeys.add(tokenKey);\n\n const data = getBalanceTransactionData(\n event.tokenStandard,\n request.from,\n tokenId,\n );\n\n const transaction: SimulationRequestTransaction = {\n from: request.from,\n to: event.contractAddress,\n data,\n };\n\n if (skipPriorBalanceCheck(event)) {\n after.set(simulationToken, transaction);\n } else {\n before.set(simulationToken, transaction);\n after.set(simulationToken, transaction);\n }\n }\n }\n\n return { before, after };\n}\n\n/**\n * Check if an event needs to check the previous balance.\n * @param event - The parsed event.\n * @returns True if the prior balance check should be skipped.\n */\nfunction skipPriorBalanceCheck(event: ParsedEvent): boolean {\n // In the case of an NFT mint, we cannot check the NFT owner before the mint\n // as the balance check transaction would revert.\n return (\n event.name === 'Transfer' &&\n event.tokenStandard === SimulationTokenStandard.erc721 &&\n parseInt(event.args.from as string, 16) === 0\n );\n}\n\n/**\n * Extract token IDs from a parsed event.\n * @param event - The parsed event.\n * @returns An array of token IDs.\n */\nfunction getEventTokenIds(event: ParsedEvent): (Hex | undefined)[] {\n if (event.tokenStandard === SimulationTokenStandard.erc721) {\n return [event.args.tokenId as Hex];\n }\n\n if (\n event.tokenStandard === SimulationTokenStandard.erc1155 &&\n event.name === 'TransferSingle'\n ) {\n return [event.args.id as Hex];\n }\n\n if (\n event.tokenStandard === SimulationTokenStandard.erc1155 &&\n event.name === 'TransferBatch'\n ) {\n return event.args.ids as Hex[];\n }\n\n // ERC-20 does not have a token ID so default to undefined.\n return [undefined];\n}\n\n/**\n * Extract the value from a balance transaction response.\n * @param from - The address to check the balance of.\n * @param token - The token to check the balance of.\n * @param response - The balance transaction response.\n * @returns The value of the balance transaction.\n */\nfunction getValueFromBalanceTransaction(\n from: Hex,\n token: SimulationToken,\n response: SimulationResponseTransaction,\n): Hex {\n const normalizedReturn = normalizeReturnValue(response.return);\n\n if (token.standard === SimulationTokenStandard.erc721) {\n return normalizedReturn === from ? '0x1' : '0x0';\n }\n\n return normalizedReturn;\n}\n\n/**\n * Generate the balance transaction data for a token.\n * @param tokenStandard - The token standard.\n * @param from - The address to check the balance of.\n * @param tokenId - The token ID to check the balance of.\n * @returns The balance transaction data.\n */\nfunction getBalanceTransactionData(\n tokenStandard: SimulationTokenStandard,\n from: Hex,\n tokenId?: Hex,\n): Hex {\n switch (tokenStandard) {\n case SimulationTokenStandard.erc721:\n return new Interface(abiERC721).encodeFunctionData('ownerOf', [\n tokenId,\n ]) as Hex;\n\n case SimulationTokenStandard.erc1155:\n return new Interface(abiERC1155).encodeFunctionData('balanceOf', [\n from,\n tokenId,\n ]) as Hex;\n\n default:\n return new Interface(abiERC20).encodeFunctionData('balanceOf', [\n from,\n ]) as Hex;\n }\n}\n\n/**\n * Parse a raw event log using known ABIs.\n * @param eventLog - The raw event log.\n * @param interfaces - The contract interfaces.\n * @returns The parsed event log or undefined if it could not be parsed.\n */\nfunction parseLog(\n eventLog: SimulationResponseLog,\n interfaces: Map<SupportedToken, Interface>,\n):\n | (LogDescription & { abi: ABI; standard: SimulationTokenStandard })\n | undefined {\n const supportedTokens = Object.values(SupportedToken);\n\n for (const token of supportedTokens) {\n try {\n const contractInterface = interfaces.get(token) as Interface;\n const { abi, standard } = SUPPORTED_TOKEN_ABIS[token];\n\n return {\n ...contractInterface.parseLog(eventLog),\n abi,\n standard,\n };\n } catch (e) {\n continue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extract all logs from a call trace tree.\n * @param call - The root call trace.\n * @returns An array of logs.\n */\nfunction extractLogs(\n call: SimulationResponseCallTrace,\n): SimulationResponseLog[] {\n /* istanbul ignore next */\n const logs = call.logs ?? [];\n\n /* istanbul ignore next */\n const nestedCalls = call.calls ?? [];\n\n return [\n ...logs,\n ...nestedCalls.map((nestedCall) => extractLogs(nestedCall)).flat(),\n ];\n}\n\n/**\n * Generate balance change data from previous and new balances.\n * @param previousBalance - The previous balance.\n * @param newBalance - The new balance.\n * @returns The balance change data or undefined if unchanged.\n */\nfunction getSimulationBalanceChange(\n previousBalance: Hex,\n newBalance: Hex,\n): SimulationBalanceChange | undefined {\n const differenceBN = hexToBN(newBalance).sub(hexToBN(previousBalance));\n const isDecrease = differenceBN.isNeg();\n const difference = toHex(differenceBN.abs());\n\n if (differenceBN.isZero()) {\n log('Balance change is zero');\n return undefined;\n }\n\n return {\n previousBalance,\n newBalance,\n difference,\n isDecrease,\n };\n}\n\n/**\n * Normalize a return value.\n * @param value - The return value to normalize.\n * @returns The normalized return value.\n */\nfunction normalizeReturnValue(value: Hex): Hex {\n return toHex(hexToBN(value));\n}\n\n/**\n * Get the contract interfaces for all supported tokens.\n * @returns A map of supported tokens to their contract interfaces.\n */\nfunction getContractInterfaces(): Map<SupportedToken, Interface> {\n const supportedTokens = Object.values(SupportedToken);\n\n return new Map(\n supportedTokens.map((tokenType) => {\n const { abi } = SUPPORTED_TOKEN_ABIS[tokenType];\n const contractInterface = new Interface(abi);\n return [tokenType, contractInterface];\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AACA,SAAS,iBAAiB;AAC1B,SAAS,SAAS,aAAa;AAC/B,SAAS,UAAU,WAAW,kBAAkB;AAChD,SAAS,0BAAoC;AA4BtC,IAAK,iBAAL,kBAAKA,oBAAL;AACL,EAAAA,gBAAA,WAAQ;AACR,EAAAA,gBAAA,YAAS;AACT,EAAAA,gBAAA,aAAU;AAGV,EAAAA,gBAAA,mBAAgB;AAGhB,EAAAA,gBAAA,mBAAgB;AATN,SAAAA;AAAA,GAAA;AA8BZ,IAAM,MAAM,mBAAmB,eAAe,YAAY;AAE1D,IAAM,mBAAmB;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,uBAAuB;AAAA,E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254,4 @@ export {
|
|
|
254
254
|
updateSwapsTransaction,
|
|
255
255
|
updatePostTransactionBalance
|
|
256
256
|
};
|
|
257
|
-
//# sourceMappingURL=chunk-
|
|
257
|
+
//# sourceMappingURL=chunk-GNAL5HC2.mjs.map
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
gweiDecimalToWeiHex
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-VXNPVIYL.mjs";
|
|
4
4
|
import {
|
|
5
5
|
projectLogger
|
|
6
6
|
} from "./chunk-UQQWZT6C.mjs";
|
|
7
7
|
import {
|
|
8
8
|
GasFeeEstimateLevel
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-6SJYXSF3.mjs";
|
|
10
10
|
import {
|
|
11
11
|
__privateAdd,
|
|
12
12
|
__privateMethod
|
|
@@ -109,4 +109,4 @@ getLegacyLevel_fn = function(gasFeeEstimates, level) {
|
|
|
109
109
|
export {
|
|
110
110
|
DefaultGasFeeFlow
|
|
111
111
|
};
|
|
112
|
-
//# sourceMappingURL=chunk-
|
|
112
|
+
//# sourceMappingURL=chunk-H2KZOK3J.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/gas-flows/DefaultGasFeeFlow.ts"],"sourcesContent":["import type {\n LegacyGasPriceEstimate,\n GasFeeEstimates as FeeMarketGasPriceEstimate,\n EthGasPriceEstimate,\n} from '@metamask/gas-fee-controller';\nimport { GAS_ESTIMATE_TYPES } from '@metamask/gas-fee-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger';\nimport type {\n FeeMarketGasFeeEstimateForLevel,\n FeeMarketGasFeeEstimates,\n GasFeeEstimates,\n GasFeeFlow,\n GasFeeFlowRequest,\n GasFeeFlowResponse,\n GasPriceGasFeeEstimates,\n LegacyGasFeeEstimates,\n TransactionMeta,\n} from '../types';\nimport { GasFeeEstimateLevel, GasFeeEstimateType } from '../types';\nimport { gweiDecimalToWeiHex } from '../utils/gas-fees';\n\nconst log = createModuleLogger(projectLogger, 'default-gas-fee-flow');\n\n/**\n * The standard implementation of a gas fee flow that obtains gas fee estimates using only the GasFeeController.\n */\nexport class DefaultGasFeeFlow implements GasFeeFlow {\n matchesTransaction(_transactionMeta: TransactionMeta): boolean {\n return true;\n }\n\n async getGasFees(request: GasFeeFlowRequest): Promise<GasFeeFlowResponse> {\n const { gasFeeControllerData } = request;\n const { gasEstimateType, gasFeeEstimates } = gasFeeControllerData;\n\n let response: GasFeeEstimates;\n\n switch (gasEstimateType) {\n case GAS_ESTIMATE_TYPES.FEE_MARKET:\n log('Using fee market estimates', gasFeeEstimates);\n response = this.#getFeeMarkEstimates(gasFeeEstimates);\n break;\n case GAS_ESTIMATE_TYPES.LEGACY:\n log('Using legacy estimates', gasFeeEstimates);\n response = this.#getLegacyEstimates(\n gasFeeEstimates as LegacyGasPriceEstimate,\n );\n break;\n case GAS_ESTIMATE_TYPES.ETH_GASPRICE:\n log('Using eth_gasPrice estimates', gasFeeEstimates);\n response = this.#getGasPriceEstimates(\n gasFeeEstimates as EthGasPriceEstimate,\n );\n break;\n default:\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 throw new Error(`Unsupported gas estimate type: ${gasEstimateType}`);\n }\n\n return {\n estimates: response,\n };\n }\n\n #getFeeMarkEstimates(\n gasFeeEstimates: FeeMarketGasPriceEstimate,\n ): FeeMarketGasFeeEstimates {\n const levels = Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: this.#getFeeMarketLevel(gasFeeEstimates, level),\n }),\n {} as Omit<FeeMarketGasFeeEstimates, 'type'>,\n );\n\n return {\n type: GasFeeEstimateType.FeeMarket,\n ...levels,\n };\n }\n\n #getLegacyEstimates(\n gasFeeEstimates: LegacyGasPriceEstimate,\n ): LegacyGasFeeEstimates {\n const levels = Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: this.#getLegacyLevel(gasFeeEstimates, level),\n }),\n {} as Omit<LegacyGasFeeEstimates, 'type'>,\n );\n\n return {\n type: GasFeeEstimateType.Legacy,\n ...levels,\n };\n }\n\n #getGasPriceEstimates(\n gasFeeEstimates: EthGasPriceEstimate,\n ): GasPriceGasFeeEstimates {\n return {\n type: GasFeeEstimateType.GasPrice,\n gasPrice: gweiDecimalToWeiHex(gasFeeEstimates.gasPrice),\n };\n }\n\n #getFeeMarketLevel(\n gasFeeEstimates: FeeMarketGasPriceEstimate,\n level: GasFeeEstimateLevel,\n ): FeeMarketGasFeeEstimateForLevel {\n const maxFeePerGas = gweiDecimalToWeiHex(\n gasFeeEstimates[level].suggestedMaxFeePerGas,\n );\n\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(\n gasFeeEstimates[level].suggestedMaxPriorityFeePerGas,\n );\n\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n };\n }\n\n #getLegacyLevel(\n gasFeeEstimates: LegacyGasPriceEstimate,\n level: GasFeeEstimateLevel,\n ): Hex {\n return gweiDecimalToWeiHex(gasFeeEstimates[level]);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAKA,SAAS,0BAA0B;AAEnC,SAAS,0BAA0B;AAiBnC,IAAM,MAAM,mBAAmB,eAAe,sBAAsB;AAxBpE;AA6BO,IAAM,oBAAN,MAA8C;AAAA,EAA9C;AAuCL;AAiBA;AAiBA;AASA;AAkBA;AAAA;AAAA,EAnGA,mBAAmB,kBAA4C;AAC7D,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,WAAW,SAAyD;AACxE,UAAM,EAAE,qBAAqB,IAAI;AACjC,UAAM,EAAE,iBAAiB,gBAAgB,IAAI;AAE7C,QAAI;AAEJ,YAAQ,iBAAiB;AAAA,MACvB,KAAK,mBAAmB;AACtB,YAAI,8BAA8B,eAAe;AACjD,mBAAW,sBAAK,8CAAL,WAA0B;AACrC;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A,OACK;AACL,SAAO,oBAAoB,gBAAgB,KAAK,CAAC;AACnD;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
GasFeeEstimateLevel
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-6SJYXSF3.mjs";
|
|
4
4
|
|
|
5
5
|
// src/utils/gas-flow.ts
|
|
6
6
|
import { weiHexToGweiDec } from "@metamask/controller-utils";
|
|
@@ -64,4 +64,4 @@ export {
|
|
|
64
64
|
getGasFeeFlow,
|
|
65
65
|
mergeGasFeeEstimates
|
|
66
66
|
};
|
|
67
|
-
//# sourceMappingURL=chunk-
|
|
67
|
+
//# sourceMappingURL=chunk-JXXTNVU4.mjs.map
|
|
@@ -41,6 +41,8 @@ var validateGasValues = (gasValues) => {
|
|
|
41
41
|
const value = gasValues[key];
|
|
42
42
|
if (typeof value !== "string" || !_utils.isStrictHexString.call(void 0, value)) {
|
|
43
43
|
throw new TypeError(
|
|
44
|
+
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
45
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
44
46
|
`expected hex string for ${key} but received: ${value}`
|
|
45
47
|
);
|
|
46
48
|
}
|
|
@@ -64,6 +66,8 @@ function validateMinimumIncrease(proposed, min) {
|
|
|
64
66
|
function validateIfTransactionUnapproved(transactionMeta, fnName) {
|
|
65
67
|
if (transactionMeta?.status !== "unapproved" /* unapproved */) {
|
|
66
68
|
throw new Error(
|
|
69
|
+
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
70
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
67
71
|
`TransactionsController: Can only call ${fnName} on an unapproved transaction.
|
|
68
72
|
Current tx status: ${transactionMeta?.status}`
|
|
69
73
|
);
|
|
@@ -120,4 +124,4 @@ function padHexToEvenLength(hex) {
|
|
|
120
124
|
|
|
121
125
|
|
|
122
126
|
exports.ESTIMATE_GAS_ERROR = ESTIMATE_GAS_ERROR; exports.normalizeTransactionParams = normalizeTransactionParams; exports.isEIP1559Transaction = isEIP1559Transaction; exports.validateGasValues = validateGasValues; exports.isFeeMarketEIP1559Values = isFeeMarketEIP1559Values; exports.isGasPriceValue = isGasPriceValue; exports.getIncreasedPriceHex = getIncreasedPriceHex; exports.getIncreasedPriceFromExisting = getIncreasedPriceFromExisting; exports.validateMinimumIncrease = validateMinimumIncrease; exports.validateIfTransactionUnapproved = validateIfTransactionUnapproved; exports.normalizeTxError = normalizeTxError; exports.normalizeGasFeeValues = normalizeGasFeeValues; exports.padHexToEvenLength = padHexToEvenLength;
|
|
123
|
-
//# sourceMappingURL=chunk-
|
|
127
|
+
//# sourceMappingURL=chunk-OZ6UB42C.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/utils.ts"],"names":[],"mappings":";AAAA,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAcA,IAAM,qBAAqB;AAIlC,IAAM,cAA2D;AAAA,EAC/D,MAAM,CAAC,SAAiB,MAAM,mBAAmB,IAAI,CAAC;AAAA,EACtD,MAAM,CAAC,SAAiB,MAAM,IAAI,EAAE,YAAY;AAAA,EAChD,KAAK,CAAC,QAAgB,MAAM,GAAG;AAAA,EAC/B,UAAU,CAAC,QAAgB,MAAM,GAAG;AAAA,EACpC,UAAU,CAAC,aAAqB,MAAM,QAAQ;AAAA,EAC9C,OAAO,CAAC,UAAkB,MAAM,KAAK;AAAA,EACrC,IAAI,CAAC,OAAe,MAAM,EAAE,EAAE,YAAY;AAAA,EAC1C,OAAO,CAAC,UAAkB,MAAM,KAAK;AAAA,EACrC,cAAc,CAAC,iBAAyB,MAAM,YAAY;AAAA,EAC1D,sBAAsB,CAAC,yBACrB,MAAM,oBAAoB;AAAA,EAC5B,kBAAkB,CAAC,yBACjB,MAAM,oBAAoB;AAAA,EAC5B,MAAM,CAAC,SAAiB,MAAM,IAAI;AAC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;AAAA,EACT;AAGA,QAAM,WAAW,uBAAuB,eAAe,6CAA6C,UAAU;AAC9G,QAAM,IAAI,MAAM,QAAQ;AAC1B;AASO,SAAS,gCACd,iBACA,QACA;AACA,MAAI,iBAAiB,0CAAyC;AAC5D,UAAM,IAAI;AAAA;AAAA;AAAA,MAGR,yCAAyC,MAAM;AAAA,2BAA4D,iBAAiB,MAAM;AAAA,IACpI;AAAA,EACF;AACF;AAQO,SAAS,iBACd,OACkB;AAClB,SAAO;AAAA,IACL,MAAM,MAAM;AAAA,IACZ,SAAS,MAAM;AAAA,IACf,OAAO,MAAM;AAAA,IACb,MAAM,MAAM;AAAA,IACZ,KAAK,iBAAiB,MAAM,KAAK,IAAI,MAAM,QAAQ;AAAA,EACrD;AACF;AAQO,SAAS,sBACd,cACwC;AAGxC,QAAM,YAAY,CAAC,UACjB,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;AAE7C,MAAI,cAAc,cAAc;AAC9B,WAAO;AAAA,MACL,UAAU,UAAU,aAAa,QAAQ;AAAA,IAC3C;AAAA,EACF;AAEA,SAAO;AAAA,IACL,cAAc,UAAU,aAAa,YAAY;AAAA,IACjD,sBAAsB,UAAU,aAAa,oBAAoB;AAAA,EACnE;AACF;AAQA,SAAS,iBAAiB,OAA+B;AACvD,MAAI;AACF,SAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAChC,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASO,SAAS,mBAAmB,KAAa;AAC9C,QAAM,SAAS,IAAI,YAAY,EAAE,WAAW,IAAI,IAAI,IAAI,MAAM,GAAG,CAAC,IAAI;AACtE,QAAM,OAAO,SAAS,IAAI,MAAM,CAAC,IAAI;AACrC,QAAM,WAAW,KAAK,SAAS,MAAM,IAAI,OAAO,IAAI,IAAI;AAExD,SAAO,SAAS;AAClB","sourcesContent":["import { convertHexToDecimal } from '@metamask/controller-utils';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\n\nimport type {\n GasPriceValue,\n FeeMarketEIP1559Values,\n} from '../TransactionController';\nimport { TransactionStatus } from '../types';\nimport type {\n TransactionParams,\n TransactionMeta,\n TransactionError,\n} from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NORMALIZERS: { [param in keyof TransactionParams]: any } = {\n data: (data: string) => add0x(padHexToEvenLength(data)),\n from: (from: string) => add0x(from).toLowerCase(),\n gas: (gas: string) => add0x(gas),\n gasLimit: (gas: string) => add0x(gas),\n gasPrice: (gasPrice: string) => add0x(gasPrice),\n nonce: (nonce: string) => add0x(nonce),\n to: (to: string) => add0x(to).toLowerCase(),\n value: (value: string) => add0x(value),\n maxFeePerGas: (maxFeePerGas: string) => add0x(maxFeePerGas),\n maxPriorityFeePerGas: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n estimatedBaseFee: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n type: (type: string) => add0x(type),\n};\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param txParams - The transaction params to normalize.\n * @returns Normalized transaction params.\n */\nexport function normalizeTransactionParams(txParams: TransactionParams) {\n const normalizedTxParams: TransactionParams = { from: '' };\n\n for (const key of getKnownPropertyNames(NORMALIZERS)) {\n if (txParams[key]) {\n normalizedTxParams[key] = NORMALIZERS[key](txParams[key]);\n }\n }\n\n if (!normalizedTxParams.value) {\n normalizedTxParams.value = '0x0';\n }\n\n return normalizedTxParams;\n}\n\n/**\n * Checks if a transaction is EIP-1559 by checking for the existence of\n * maxFeePerGas and maxPriorityFeePerGas within its parameters.\n *\n * @param txParams - Transaction params object to add.\n * @returns Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false.\n */\nexport function isEIP1559Transaction(txParams: TransactionParams): boolean {\n const hasOwnProp = (obj: TransactionParams, key: string) =>\n Object.prototype.hasOwnProperty.call(obj, key);\n return (\n hasOwnProp(txParams, 'maxFeePerGas') &&\n hasOwnProp(txParams, 'maxPriorityFeePerGas')\n );\n}\n\nexport const validateGasValues = (\n gasValues: GasPriceValue | FeeMarketEIP1559Values,\n) => {\n Object.keys(gasValues).forEach((key) => {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (gasValues as any)[key];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw new TypeError(\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 `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\n};\n\nexport const isFeeMarketEIP1559Values = (\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): gasValues is FeeMarketEIP1559Values =>\n (gasValues as FeeMarketEIP1559Values)?.maxFeePerGas !== undefined ||\n (gasValues as FeeMarketEIP1559Values)?.maxPriorityFeePerGas !== undefined;\n\nexport const isGasPriceValue = (\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): gasValues is GasPriceValue =>\n (gasValues as GasPriceValue)?.gasPrice !== undefined;\n\nexport const getIncreasedPriceHex = (value: number, rate: number): string =>\n add0x(`${parseInt(`${value * rate}`, 10).toString(16)}`);\n\nexport const getIncreasedPriceFromExisting = (\n value: string | undefined,\n rate: number,\n): string => {\n return getIncreasedPriceHex(convertHexToDecimal(value), rate);\n};\n\n/**\n * Validates that the proposed value is greater than or equal to the minimum value.\n *\n * @param proposed - The proposed value.\n * @param min - The minimum value.\n * @returns The proposed value.\n * @throws Will throw if the proposed value is too low.\n */\nexport function validateMinimumIncrease(proposed: string, min: string) {\n const proposedDecimal = convertHexToDecimal(proposed);\n const minDecimal = convertHexToDecimal(min);\n if (proposedDecimal >= minDecimal) {\n return proposed;\n }\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 const errorMsg = `The proposed value: ${proposedDecimal} should meet or exceed the minimum value: ${minDecimal}`;\n throw new Error(errorMsg);\n}\n\n/**\n * Validates that a transaction is unapproved.\n * Throws if the transaction is not unapproved.\n *\n * @param transactionMeta - The transaction metadata to check.\n * @param fnName - The name of the function calling this helper.\n */\nexport function validateIfTransactionUnapproved(\n transactionMeta: TransactionMeta | undefined,\n fnName: string,\n) {\n if (transactionMeta?.status !== TransactionStatus.unapproved) {\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 `TransactionsController: Can only call ${fnName} on an unapproved transaction.\\n Current tx status: ${transactionMeta?.status}`,\n );\n }\n}\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param error - The error to be normalize.\n * @returns Normalized transaction error.\n */\nexport function normalizeTxError(\n error: Error & { code?: string; value?: unknown },\n): TransactionError {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n code: error.code,\n rpc: isJsonCompatible(error.value) ? error.value : undefined,\n };\n}\n\n/**\n * Normalize an object containing gas fee values.\n *\n * @param gasFeeValues - An object containing gas fee values.\n * @returns An object containing normalized gas fee values.\n */\nexport function normalizeGasFeeValues(\n gasFeeValues: GasPriceValue | FeeMarketEIP1559Values,\n): GasPriceValue | FeeMarketEIP1559Values {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const normalize = (value: any) =>\n typeof value === 'string' ? add0x(value) : value;\n\n if ('gasPrice' in gasFeeValues) {\n return {\n gasPrice: normalize(gasFeeValues.gasPrice),\n };\n }\n\n return {\n maxFeePerGas: normalize(gasFeeValues.maxFeePerGas),\n maxPriorityFeePerGas: normalize(gasFeeValues.maxPriorityFeePerGas),\n };\n}\n\n/**\n * Determines whether the given value can be encoded as JSON.\n *\n * @param value - The value.\n * @returns True if the value is JSON-encodable, false if not.\n */\nfunction isJsonCompatible(value: unknown): value is Json {\n try {\n JSON.parse(JSON.stringify(value));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure a hex string is of even length by adding a leading 0 if necessary.\n * Any existing `0x` prefix is preserved but is not added if missing.\n *\n * @param hex - The hex string to ensure is even.\n * @returns The hex string with an even length.\n */\nexport function padHexToEvenLength(hex: string) {\n const prefix = hex.toLowerCase().startsWith('0x') ? hex.slice(0, 2) : '';\n const data = prefix ? hex.slice(2) : hex;\n const evenData = data.length % 2 === 0 ? data : `0${data}`;\n\n return prefix + evenData;\n}\n"]}
|
|
@@ -41,6 +41,8 @@ var validateGasValues = (gasValues) => {
|
|
|
41
41
|
const value = gasValues[key];
|
|
42
42
|
if (typeof value !== "string" || !isStrictHexString(value)) {
|
|
43
43
|
throw new TypeError(
|
|
44
|
+
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
45
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
44
46
|
`expected hex string for ${key} but received: ${value}`
|
|
45
47
|
);
|
|
46
48
|
}
|
|
@@ -64,6 +66,8 @@ function validateMinimumIncrease(proposed, min) {
|
|
|
64
66
|
function validateIfTransactionUnapproved(transactionMeta, fnName) {
|
|
65
67
|
if (transactionMeta?.status !== "unapproved" /* unapproved */) {
|
|
66
68
|
throw new Error(
|
|
69
|
+
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
70
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
67
71
|
`TransactionsController: Can only call ${fnName} on an unapproved transaction.
|
|
68
72
|
Current tx status: ${transactionMeta?.status}`
|
|
69
73
|
);
|
|
@@ -120,4 +124,4 @@ export {
|
|
|
120
124
|
normalizeGasFeeValues,
|
|
121
125
|
padHexToEvenLength
|
|
122
126
|
};
|
|
123
|
-
//# sourceMappingURL=chunk-
|
|
127
|
+
//# sourceMappingURL=chunk-Q56I5ONX.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/utils.ts"],"sourcesContent":["import { convertHexToDecimal } from '@metamask/controller-utils';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\n\nimport type {\n GasPriceValue,\n FeeMarketEIP1559Values,\n} from '../TransactionController';\nimport { TransactionStatus } from '../types';\nimport type {\n TransactionParams,\n TransactionMeta,\n TransactionError,\n} from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NORMALIZERS: { [param in keyof TransactionParams]: any } = {\n data: (data: string) => add0x(padHexToEvenLength(data)),\n from: (from: string) => add0x(from).toLowerCase(),\n gas: (gas: string) => add0x(gas),\n gasLimit: (gas: string) => add0x(gas),\n gasPrice: (gasPrice: string) => add0x(gasPrice),\n nonce: (nonce: string) => add0x(nonce),\n to: (to: string) => add0x(to).toLowerCase(),\n value: (value: string) => add0x(value),\n maxFeePerGas: (maxFeePerGas: string) => add0x(maxFeePerGas),\n maxPriorityFeePerGas: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n estimatedBaseFee: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n type: (type: string) => add0x(type),\n};\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param txParams - The transaction params to normalize.\n * @returns Normalized transaction params.\n */\nexport function normalizeTransactionParams(txParams: TransactionParams) {\n const normalizedTxParams: TransactionParams = { from: '' };\n\n for (const key of getKnownPropertyNames(NORMALIZERS)) {\n if (txParams[key]) {\n normalizedTxParams[key] = NORMALIZERS[key](txParams[key]);\n }\n }\n\n if (!normalizedTxParams.value) {\n normalizedTxParams.value = '0x0';\n }\n\n return normalizedTxParams;\n}\n\n/**\n * Checks if a transaction is EIP-1559 by checking for the existence of\n * maxFeePerGas and maxPriorityFeePerGas within its parameters.\n *\n * @param txParams - Transaction params object to add.\n * @returns Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false.\n */\nexport function isEIP1559Transaction(txParams: TransactionParams): boolean {\n const hasOwnProp = (obj: TransactionParams, key: string) =>\n Object.prototype.hasOwnProperty.call(obj, key);\n return (\n hasOwnProp(txParams, 'maxFeePerGas') &&\n hasOwnProp(txParams, 'maxPriorityFeePerGas')\n );\n}\n\nexport const validateGasValues = (\n gasValues: GasPriceValue | FeeMarketEIP1559Values,\n) => {\n Object.keys(gasValues).forEach((key) => {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (gasValues as any)[key];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw new TypeError(\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 `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\n};\n\nexport const isFeeMarketEIP1559Values = (\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): gasValues is FeeMarketEIP1559Values =>\n (gasValues as FeeMarketEIP1559Values)?.maxFeePerGas !== undefined ||\n (gasValues as FeeMarketEIP1559Values)?.maxPriorityFeePerGas !== undefined;\n\nexport const isGasPriceValue = (\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): gasValues is GasPriceValue =>\n (gasValues as GasPriceValue)?.gasPrice !== undefined;\n\nexport const getIncreasedPriceHex = (value: number, rate: number): string =>\n add0x(`${parseInt(`${value * rate}`, 10).toString(16)}`);\n\nexport const getIncreasedPriceFromExisting = (\n value: string | undefined,\n rate: number,\n): string => {\n return getIncreasedPriceHex(convertHexToDecimal(value), rate);\n};\n\n/**\n * Validates that the proposed value is greater than or equal to the minimum value.\n *\n * @param proposed - The proposed value.\n * @param min - The minimum value.\n * @returns The proposed value.\n * @throws Will throw if the proposed value is too low.\n */\nexport function validateMinimumIncrease(proposed: string, min: string) {\n const proposedDecimal = convertHexToDecimal(proposed);\n const minDecimal = convertHexToDecimal(min);\n if (proposedDecimal >= minDecimal) {\n return proposed;\n }\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 const errorMsg = `The proposed value: ${proposedDecimal} should meet or exceed the minimum value: ${minDecimal}`;\n throw new Error(errorMsg);\n}\n\n/**\n * Validates that a transaction is unapproved.\n * Throws if the transaction is not unapproved.\n *\n * @param transactionMeta - The transaction metadata to check.\n * @param fnName - The name of the function calling this helper.\n */\nexport function validateIfTransactionUnapproved(\n transactionMeta: TransactionMeta | undefined,\n fnName: string,\n) {\n if (transactionMeta?.status !== TransactionStatus.unapproved) {\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 `TransactionsController: Can only call ${fnName} on an unapproved transaction.\\n Current tx status: ${transactionMeta?.status}`,\n );\n }\n}\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param error - The error to be normalize.\n * @returns Normalized transaction error.\n */\nexport function normalizeTxError(\n error: Error & { code?: string; value?: unknown },\n): TransactionError {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n code: error.code,\n rpc: isJsonCompatible(error.value) ? error.value : undefined,\n };\n}\n\n/**\n * Normalize an object containing gas fee values.\n *\n * @param gasFeeValues - An object containing gas fee values.\n * @returns An object containing normalized gas fee values.\n */\nexport function normalizeGasFeeValues(\n gasFeeValues: GasPriceValue | FeeMarketEIP1559Values,\n): GasPriceValue | FeeMarketEIP1559Values {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const normalize = (value: any) =>\n typeof value === 'string' ? add0x(value) : value;\n\n if ('gasPrice' in gasFeeValues) {\n return {\n gasPrice: normalize(gasFeeValues.gasPrice),\n };\n }\n\n return {\n maxFeePerGas: normalize(gasFeeValues.maxFeePerGas),\n maxPriorityFeePerGas: normalize(gasFeeValues.maxPriorityFeePerGas),\n };\n}\n\n/**\n * Determines whether the given value can be encoded as JSON.\n *\n * @param value - The value.\n * @returns True if the value is JSON-encodable, false if not.\n */\nfunction isJsonCompatible(value: unknown): value is Json {\n try {\n JSON.parse(JSON.stringify(value));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure a hex string is of even length by adding a leading 0 if necessary.\n * Any existing `0x` prefix is preserved but is not added if missing.\n *\n * @param hex - The hex string to ensure is even.\n * @returns The hex string with an even length.\n */\nexport function padHexToEvenLength(hex: string) {\n const prefix = hex.toLowerCase().startsWith('0x') ? hex.slice(0, 2) : '';\n const data = prefix ? hex.slice(2) : hex;\n const evenData = data.length % 2 === 0 ? data : `0${data}`;\n\n return prefix + evenData;\n}\n"],"mappings":";AAAA,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAcA,IAAM,qBAAqB;AAIlC,IAAM,cAA2D;AAAA,EAC/D,MAAM,CAAC,SAAiB,MAAM,mBAAmB,IAAI,CAAC;AAAA,EACtD,MAAM,CAAC,SAAiB,MAAM,IAAI,EAAE,YAAY;AAAA,EAChD,KAAK,CAAC,QAAgB,MAAM,GAAG;AAAA,EAC/B,UAAU,CAAC,QAAgB,MAAM,GAAG;AAAA,EACpC,UAAU,CAAC,aAAqB,MAAM,QAAQ;AAAA,EAC9C,OAAO,CAAC,UAAkB,MAAM,KAAK;AAAA,EACrC,IAAI,CAAC,OAAe,MAAM,EAAE,EAAE,YAAY;AAAA,EAC1C,OAAO,CAAC,UAAkB,MAAM,KAAK;AAAA,EACrC,cAAc,CAAC,iBAAyB,MAAM,YAAY;AAAA,EAC1D,sBAAsB,CAAC,yBACrB,MAAM,oBAAoB;AAAA,EAC5B,kBAAkB,CAAC,yBACjB,MAAM,oBAAoB;AAAA,EAC5B,MAAM,CAAC,SAAiB,MAAM,IAAI;AACpC;AAQO,SAAS,2BAA2B,UAA6B;AACtE,QAAM,qBAAwC,EAAE,MAAM,GAAG;AAEzD,aAAW,OAAO,sBAAsB,WAAW,GAAG;AACpD,QAAI,SAAS,GAAG,GAAG;AACjB,yBA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AyC;AAC5D,UAAM,IAAI;AAAA;AAAA;AAAA,MAGR,yCAAyC,MAAM;AAAA,2BAA4D,iBAAiB,MAAM;AAAA,IACpI;AAAA,EACF;AACF;AAQO,SAAS,iBACd,OACkB;AAClB,SAAO;AAAA,IACL,MAAM,MAAM;AAAA,IACZ,SAAS,MAAM;AAAA,IACf,OAAO,MAAM;AAAA,IACb,MAAM,MAAM;AAAA,IACZ,KAAK,iBAAiB,MAAM,KAAK,IAAI,MAAM,QAAQ;AAAA,EACrD;AACF;AAQO,SAAS,sBACd,cACwC;AAGxC,QAAM,YAAY,CAAC,UACjB,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;AAE7C,MAAI,cAAc,cAAc;AAC9B,WAAO;AAAA,MACL,UAAU,UAAU,aAAa,QAAQ;AAAA,IAC3C;AAAA,EACF;AAEA,SAAO;AAAA,IACL,cAAc,UAAU,aAAa,YAAY;AAAA,IACjD,sBAAsB,UAAU,aAAa,oBAAoB;AAAA,EACnE;AACF;AAQA,SAAS,iBAAiB,OAA+B;AACvD,MAAI;AACF,SAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAChC,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASO,SAAS,mBAAmB,KAAa;AAC9C,QAAM,SAAS,IAAI,YAAY,EAAE,WAAW,IAAI,IAAI,IAAI,MAAM,GAAG,CAAC,IAAI;AACtE,QAAM,OAAO,SAAS,IAAI,MAAM,CAAC,IAAI;AACrC,QAAM,WAAW,KAAK,SAAS,MAAM,IAAI,OAAO,IAAI,IAAI;AAExD,SAAO,SAAS;AAClB;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkOZ6UB42Cjs = require('./chunk-OZ6UB42C.js');
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
var _chunkUGN7PBONjs = require('./chunk-UGN7PBON.js');
|
|
@@ -172,7 +172,7 @@ function updateSwapTransaction(transactionMeta, {
|
|
|
172
172
|
estimatedBaseFee,
|
|
173
173
|
approvalTxId
|
|
174
174
|
}) {
|
|
175
|
-
|
|
175
|
+
_chunkOZ6UB42Cjs.validateIfTransactionUnapproved.call(void 0, transactionMeta, "updateSwapTransaction");
|
|
176
176
|
let swapTransaction = {
|
|
177
177
|
sourceTokenSymbol,
|
|
178
178
|
destinationTokenSymbol,
|
|
@@ -203,7 +203,7 @@ function updateSwapAndSendTransaction(transactionMeta, {
|
|
|
203
203
|
swapTokenValue,
|
|
204
204
|
type
|
|
205
205
|
}) {
|
|
206
|
-
|
|
206
|
+
_chunkOZ6UB42Cjs.validateIfTransactionUnapproved.call(void 0, transactionMeta, "updateSwapTransaction");
|
|
207
207
|
let swapTransaction = {
|
|
208
208
|
approvalTxId,
|
|
209
209
|
destinationTokenAddress,
|
|
@@ -224,7 +224,7 @@ function updateSwapAndSendTransaction(transactionMeta, {
|
|
|
224
224
|
return _lodash.merge.call(void 0, {}, transactionMeta, swapTransaction);
|
|
225
225
|
}
|
|
226
226
|
function updateSwapApprovalTransaction(transactionMeta, { type, sourceTokenSymbol }) {
|
|
227
|
-
|
|
227
|
+
_chunkOZ6UB42Cjs.validateIfTransactionUnapproved.call(void 0,
|
|
228
228
|
transactionMeta,
|
|
229
229
|
"updateSwapApprovalTransaction"
|
|
230
230
|
);
|
|
@@ -254,4 +254,4 @@ function sleep(ms) {
|
|
|
254
254
|
|
|
255
255
|
|
|
256
256
|
exports.UPDATE_POST_TX_BALANCE_TIMEOUT = UPDATE_POST_TX_BALANCE_TIMEOUT; exports.UPDATE_POST_TX_BALANCE_ATTEMPTS = UPDATE_POST_TX_BALANCE_ATTEMPTS; exports.DEFAULT_TOKEN_ADDRESS = DEFAULT_TOKEN_ADDRESS; exports.SWAPS_CHAINID_DEFAULT_TOKEN_MAP = SWAPS_CHAINID_DEFAULT_TOKEN_MAP; exports.SWAP_TRANSACTION_TYPES = SWAP_TRANSACTION_TYPES; exports.updateSwapsTransaction = updateSwapsTransaction; exports.updatePostTransactionBalance = updatePostTransactionBalance;
|
|
257
|
-
//# sourceMappingURL=chunk-
|
|
257
|
+
//# sourceMappingURL=chunk-QH2H4W3N.js.map
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkC3WC4OJ3js = require('./chunk-C3WC4OJ3.js');
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
var _chunkS6VGOPUYjs = require('./chunk-S6VGOPUY.js');
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
var
|
|
9
|
+
var _chunkAYTU4HU5js = require('./chunk-AYTU4HU5.js');
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
|
|
@@ -55,7 +55,7 @@ var DefaultGasFeeFlow = class {
|
|
|
55
55
|
};
|
|
56
56
|
_getFeeMarkEstimates = new WeakSet();
|
|
57
57
|
getFeeMarkEstimates_fn = function(gasFeeEstimates) {
|
|
58
|
-
const levels = Object.values(
|
|
58
|
+
const levels = Object.values(_chunkAYTU4HU5js.GasFeeEstimateLevel).reduce(
|
|
59
59
|
(result, level) => ({
|
|
60
60
|
...result,
|
|
61
61
|
[level]: _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getFeeMarketLevel, getFeeMarketLevel_fn).call(this, gasFeeEstimates, level)
|
|
@@ -69,7 +69,7 @@ getFeeMarkEstimates_fn = function(gasFeeEstimates) {
|
|
|
69
69
|
};
|
|
70
70
|
_getLegacyEstimates = new WeakSet();
|
|
71
71
|
getLegacyEstimates_fn = function(gasFeeEstimates) {
|
|
72
|
-
const levels = Object.values(
|
|
72
|
+
const levels = Object.values(_chunkAYTU4HU5js.GasFeeEstimateLevel).reduce(
|
|
73
73
|
(result, level) => ({
|
|
74
74
|
...result,
|
|
75
75
|
[level]: _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getLegacyLevel, getLegacyLevel_fn).call(this, gasFeeEstimates, level)
|
|
@@ -85,15 +85,15 @@ _getGasPriceEstimates = new WeakSet();
|
|
|
85
85
|
getGasPriceEstimates_fn = function(gasFeeEstimates) {
|
|
86
86
|
return {
|
|
87
87
|
type: "eth_gasPrice" /* GasPrice */,
|
|
88
|
-
gasPrice:
|
|
88
|
+
gasPrice: _chunkC3WC4OJ3js.gweiDecimalToWeiHex.call(void 0, gasFeeEstimates.gasPrice)
|
|
89
89
|
};
|
|
90
90
|
};
|
|
91
91
|
_getFeeMarketLevel = new WeakSet();
|
|
92
92
|
getFeeMarketLevel_fn = function(gasFeeEstimates, level) {
|
|
93
|
-
const maxFeePerGas =
|
|
93
|
+
const maxFeePerGas = _chunkC3WC4OJ3js.gweiDecimalToWeiHex.call(void 0,
|
|
94
94
|
gasFeeEstimates[level].suggestedMaxFeePerGas
|
|
95
95
|
);
|
|
96
|
-
const maxPriorityFeePerGas =
|
|
96
|
+
const maxPriorityFeePerGas = _chunkC3WC4OJ3js.gweiDecimalToWeiHex.call(void 0,
|
|
97
97
|
gasFeeEstimates[level].suggestedMaxPriorityFeePerGas
|
|
98
98
|
);
|
|
99
99
|
return {
|
|
@@ -103,10 +103,10 @@ getFeeMarketLevel_fn = function(gasFeeEstimates, level) {
|
|
|
103
103
|
};
|
|
104
104
|
_getLegacyLevel = new WeakSet();
|
|
105
105
|
getLegacyLevel_fn = function(gasFeeEstimates, level) {
|
|
106
|
-
return
|
|
106
|
+
return _chunkC3WC4OJ3js.gweiDecimalToWeiHex.call(void 0, gasFeeEstimates[level]);
|
|
107
107
|
};
|
|
108
108
|
|
|
109
109
|
|
|
110
110
|
|
|
111
111
|
exports.DefaultGasFeeFlow = DefaultGasFeeFlow;
|
|
112
|
-
//# sourceMappingURL=chunk-
|
|
112
|
+
//# sourceMappingURL=chunk-QTKXIDGE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/gas-flows/DefaultGasFe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pD;AAAA,IACA,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL;AAAA,IACA,GAAG;AAAA,EACL;AACF;AAEA;AAAA,wBAAmB,SACjB,iBACuB;AACvB,QAAM,SAAS,OAAO,OAAO,mBAAmB,EAAE;AAAA,IAChD,CAAC,QAAQ,WAAW;AAAA,MAClB,GAAG;AAAA,MACH,CAAC,KAAK,GAAG,sBAAK,oCAAL,WAAqB,iBAAiB;AAAA,IACjD;AAAA,IACA,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL;AAAA,IACA,GAAG;AAAA,EACL;AACF;AAEA;AAAA,0BAAqB,SACnB,iBACyB;AACzB,SAAO;AAAA,IACL;AAAA,IACA,UAAU,oBAAoB,gBAAgB,QAAQ;AAAA,EACxD;AACF;AAEA;AAAA,uBAAkB,SAChB,iBACA,OACiC;AACjC,QAAM,eAAe;AAAA,IACnB,gBAAgB,KAAK,EAAE;AAAA,EACzB;AAEA,QAAM,uBAAuB;AAAA,IAC3B,gBAAgB,KAAK,EAAE;AAAA,EACzB;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;AAEA;AAAA,oBAAe,SACb,iBACA,OACK;AACL,SAAO,oBAAoB,gBAAgB,KAAK,CAAC;AACnD","sourcesContent":["import type {\n LegacyGasPriceEstimate,\n GasFeeEstimates as FeeMarketGasPriceEstimate,\n EthGasPriceEstimate,\n} from '@metamask/gas-fee-controller';\nimport { GAS_ESTIMATE_TYPES } from '@metamask/gas-fee-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger';\nimport type {\n FeeMarketGasFeeEstimateForLevel,\n FeeMarketGasFeeEstimates,\n GasFeeEstimates,\n GasFeeFlow,\n GasFeeFlowRequest,\n GasFeeFlowResponse,\n GasPriceGasFeeEstimates,\n LegacyGasFeeEstimates,\n TransactionMeta,\n} from '../types';\nimport { GasFeeEstimateLevel, GasFeeEstimateType } from '../types';\nimport { gweiDecimalToWeiHex } from '../utils/gas-fees';\n\nconst log = createModuleLogger(projectLogger, 'default-gas-fee-flow');\n\n/**\n * The standard implementation of a gas fee flow that obtains gas fee estimates using only the GasFeeController.\n */\nexport class DefaultGasFeeFlow implements GasFeeFlow {\n matchesTransaction(_transactionMeta: TransactionMeta): boolean {\n return true;\n }\n\n async getGasFees(request: GasFeeFlowRequest): Promise<GasFeeFlowResponse> {\n const { gasFeeControllerData } = request;\n const { gasEstimateType, gasFeeEstimates } = gasFeeControllerData;\n\n let response: GasFeeEstimates;\n\n switch (gasEstimateType) {\n case GAS_ESTIMATE_TYPES.FEE_MARKET:\n log('Using fee market estimates', gasFeeEstimates);\n response = this.#getFeeMarkEstimates(gasFeeEstimates);\n break;\n case GAS_ESTIMATE_TYPES.LEGACY:\n log('Using legacy estimates', gasFeeEstimates);\n response = this.#getLegacyEstimates(\n gasFeeEstimates as LegacyGasPriceEstimate,\n );\n break;\n case GAS_ESTIMATE_TYPES.ETH_GASPRICE:\n log('Using eth_gasPrice estimates', gasFeeEstimates);\n response = this.#getGasPriceEstimates(\n gasFeeEstimates as EthGasPriceEstimate,\n );\n break;\n default:\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 throw new Error(`Unsupported gas estimate type: ${gasEstimateType}`);\n }\n\n return {\n estimates: response,\n };\n }\n\n #getFeeMarkEstimates(\n gasFeeEstimates: FeeMarketGasPriceEstimate,\n ): FeeMarketGasFeeEstimates {\n const levels = Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: this.#getFeeMarketLevel(gasFeeEstimates, level),\n }),\n {} as Omit<FeeMarketGasFeeEstimates, 'type'>,\n );\n\n return {\n type: GasFeeEstimateType.FeeMarket,\n ...levels,\n };\n }\n\n #getLegacyEstimates(\n gasFeeEstimates: LegacyGasPriceEstimate,\n ): LegacyGasFeeEstimates {\n const levels = Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: this.#getLegacyLevel(gasFeeEstimates, level),\n }),\n {} as Omit<LegacyGasFeeEstimates, 'type'>,\n );\n\n return {\n type: GasFeeEstimateType.Legacy,\n ...levels,\n };\n }\n\n #getGasPriceEstimates(\n gasFeeEstimates: EthGasPriceEstimate,\n ): GasPriceGasFeeEstimates {\n return {\n type: GasFeeEstimateType.GasPrice,\n gasPrice: gweiDecimalToWeiHex(gasFeeEstimates.gasPrice),\n };\n }\n\n #getFeeMarketLevel(\n gasFeeEstimates: FeeMarketGasPriceEstimate,\n level: GasFeeEstimateLevel,\n ): FeeMarketGasFeeEstimateForLevel {\n const maxFeePerGas = gweiDecimalToWeiHex(\n gasFeeEstimates[level].suggestedMaxFeePerGas,\n );\n\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(\n gasFeeEstimates[level].suggestedMaxPriorityFeePerGas,\n );\n\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n };\n }\n\n #getLegacyLevel(\n gasFeeEstimates: LegacyGasPriceEstimate,\n level: GasFeeEstimateLevel,\n ): Hex {\n return gweiDecimalToWeiHex(gasFeeEstimates[level]);\n }\n}\n"]}
|
|
@@ -99,12 +99,12 @@ var IncomingTransactionHelper = class {
|
|
|
99
99
|
);
|
|
100
100
|
const additionalLastFetchedKeys = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _remoteTransactionSource).getLastBlockVariations?.() ?? [];
|
|
101
101
|
const fromBlock = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getFromBlock, getFromBlock_fn).call(this, latestBlockNumber);
|
|
102
|
-
const
|
|
102
|
+
const account = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _getCurrentAccount).call(this);
|
|
103
103
|
const currentChainId = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _getChainId).call(this);
|
|
104
104
|
let remoteTransactions = [];
|
|
105
105
|
try {
|
|
106
106
|
remoteTransactions = await _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _remoteTransactionSource).fetchTransactions({
|
|
107
|
-
address,
|
|
107
|
+
address: account.address,
|
|
108
108
|
currentChainId,
|
|
109
109
|
fromBlock,
|
|
110
110
|
limit: _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _transactionLimit)
|
|
@@ -114,8 +114,9 @@ var IncomingTransactionHelper = class {
|
|
|
114
114
|
return;
|
|
115
115
|
}
|
|
116
116
|
if (!_chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _updateTransactions)) {
|
|
117
|
+
const address = account.address.toLowerCase();
|
|
117
118
|
remoteTransactions = remoteTransactions.filter(
|
|
118
|
-
(tx) => tx.txParams.to?.toLowerCase() === address
|
|
119
|
+
(tx) => tx.txParams.to?.toLowerCase() === address
|
|
119
120
|
);
|
|
120
121
|
}
|
|
121
122
|
const localTransactions = !_chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _updateTransactions) ? [] : _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _getLocalTransactions).call(this);
|
|
@@ -221,7 +222,7 @@ updateLastFetchedBlockNumber_fn = function(remoteTxs, additionalKeys) {
|
|
|
221
222
|
_getBlockNumberKey = new WeakSet();
|
|
222
223
|
getBlockNumberKey_fn = function(additionalKeys) {
|
|
223
224
|
const currentChainId = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _getChainId).call(this);
|
|
224
|
-
const currentAccount = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _getCurrentAccount).call(this)?.toLowerCase();
|
|
225
|
+
const currentAccount = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _getCurrentAccount).call(this)?.address.toLowerCase();
|
|
225
226
|
return [currentChainId, currentAccount, ...additionalKeys].join("#");
|
|
226
227
|
};
|
|
227
228
|
_canStart = new WeakSet();
|
|
@@ -235,4 +236,4 @@ canStart_fn = function() {
|
|
|
235
236
|
|
|
236
237
|
|
|
237
238
|
exports.IncomingTransactionHelper = IncomingTransactionHelper;
|
|
238
|
-
//# sourceMappingURL=chunk-
|
|
239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;AAE/B,MAAI,wBAAwB;AAC1B,WAAO,yBAAyB;AAAA,EAClC;AAEA,SAAO,mBAAK,uBACR,SACA,oBAAoB;AAC1B;AAEA;AAAA,kCAA6B,SAC3B,WACA,gBACA;AACA,MAAI,yBAAyB;AAE7B,aAAW,MAAM,WAAW;AAC1B,UAAM,0BAA0B,GAAG,cAC/B,SAAS,GAAG,aAAa,EAAE,IAC3B;AAEJ,6BAAyB,KAAK;AAAA,MAC5B;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,MAAI,2BAA2B,IAAI;AACjC;AAAA,EACF;AAEA,QAAM,iBAAiB,sBAAK,0CAAL,WAAwB;AAC/C,QAAM,0BAA0B,mBAAK,6BAAL;AAChC,QAAM,gBAAgB,wBAAwB,cAAc;AAE5D,MAAI,iBAAiB,wBAAwB;AAC3C;AAAA,EACF;AAEA,OAAK,IAAI,KAAK,kCAAkC;AAAA,IAC9C,yBAAyB;AAAA,MACvB,GAAG;AAAA,MACH,CAAC,cAAc,GAAG;AAAA,IACpB;AAAA,IACA,aAAa;AAAA,EACf,CAAC;AACH;AAEA;AAAA,uBAAkB,SAAC,gBAAkC;AACnD,QAAM,iBAAiB,mBAAK,aAAL;AACvB,QAAM,iBAAiB,mBAAK,oBAAL,YAA2B,QAAQ,YAAY;AAEtE,SAAO,CAAC,gBAAgB,gBAAgB,GAAG,cAAc,EAAE,KAAK,GAAG;AACrE;AAEA;AAAA,cAAS,WAAY;AACnB,QAAM,YAAY,mBAAK,YAAL;AAClB,QAAM,iBAAiB,mBAAK,aAAL;AAEvB,QAAM,qBACJ,mBAAK,0BAAyB,mBAAmB,cAAc;AAEjE,SAAO,aAAa;AACtB","sourcesContent":["import type { AccountsController } from '@metamask/accounts-controller';\nimport type { BlockTracker } from '@metamask/network-controller';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport EventEmitter from 'events';\n\nimport { incomingTransactionsLogger as log } from '../logger';\nimport type { RemoteTransactionSource, TransactionMeta } from '../types';\n\nconst RECENT_HISTORY_BLOCK_RANGE = 10;\n\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst UPDATE_CHECKS: ((txMeta: TransactionMeta) => any)[] = [\n (txMeta) => txMeta.status,\n (txMeta) => txMeta.txParams.gasUsed,\n];\n\n/**\n * Configuration options for the IncomingTransactionHelper\n *\n * @property includeTokenTransfers - Whether or not to include ERC20 token transfers.\n * @property isEnabled - Whether or not incoming transaction retrieval is enabled.\n * @property queryEntireHistory - Whether to initially query the entire transaction history or only recent blocks.\n * @property updateTransactions - Whether to update local transactions using remote transaction data.\n */\nexport type IncomingTransactionOptions = {\n includeTokenTransfers?: boolean;\n isEnabled?: () => boolean;\n queryEntireHistory?: boolean;\n updateTransactions?: boolean;\n};\n\nexport class IncomingTransactionHelper {\n hub: EventEmitter;\n\n #blockTracker: BlockTracker;\n\n #getCurrentAccount: () => ReturnType<\n AccountsController['getSelectedAccount']\n >;\n\n #getLastFetchedBlockNumbers: () => Record<string, number>;\n\n #getLocalTransactions: () => TransactionMeta[];\n\n #getChainId: () => Hex;\n\n #isEnabled: () => boolean;\n\n #isRunning: boolean;\n\n #mutex = new Mutex();\n\n #onLatestBlock: (blockNumberHex: Hex) => Promise<void>;\n\n #queryEntireHistory: boolean;\n\n #remoteTransactionSource: RemoteTransactionSource;\n\n #transactionLimit?: number;\n\n #updateTransactions: boolean;\n\n constructor({\n blockTracker,\n getCurrentAccount,\n getLastFetchedBlockNumbers,\n getLocalTransactions,\n getChainId,\n isEnabled,\n queryEntireHistory,\n remoteTransactionSource,\n transactionLimit,\n updateTransactions,\n }: {\n blockTracker: BlockTracker;\n getCurrentAccount: () => ReturnType<\n AccountsController['getSelectedAccount']\n >;\n getLastFetchedBlockNumbers: () => Record<string, number>;\n getLocalTransactions?: () => TransactionMeta[];\n getChainId: () => Hex;\n isEnabled?: () => boolean;\n queryEntireHistory?: boolean;\n remoteTransactionSource: RemoteTransactionSource;\n transactionLimit?: number;\n updateTransactions?: boolean;\n }) {\n this.hub = new EventEmitter();\n\n this.#blockTracker = blockTracker;\n this.#getCurrentAccount = getCurrentAccount;\n this.#getLastFetchedBlockNumbers = getLastFetchedBlockNumbers;\n this.#getLocalTransactions = getLocalTransactions || (() => []);\n this.#getChainId = getChainId;\n this.#isEnabled = isEnabled ?? (() => true);\n this.#isRunning = false;\n this.#queryEntireHistory = queryEntireHistory ?? true;\n this.#remoteTransactionSource = remoteTransactionSource;\n this.#transactionLimit = transactionLimit;\n this.#updateTransactions = updateTransactions ?? false;\n\n // Using a property instead of a method to provide a listener reference\n // with the correct scope that we can remove later if stopped.\n this.#onLatestBlock = async (blockNumberHex: Hex) => {\n try {\n await this.update(blockNumberHex);\n } catch (error) {\n console.error('Error while checking incoming transactions', error);\n }\n };\n }\n\n start() {\n if (this.#isRunning) {\n return;\n }\n\n if (!this.#canStart()) {\n return;\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#blockTracker.addListener('latest', this.#onLatestBlock);\n this.#isRunning = true;\n }\n\n stop() {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#blockTracker.removeListener('latest', this.#onLatestBlock);\n this.#isRunning = false;\n }\n\n async update(latestBlockNumberHex?: Hex): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n\n log('Checking for incoming transactions');\n\n try {\n if (!this.#canStart()) {\n return;\n }\n\n const latestBlockNumber = parseInt(\n latestBlockNumberHex || (await this.#blockTracker.getLatestBlock()),\n 16,\n );\n\n const additionalLastFetchedKeys =\n this.#remoteTransactionSource.getLastBlockVariations?.() ?? [];\n\n const fromBlock = this.#getFromBlock(latestBlockNumber);\n const account = this.#getCurrentAccount();\n const currentChainId = this.#getChainId();\n\n let remoteTransactions = [];\n\n try {\n remoteTransactions =\n await this.#remoteTransactionSource.fetchTransactions({\n address: account.address,\n currentChainId,\n fromBlock,\n limit: this.#transactionLimit,\n });\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n log('Error while fetching remote transactions', error);\n return;\n }\n if (!this.#updateTransactions) {\n const address = account.address.toLowerCase();\n remoteTransactions = remoteTransactions.filter(\n (tx) => tx.txParams.to?.toLowerCase() === address,\n );\n }\n\n const localTransactions = !this.#updateTransactions\n ? []\n : this.#getLocalTransactions();\n\n const newTransactions = this.#getNewTransactions(\n remoteTransactions,\n localTransactions,\n );\n\n const updatedTransactions = this.#getUpdatedTransactions(\n remoteTransactions,\n localTransactions,\n );\n\n if (newTransactions.length > 0 || updatedTransactions.length > 0) {\n this.#sortTransactionsByTime(newTransactions);\n this.#sortTransactionsByTime(updatedTransactions);\n\n log('Found incoming transactions', {\n new: newTransactions,\n updated: updatedTransactions,\n });\n\n this.hub.emit('transactions', {\n added: newTransactions,\n updated: updatedTransactions,\n });\n }\n this.#updateLastFetchedBlockNumber(\n remoteTransactions,\n additionalLastFetchedKeys,\n );\n } finally {\n releaseLock();\n }\n }\n\n #sortTransactionsByTime(transactions: TransactionMeta[]) {\n transactions.sort((a, b) => (a.time < b.time ? -1 : 1));\n }\n\n #getNewTransactions(\n remoteTxs: TransactionMeta[],\n localTxs: TransactionMeta[],\n ): TransactionMeta[] {\n return remoteTxs.filter(\n (tx) => !localTxs.some(({ hash }) => hash === tx.hash),\n );\n }\n\n #getUpdatedTransactions(\n remoteTxs: TransactionMeta[],\n localTxs: TransactionMeta[],\n ): TransactionMeta[] {\n return remoteTxs.filter((remoteTx) =>\n localTxs.some(\n (localTx) =>\n remoteTx.hash === localTx.hash &&\n this.#isTransactionOutdated(remoteTx, localTx),\n ),\n );\n }\n\n #isTransactionOutdated(\n remoteTx: TransactionMeta,\n localTx: TransactionMeta,\n ): boolean {\n return UPDATE_CHECKS.some(\n (getValue) => getValue(remoteTx) !== getValue(localTx),\n );\n }\n\n #getLastFetchedBlockNumberDec(): number {\n const additionalLastFetchedKeys =\n this.#remoteTransactionSource.getLastBlockVariations?.() ?? [];\n const lastFetchedKey = this.#getBlockNumberKey(additionalLastFetchedKeys);\n const lastFetchedBlockNumbers = this.#getLastFetchedBlockNumbers();\n return lastFetchedBlockNumbers[lastFetchedKey];\n }\n\n #getFromBlock(latestBlockNumber: number): number | undefined {\n const lastFetchedBlockNumber = this.#getLastFetchedBlockNumberDec();\n\n if (lastFetchedBlockNumber) {\n return lastFetchedBlockNumber + 1;\n }\n\n return this.#queryEntireHistory\n ? undefined\n : latestBlockNumber - RECENT_HISTORY_BLOCK_RANGE;\n }\n\n #updateLastFetchedBlockNumber(\n remoteTxs: TransactionMeta[],\n additionalKeys: string[],\n ) {\n let lastFetchedBlockNumber = -1;\n\n for (const tx of remoteTxs) {\n const currentBlockNumberValue = tx.blockNumber\n ? parseInt(tx.blockNumber, 10)\n : -1;\n\n lastFetchedBlockNumber = Math.max(\n lastFetchedBlockNumber,\n currentBlockNumberValue,\n );\n }\n\n if (lastFetchedBlockNumber === -1) {\n return;\n }\n\n const lastFetchedKey = this.#getBlockNumberKey(additionalKeys);\n const lastFetchedBlockNumbers = this.#getLastFetchedBlockNumbers();\n const previousValue = lastFetchedBlockNumbers[lastFetchedKey];\n\n if (previousValue >= lastFetchedBlockNumber) {\n return;\n }\n\n this.hub.emit('updatedLastFetchedBlockNumbers', {\n lastFetchedBlockNumbers: {\n ...lastFetchedBlockNumbers,\n [lastFetchedKey]: lastFetchedBlockNumber,\n },\n blockNumber: lastFetchedBlockNumber,\n });\n }\n\n #getBlockNumberKey(additionalKeys: string[]): string {\n const currentChainId = this.#getChainId();\n const currentAccount = this.#getCurrentAccount()?.address.toLowerCase();\n\n return [currentChainId, currentAccount, ...additionalKeys].join('#');\n }\n\n #canStart(): boolean {\n const isEnabled = this.#isEnabled();\n const currentChainId = this.#getChainId();\n\n const isSupportedNetwork =\n this.#remoteTransactionSource.isSupportedNetwork(currentChainId);\n\n return isEnabled && isSupportedNetwork;\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkOZ6UB42Cjs = require('./chunk-OZ6UB42C.js');
|
|
4
4
|
|
|
5
5
|
// src/utils/validation.ts
|
|
6
6
|
var _abi = require('@ethersproject/abi');
|
|
@@ -35,7 +35,7 @@ function validateTxParams(txParams, isEIP1559Compatible = true) {
|
|
|
35
35
|
validateGasFeeParams(txParams);
|
|
36
36
|
}
|
|
37
37
|
function validateEIP1559Compatibility(txParams, isEIP1559Compatible) {
|
|
38
|
-
if (
|
|
38
|
+
if (_chunkOZ6UB42Cjs.isEIP1559Transaction.call(void 0, txParams) && !isEIP1559Compatible) {
|
|
39
39
|
throw _rpcerrors.rpcErrors.invalidParams(
|
|
40
40
|
"Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559"
|
|
41
41
|
);
|
|
@@ -100,6 +100,8 @@ function validateParamData(value) {
|
|
|
100
100
|
function validateParamChainId(chainId) {
|
|
101
101
|
if (chainId !== void 0 && typeof chainId !== "number" && typeof chainId !== "string") {
|
|
102
102
|
throw _rpcerrors.rpcErrors.invalidParams(
|
|
103
|
+
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
104
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
103
105
|
`Invalid transaction params: chainId is not a Number or hex string. got: (${chainId})`
|
|
104
106
|
);
|
|
105
107
|
}
|
|
@@ -170,6 +172,8 @@ function ensureMutuallyExclusiveFieldsNotProvided(txParams, fieldBeingValidated,
|
|
|
170
172
|
function ensureFieldIsString(txParams, field) {
|
|
171
173
|
if (typeof txParams[field] !== "string") {
|
|
172
174
|
throw _rpcerrors.rpcErrors.invalidParams(
|
|
175
|
+
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
176
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
173
177
|
`Invalid transaction params: ${field} is not a string. got: (${txParams[field]})`
|
|
174
178
|
);
|
|
175
179
|
}
|
|
@@ -179,4 +183,4 @@ function ensureFieldIsString(txParams, field) {
|
|
|
179
183
|
|
|
180
184
|
|
|
181
185
|
exports.validateTransactionOrigin = validateTransactionOrigin; exports.validateTxParams = validateTxParams;
|
|
182
|
-
//# sourceMappingURL=chunk-
|
|
186
|
+
//# sourceMappingURL=chunk-RXIUMVA5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/validation.ts"],"names":[],"mappings":";;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB,yBAAyB;AACnD,SAAS,gBAAgB;AACzB,SAAS,gBAAgB,iBAAiB;AAgB1C,eAAsB,0BACpB,oBACA,iBACA,MACA,QACA;AACA,MAAI,WAAW,iBAAiB;AAE9B,QAAI,SAAS,iBAAiB;AAC5B,YAAM,UAAU,SAAS;AAAA,QACvB,SAAS;AAAA,QACT,MAAM;AAAA,UACJ;AAAA,UACA,aAAa;AAAA,UACb;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AACA;AAAA,EACF;AAGA,MAAI,CAAC,mBAAmB,SAAS,IAAI,GAAG;AACtC,UAAM,eAAe,aAAa,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;AAAA,EACxD;AACF;AASO,SAAS,iBACd,UACA,sBAAsB,MACtB;AACA,+BAA6B,UAAU,mBAAmB;AAC1D,oBAAkB,SAAS,IAAI;AAC/B,yBAAuB,QAAQ;AAC/B,qBAAmB,SAAS,KAAK;AACjC,oBAAkB,SAAS,IAAI;AAC/B,uBAAqB,SAAS,OAAO;AACrC,uBAAqB,QAAQ;AAC/B;AASA,SAAS,6BACP,UACA,qBACA;AACA,MAAI,qBAAqB,QAAQ,KAAK,CAAC,qBAAqB;AAC1D,UAAM,UAAU;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;AAaA,SAAS,mBAAmB,OAAgB;AAC1C,MAAI,UAAU,Q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AA,IAC1G;AAAA,EACF;AACF;AAUA,SAAS,oBACP,UACA,OACA;AACA,MAAI,OAAO,SAAS,KAAK,MAAM,UAAU;AACvC,UAAM,UAAU;AAAA;AAAA;AAAA,MAGd,+BAA+B,KAAK,2BAA2B,SAAS,KAAK,CAAC;AAAA,IAChF;AAAA,EACF;AACF","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport { ORIGIN_METAMASK, isValidHexAddress } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\n\nimport { TransactionEnvelopeType, type TransactionParams } from '../types';\nimport { isEIP1559Transaction } from './utils';\n\ntype GasFieldsToValidate = 'gasPrice' | 'maxFeePerGas' | 'maxPriorityFeePerGas';\n\n/**\n * Validates whether a transaction initiated by a specific 'from' address is permitted by the origin.\n *\n * @param permittedAddresses - The permitted accounts for the given origin.\n * @param selectedAddress - The currently selected Ethereum address in the wallet.\n * @param from - The address from which the transaction is initiated.\n * @param origin - The origin or source of the transaction.\n * @throws Throws an error if the transaction is not permitted.\n */\nexport async function validateTransactionOrigin(\n permittedAddresses: string[],\n selectedAddress: string,\n from: string,\n origin: string,\n) {\n if (origin === ORIGIN_METAMASK) {\n // Ensure the 'from' address matches the currently selected address\n if (from !== selectedAddress) {\n throw rpcErrors.internal({\n message: `Internally initiated transaction is using invalid account.`,\n data: {\n origin,\n fromAddress: from,\n selectedAddress,\n },\n });\n }\n return;\n }\n\n // Check if the origin has permissions to initiate transactions from the specified address\n if (!permittedAddresses.includes(from)) {\n throw providerErrors.unauthorized({ data: { origin } });\n }\n}\n\n/**\n * Validates the transaction params for required properties and throws in\n * the event of any validation error.\n *\n * @param txParams - Transaction params object to validate.\n * @param isEIP1559Compatible - whether or not the current network supports EIP-1559 transactions.\n */\nexport function validateTxParams(\n txParams: TransactionParams,\n isEIP1559Compatible = true,\n) {\n validateEIP1559Compatibility(txParams, isEIP1559Compatible);\n validateParamFrom(txParams.from);\n validateParamRecipient(txParams);\n validateParamValue(txParams.value);\n validateParamData(txParams.data);\n validateParamChainId(txParams.chainId);\n validateGasFeeParams(txParams);\n}\n\n/**\n * Validates EIP-1559 compatibility for transaction creation.\n *\n * @param txParams - The transaction parameters to validate.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n * @throws Throws invalid params if the transaction specifies EIP-1559 but the network does not support it.\n */\nfunction validateEIP1559Compatibility(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (isEIP1559Transaction(txParams) && !isEIP1559Compatible) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559',\n );\n }\n}\n\n/**\n * Validates value property, ensuring it is a valid positive integer number\n * denominated in wei.\n *\n * @param value - The value to validate, expressed as a string.\n * @throws Throws an error if the value is not a valid positive integer\n * number denominated in wei.\n * - If the value contains a hyphen (-), it is considered invalid.\n * - If the value contains a decimal point (.), it is considered invalid.\n * - If the value is not a finite number, is NaN, or is not a safe integer, it is considered invalid.\n */\nfunction validateParamValue(value?: string) {\n if (value !== undefined) {\n if (value.includes('-')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": not a positive number.`,\n );\n }\n\n if (value.includes('.')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": number must be in wei.`,\n );\n }\n const intValue = parseInt(value, 10);\n const isValid =\n Number.isFinite(intValue) &&\n !Number.isNaN(intValue) &&\n !isNaN(Number(value)) &&\n Number.isSafeInteger(intValue);\n if (!isValid) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value ${value}: number must be a valid number.`,\n );\n }\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param txParams - The transaction parameters object to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamRecipient(txParams: TransactionParams) {\n if (txParams.to === '0x' || txParams.to === undefined) {\n if (txParams.data) {\n delete txParams.to;\n } else {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n } else if (txParams.to !== undefined && !isValidHexAddress(txParams.to)) {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param from - The from property to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamFrom(from: string) {\n if (!from || typeof from !== 'string') {\n throw rpcErrors.invalidParams(\n `Invalid \"from\" address ${from}: not a string.`,\n );\n }\n if (!isValidHexAddress(from)) {\n throw rpcErrors.invalidParams('Invalid \"from\" address.');\n }\n}\n\n/**\n * Validates input data for transactions.\n *\n * @param value - The input data to validate.\n * @throws Throws invalid params if the input data is invalid.\n */\nfunction validateParamData(value?: string) {\n if (value) {\n const ERC20Interface = new Interface(abiERC20);\n try {\n ERC20Interface.parseTransaction({ data: value });\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.message.match(/BUFFER_OVERRUN/u)) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: data out-of-bounds, BUFFER_OVERRUN.',\n );\n }\n }\n }\n}\n\n/**\n * Validates chainId type.\n *\n * @param chainId - The chainId to validate.\n */\nfunction validateParamChainId(chainId: number | string | undefined) {\n if (\n chainId !== undefined &&\n typeof chainId !== 'number' &&\n typeof chainId !== 'string'\n ) {\n throw rpcErrors.invalidParams(\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 `Invalid transaction params: chainId is not a Number or hex string. got: (${chainId})`,\n );\n }\n}\n\n/**\n * Validates gas values.\n *\n * @param txParams - The transaction parameters to validate.\n */\nfunction validateGasFeeParams(txParams: TransactionParams) {\n if (txParams.gasPrice) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'gasPrice');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxPriorityFeePerGas',\n );\n ensureFieldIsString(txParams, 'gasPrice');\n }\n\n if (txParams.maxFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'maxFeePerGas');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsString(txParams, 'maxFeePerGas');\n }\n\n if (txParams.maxPriorityFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(\n txParams,\n 'maxPriorityFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxPriorityFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsString(txParams, 'maxPriorityFeePerGas');\n }\n}\n\n/**\n * Ensures that the provided txParams has the proper 'type' specified for the\n * given field, if it is provided. If types do not match throws an\n * invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param field - The current field being validated\n * @throws {ethErrors.rpc.invalidParams} Throws if type does not match the\n * expectations for provided field.\n */\nfunction ensureProperTransactionEnvelopeTypeProvided(\n txParams: TransactionParams,\n field: GasFieldsToValidate,\n) {\n switch (field) {\n case 'maxFeePerGas':\n case 'maxPriorityFeePerGas':\n if (\n txParams.type &&\n txParams.type !== TransactionEnvelopeType.feeMarket\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${txParams.type}\" but including maxFeePerGas and maxPriorityFeePerGas requires type: \"${TransactionEnvelopeType.feeMarket}\"`,\n );\n }\n break;\n case 'gasPrice':\n default:\n if (\n txParams.type &&\n txParams.type === TransactionEnvelopeType.feeMarket\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${txParams.type}\" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`,\n );\n }\n }\n}\n\n/**\n * Given two fields, ensure that the second field is not included in txParams,\n * and if it is throw an invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param fieldBeingValidated - The current field being validated\n * @param mutuallyExclusiveField - The field to ensure is not provided\n * @throws {ethErrors.rpc.invalidParams} Throws if mutuallyExclusiveField is\n * present in txParams.\n */\nfunction ensureMutuallyExclusiveFieldsNotProvided(\n txParams: TransactionParams,\n fieldBeingValidated: GasFieldsToValidate,\n mutuallyExclusiveField: GasFieldsToValidate,\n) {\n if (typeof txParams[mutuallyExclusiveField] !== 'undefined') {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: specified ${fieldBeingValidated} but also included ${mutuallyExclusiveField}, these cannot be mixed`,\n );\n }\n}\n\n/**\n * Ensures that the provided value for field is a string, throws an\n * invalidParams error if field is not a string.\n *\n * @param txParams - The transaction parameters object\n * @param field - The current field being validated\n * @throws {rpcErrors.invalidParams} Throws if field is not a string\n */\nfunction ensureFieldIsString(\n txParams: TransactionParams,\n field: GasFieldsToValidate,\n) {\n if (typeof txParams[field] !== 'string') {\n throw rpcErrors.invalidParams(\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 `Invalid transaction params: ${field} is not a string. got: (${txParams[field]})`,\n );\n }\n}\n"]}
|