@metamask/transaction-controller 62.4.0 → 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 +9 -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/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 +3 -1
- 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 +3 -1
- 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 +2 -2
package/dist/utils/gas.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas.mjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EACP,UAAU,EACV,OAAO,EACP,KAAK,EACL,KAAK,EACN,mCAAmC;AAGpC,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,QAAQ,EAAE,wBAAwB;AACtE,OAAO,EAAE,EAAE,EAAE,cAAc;AAE3B,OAAO,EAAE,iBAAiB,EAAE,sBAAkB;AAC9C,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,4BAAwB;AAC/E,OAAO,EAAE,oBAAoB,EAAE,kCAA8B;AAC7D,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAM1C,OAAO,EACL,uBAAuB,EAGxB,qBAAiB;AAYlB,MAAM,CAAC,MAAM,G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Y,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;IAEtD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;IAC/C,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,0BAA0B,CACjC,iBAAyD,EACzD,OAAY;IAEZ,OAAO,iBAAiB,EAAE,GAAG,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC;QAChD,GAAG,aAAa;QAChB,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,OAAO;QACzC,KAAK,EAAE,aAAa,CAAC,KAAK,IAAI,KAAK;QACnC,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,6BAA6B;QACnD,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,6BAA6B;QACnD,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,KAAK;KACxC,CAAC,CAAC,CAAC;AACN,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,eAAe,CACtB,QAAkB,EAClB,QAA2B,EAC3B,iBAAuB;IAEvB,MAAM,EAAE,IAAI,EAAE,GAAG,QAAQ,CAAC;IAC1B,MAAM,MAAM,GAAG,CAAC,QAAQ,CAAW,CAAC;IAEpC,IAAI,iBAAiB,EAAE,CAAC;QACtB,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAEtB,MAAM,CAAC,IAAI,CAAC;YACV,CAAC,IAAc,CAAC,EAAE;gBAChB,IAAI,EAAE,iBAAiB,GAAG,QAAQ,CAAC,iBAAiB,CAAC;aACtD;SACF,CAAC,CAAC;IACL,CAAC;IAED,OAAO,KAAK,CAAC,QAAQ,EAAE,aAAa,EAAE,MAAM,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import {\n BNToHex,\n fractionBN,\n hexToBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type { Hex, Json } from '@metamask/utils';\nimport { add0x, createModuleLogger, remove0x } from '@metamask/utils';\nimport { BN } from 'bn.js';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport { getGasEstimateBuffer, getGasEstimateFallback } from './feature-flags';\nimport { simulateTransactions } from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n GetSimulationConfig,\n TransactionBatchSingleRequest,\n} from '../types';\nimport {\n TransactionEnvelopeType,\n type TransactionMeta,\n type TransactionParams,\n} from '../types';\n\nexport type UpdateGasRequest = {\n chainId: Hex;\n ethQuery: EthQuery;\n isCustomNetwork: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport const log = createModuleLogger(projectLogger, 'gas');\n\nexport const FIXED_GAS = '0x5208';\nexport const DEFAULT_GAS_MULTIPLIER = 1.5;\nexport const MAX_GAS_BLOCK_PERCENT = 90;\nexport const INTRINSIC_GAS = 21000;\n\nexport const DUMMY_AUTHORIZATION_SIGNATURE =\n '0x1111111111111111111111111111111111111111111111111111111111111111';\n\n/**\n * Populate the gas properties of the provided transaction meta.\n *\n * @param request - The request object including the necessary parameters.\n */\nexport async function updateGas(request: UpdateGasRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const [gas, simulationFails, gasLimitNoBuffer] = await getGas(request);\n\n txMeta.txParams.gas = gas;\n txMeta.simulationFails = simulationFails;\n txMeta.gasLimitNoBuffer = gasLimitNoBuffer;\n\n if (!initialParams.gas) {\n txMeta.originalGasEstimate = txMeta.txParams.gas;\n }\n\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;\n}\n\n/**\n * Estimate the gas for the provided transaction parameters.\n * If the gas estimate fails, the fallback value is returned.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transaction.\n * @param options.ethQuery - The EthQuery instance to interact with the network.\n * @param options.ignoreDelegationSignatures - Ignore signature errors if submitting delegations to the DelegationManager.\n * @param options.isSimulationEnabled - Whether the simulation is enabled.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.messenger - The messenger instance for communication.\n * @param options.txParams - The transaction parameters.\n * @returns The estimated gas and related info.\n */\nexport async function estimateGas({\n chainId,\n ethQuery,\n ignoreDelegationSignatures,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txParams,\n}: {\n chainId: Hex;\n ethQuery: EthQuery;\n ignoreDelegationSignatures?: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n txParams: TransactionParams;\n}) {\n const request = { ...txParams };\n const { authorizationList, data, from, value, to } = request;\n\n if (ignoreDelegationSignatures && !isSimulationEnabled) {\n throw new Error(\n 'Gas estimation with ignored delegation signatures is not supported as simulation disabled',\n );\n }\n\n const { gasLimit: blockGasLimit, number: blockNumber } =\n await getLatestBlock(ethQuery);\n\n const blockGasLimitBN = hexToBN(blockGasLimit);\n const { percentage, fixed } = getGasEstimateFallback(chainId, messenger);\n\n const fallback = fixed\n ? toHex(fixed)\n : BNToHex(fractionBN(blockGasLimitBN, percentage, 100));\n\n log('Estimation fallback values', fallback);\n\n request.data = data ? add0x(data) : data;\n request.value = value || '0x0';\n\n request.authorizationList = normalizeAuthorizationList(\n request.authorizationList,\n chainId,\n );\n\n delete request.gasPrice;\n delete request.maxFeePerGas;\n delete request.maxPriorityFeePerGas;\n\n let estimatedGas = fallback;\n let simulationFails: TransactionMeta['simulationFails'];\n\n const isUpgradeWithDataToSelf =\n txParams.type === TransactionEnvelopeType.setCode &&\n Boolean(authorizationList?.length) &&\n Boolean(data) &&\n data !== '0x' &&\n from?.toLowerCase() === to?.toLowerCase();\n\n try {\n if (isSimulationEnabled && isUpgradeWithDataToSelf) {\n estimatedGas = await estimateGasUpgradeWithDataToSelf(\n request,\n ethQuery,\n chainId,\n getSimulationConfig,\n );\n } else if (ignoreDelegationSignatures && isSimulationEnabled) {\n estimatedGas = await simulateGas({\n chainId,\n getSimulationConfig,\n transaction: request,\n });\n } else {\n estimatedGas = await estimateGasNode(ethQuery, request);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n simulationFails = {\n reason: error.message,\n errorKey: error.errorKey,\n debug: {\n blockNumber,\n blockGasLimit,\n },\n };\n\n log('Estimation failed', { ...simulationFails, fallback });\n }\n\n return {\n blockGasLimit,\n estimatedGas,\n isUpgradeWithDataToSelf,\n simulationFails,\n };\n}\n\n/**\n * Add a buffer to the provided estimated gas.\n * The buffer is calculated based on the block gas limit and a multiplier.\n *\n * @param estimatedGas - The estimated gas.\n * @param blockGasLimit - The block gas limit.\n * @param multiplier - The multiplier to apply to the estimated gas.\n * @returns The gas with the buffer applied.\n */\nexport function addGasBuffer(\n estimatedGas: string,\n blockGasLimit: string,\n multiplier: number,\n) {\n const estimatedGasBN = hexToBN(estimatedGas);\n\n const maxGasBN = fractionBN(\n hexToBN(blockGasLimit),\n MAX_GAS_BLOCK_PERCENT,\n 100,\n );\n\n const paddedGasBN = fractionBN(estimatedGasBN, multiplier * 100, 100);\n\n if (estimatedGasBN.gt(maxGasBN)) {\n const estimatedGasHex = add0x(estimatedGas);\n log('Using estimated value', estimatedGasHex);\n return estimatedGasHex;\n }\n\n if (paddedGasBN.lt(maxGasBN)) {\n const paddedHex = add0x(BNToHex(paddedGasBN));\n log('Using padded estimate', paddedHex, multiplier);\n return paddedHex;\n }\n\n const maxHex = add0x(BNToHex(maxGasBN));\n log('Using 90% of block gas limit', maxHex);\n return maxHex;\n}\n\n/**\n * Simulate the required gas for a batch of transactions using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transactions.\n * @param options.from - The address of the sender.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transactions - The array of transactions within a batch request.\n * @returns An object containing the transactions with their gas limits and the total gas limit.\n */\nexport async function simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions,\n}: {\n chainId: Hex;\n from: Hex;\n getSimulationConfig: GetSimulationConfig;\n transactions: TransactionBatchSingleRequest[];\n}): Promise<{ gasLimit: Hex }> {\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: transactions.map((transaction) => ({\n ...transaction.params,\n from,\n })),\n });\n\n if (\n !response?.transactions ||\n response.transactions.length !== transactions.length\n ) {\n throw new Error('Simulation response does not match transaction count');\n }\n\n const totalGasLimit = response.transactions.reduce((acc, transaction) => {\n const gasLimit = transaction?.gasLimit;\n\n if (!gasLimit) {\n throw new Error(\n 'No simulated gas returned for one of the transactions',\n );\n }\n\n return acc.add(hexToBN(gasLimit));\n }, new BN(0));\n\n return {\n gasLimit: BNToHex(totalGasLimit), // Return the total gas limit as a hex string\n };\n } catch (error: unknown) {\n log('Error while simulating gas batch', error);\n throw new Error(\n 'Cannot estimate transaction batch total gas as simulation failed',\n );\n }\n}\n\n/**\n * Determine the gas for the provided request.\n *\n * @param request - The request object including the necessary parameters.\n * @returns The final gas value and the estimate used.\n */\nasync function getGas(\n request: UpdateGasRequest,\n): Promise<[string, TransactionMeta['simulationFails']?, string?]> {\n const {\n chainId,\n isCustomNetwork,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txMeta,\n } = request;\n const { disableGasBuffer } = txMeta;\n\n if (txMeta.txParams.gas) {\n log('Using value from request', txMeta.txParams.gas);\n return [txMeta.txParams.gas, undefined, txMeta.txParams.gas];\n }\n\n if (await requiresFixedGas(request)) {\n log('Using fixed value', FIXED_GAS);\n return [FIXED_GAS, undefined, FIXED_GAS];\n }\n\n const {\n blockGasLimit,\n estimatedGas,\n isUpgradeWithDataToSelf,\n simulationFails,\n } = await estimateGas({\n chainId,\n ethQuery: request.ethQuery,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txParams: txMeta.txParams,\n });\n\n log('Original estimated gas', estimatedGas);\n\n if (simulationFails) {\n log('Using original fallback estimate as simulation failed');\n }\n\n if (disableGasBuffer) {\n log('Gas buffer disabled');\n }\n\n if (simulationFails || disableGasBuffer) {\n return [estimatedGas, simulationFails, estimatedGas];\n }\n\n const bufferMultiplier = getGasEstimateBuffer({\n chainId,\n isCustomRPC: isCustomNetwork,\n isUpgradeWithDataToSelf,\n messenger,\n });\n\n log('Buffer', bufferMultiplier);\n\n const bufferedGas = addGasBuffer(\n estimatedGas,\n blockGasLimit,\n bufferMultiplier,\n );\n\n log('Buffered gas', bufferedGas);\n\n return [bufferedGas, simulationFails, estimatedGas];\n}\n\n/**\n * Determine if the gas for the provided request should be fixed.\n *\n * @param options - The options object.\n * @param options.ethQuery - The EthQuery instance to interact with the network.\n * @param options.txMeta - The transaction meta object.\n * @param options.isCustomNetwork - Whether the network is a custom network.\n * @returns Whether the gas should be fixed.\n */\nasync function requiresFixedGas({\n ethQuery,\n txMeta,\n isCustomNetwork,\n}: UpdateGasRequest): Promise<boolean> {\n const {\n txParams: { to, data, type },\n } = txMeta;\n\n if (\n isCustomNetwork ||\n !to ||\n data ||\n type === TransactionEnvelopeType.setCode\n ) {\n return false;\n }\n\n const code = await getCode(ethQuery, to);\n\n return !code || code === '0x';\n}\n\n/**\n * Get the contract code for the provided address.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param address - The address to get the code for.\n * @returns The contract code.\n */\nasync function getCode(\n ethQuery: EthQuery,\n address: string,\n): Promise<string | undefined> {\n return await query(ethQuery, 'getCode', [address]);\n}\n\n/**\n * Get the latest block from the network.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @returns The latest block number.\n */\nasync function getLatestBlock(\n ethQuery: EthQuery,\n): Promise<{ gasLimit: string; number: string }> {\n return await query(ethQuery, 'getBlockByNumber', ['latest', false]);\n}\n\n/**\n * Estimate the gas for a type 4 transaction.\n *\n * @param txParams - The transaction parameters.\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param chainId - The chain ID of the transaction.\n * @param getSimulationConfig - The function to get the simulation configuration.\n * @returns The estimated gas.\n */\nasync function estimateGasUpgradeWithDataToSelf(\n txParams: TransactionParams,\n ethQuery: EthQuery,\n chainId: Hex,\n getSimulationConfig: GetSimulationConfig,\n) {\n const upgradeGas = await query(ethQuery, 'estimateGas', [\n {\n ...txParams,\n data: '0x',\n },\n ]);\n\n log('Upgrade only gas', upgradeGas);\n\n const delegationAddress = txParams.authorizationList?.[0].address as Hex;\n\n let executeGas: Hex | undefined;\n\n try {\n executeGas = await simulateGas({\n chainId: chainId as Hex,\n delegationAddress,\n getSimulationConfig,\n transaction: txParams,\n });\n } catch (error: unknown) {\n log('Error while simulating data portion of upgrade', error);\n }\n\n if (executeGas === undefined) {\n try {\n executeGas = await estimateGasNode(\n ethQuery,\n { ...txParams, authorizationList: undefined, type: undefined },\n delegationAddress,\n );\n } catch (error: unknown) {\n log('Error while estimating data portion of upgrade', error);\n throw error;\n }\n\n log('Success estimating data portion of upgrade', executeGas);\n }\n\n log('Execute gas', executeGas);\n\n const total = BNToHex(\n hexToBN(upgradeGas)\n .add(hexToBN(executeGas as Hex))\n .subn(INTRINSIC_GAS),\n );\n\n log('Total type 4 gas', total);\n\n return total;\n}\n\n/**\n * Simulate the required gas using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transaction.\n * @param options.delegationAddress - The delegation address of the sender to mock.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transaction - The transaction parameters.\n * @returns The simulated gas.\n */\nasync function simulateGas({\n chainId,\n delegationAddress,\n getSimulationConfig,\n transaction,\n}: {\n chainId: Hex;\n delegationAddress?: Hex;\n getSimulationConfig: GetSimulationConfig;\n transaction: TransactionParams;\n}): Promise<Hex> {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n to: transaction.to as Hex,\n from: transaction.from as Hex,\n data: transaction.data as Hex,\n value: transaction.value as Hex,\n },\n ],\n overrides: {\n [transaction.from as string]: {\n code:\n delegationAddress &&\n ((DELEGATION_PREFIX + remove0x(delegationAddress)) as Hex),\n },\n },\n });\n\n const gasLimit = response?.transactions?.[0].gasLimit;\n\n if (!gasLimit) {\n throw new Error('No simulated gas returned');\n }\n\n return gasLimit;\n}\n\n/**\n * Populate the authorization list with dummy values.\n *\n * @param authorizationList - The authorization list to prepare.\n * @param chainId - The chain ID to use.\n * @returns The authorization list with dummy values.\n */\nfunction normalizeAuthorizationList(\n authorizationList: TransactionParams['authorizationList'],\n chainId: Hex,\n) {\n return authorizationList?.map((authorization) => ({\n ...authorization,\n chainId: authorization.chainId ?? chainId,\n nonce: authorization.nonce ?? '0x1',\n r: authorization.r ?? DUMMY_AUTHORIZATION_SIGNATURE,\n s: authorization.s ?? DUMMY_AUTHORIZATION_SIGNATURE,\n yParity: authorization.yParity ?? '0x1',\n }));\n}\n\n/**\n * Estimate the gas for a transaction using the `eth_estimateGas` method.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param txParams - The transaction parameters.\n * @param delegationAddress - The delegation address of the sender to mock.\n * @returns The estimated gas as a hex string.\n */\nfunction estimateGasNode(\n ethQuery: EthQuery,\n txParams: TransactionParams,\n delegationAddress?: Hex,\n) {\n const { from } = txParams;\n const params = [txParams] as Json[];\n\n if (delegationAddress) {\n params.push('latest');\n\n params.push({\n [from as string]: {\n code: DELEGATION_PREFIX + remove0x(delegationAddress),\n },\n });\n }\n\n return query(ethQuery, 'estimateGas', params);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gas.mjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EACP,UAAU,EACV,OAAO,EACP,KAAK,EACL,KAAK,EACN,mCAAmC;AAGpC,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,QAAQ,EAAE,wBAAwB;AACtE,OAAO,EAAE,EAAE,EAAE,cAAc;AAE3B,OAAO,EAAE,iBAAiB,EAAE,sBAAkB;AAC9C,OAAO,EAAE,oBAAoB,EAA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,aAAa,EAAE,MAAM,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import {\n BNToHex,\n fractionBN,\n hexToBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type { Hex, Json } from '@metamask/utils';\nimport { add0x, createModuleLogger, remove0x } from '@metamask/utils';\nimport { BN } from 'bn.js';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport { getGasEstimateBuffer, getGasEstimateFallback } from './feature-flags';\nimport { simulateTransactions } from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport { TransactionEnvelopeType } from '../types';\nimport type {\n GetSimulationConfig,\n TransactionBatchSingleRequest,\n TransactionMeta,\n TransactionParams,\n} from '../types';\n\nexport type UpdateGasRequest = {\n chainId: Hex;\n ethQuery: EthQuery;\n isCustomNetwork: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport const log = createModuleLogger(projectLogger, 'gas');\n\nexport const FIXED_GAS = '0x5208';\nexport const DEFAULT_GAS_MULTIPLIER = 1.5;\nexport const MAX_GAS_BLOCK_PERCENT = 90;\nexport const INTRINSIC_GAS = 21000;\n\nexport const DUMMY_AUTHORIZATION_SIGNATURE =\n '0x1111111111111111111111111111111111111111111111111111111111111111';\n\n/**\n * Populate the gas properties of the provided transaction meta.\n *\n * @param request - The request object including the necessary parameters.\n */\nexport async function updateGas(request: UpdateGasRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const [gas, simulationFails, gasLimitNoBuffer] = await getGas(request);\n\n txMeta.txParams.gas = gas;\n txMeta.simulationFails = simulationFails;\n txMeta.gasLimitNoBuffer = gasLimitNoBuffer;\n\n if (!initialParams.gas) {\n txMeta.originalGasEstimate = txMeta.txParams.gas;\n }\n\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;\n}\n\n/**\n * Estimate the gas for the provided transaction parameters.\n * If the gas estimate fails, the fallback value is returned.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transaction.\n * @param options.ethQuery - The EthQuery instance to interact with the network.\n * @param options.ignoreDelegationSignatures - Ignore signature errors if submitting delegations to the DelegationManager.\n * @param options.isSimulationEnabled - Whether the simulation is enabled.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.messenger - The messenger instance for communication.\n * @param options.txParams - The transaction parameters.\n * @returns The estimated gas and related info.\n */\nexport async function estimateGas({\n chainId,\n ethQuery,\n ignoreDelegationSignatures,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txParams,\n}: {\n chainId: Hex;\n ethQuery: EthQuery;\n ignoreDelegationSignatures?: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n txParams: TransactionParams;\n}) {\n const request = { ...txParams };\n const { authorizationList, data, from, value, to } = request;\n\n if (ignoreDelegationSignatures && !isSimulationEnabled) {\n throw new Error(\n 'Gas estimation with ignored delegation signatures is not supported as simulation disabled',\n );\n }\n\n const { gasLimit: blockGasLimit, number: blockNumber } =\n await getLatestBlock(ethQuery);\n\n const blockGasLimitBN = hexToBN(blockGasLimit);\n const { percentage, fixed } = getGasEstimateFallback(chainId, messenger);\n\n const fallback = fixed\n ? toHex(fixed)\n : BNToHex(fractionBN(blockGasLimitBN, percentage, 100));\n\n log('Estimation fallback values', fallback);\n\n request.data = data ? add0x(data) : data;\n request.value = value || '0x0';\n\n request.authorizationList = normalizeAuthorizationList(\n request.authorizationList,\n chainId,\n );\n\n delete request.gasPrice;\n delete request.maxFeePerGas;\n delete request.maxPriorityFeePerGas;\n\n let estimatedGas = fallback;\n let simulationFails: TransactionMeta['simulationFails'];\n\n const isUpgradeWithDataToSelf =\n txParams.type === TransactionEnvelopeType.setCode &&\n Boolean(authorizationList?.length) &&\n Boolean(data) &&\n data !== '0x' &&\n from?.toLowerCase() === to?.toLowerCase();\n\n try {\n if (isSimulationEnabled && isUpgradeWithDataToSelf) {\n estimatedGas = await estimateGasUpgradeWithDataToSelf(\n request,\n ethQuery,\n chainId,\n getSimulationConfig,\n );\n } else if (ignoreDelegationSignatures && isSimulationEnabled) {\n estimatedGas = await simulateGas({\n chainId,\n getSimulationConfig,\n transaction: request,\n });\n } else {\n estimatedGas = await estimateGasNode(ethQuery, request);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n simulationFails = {\n reason: error.message,\n errorKey: error.errorKey,\n debug: {\n blockNumber,\n blockGasLimit,\n },\n };\n\n log('Estimation failed', { ...simulationFails, fallback });\n }\n\n return {\n blockGasLimit,\n estimatedGas,\n isUpgradeWithDataToSelf,\n simulationFails,\n };\n}\n\n/**\n * Add a buffer to the provided estimated gas.\n * The buffer is calculated based on the block gas limit and a multiplier.\n *\n * @param estimatedGas - The estimated gas.\n * @param blockGasLimit - The block gas limit.\n * @param multiplier - The multiplier to apply to the estimated gas.\n * @returns The gas with the buffer applied.\n */\nexport function addGasBuffer(\n estimatedGas: string,\n blockGasLimit: string,\n multiplier: number,\n) {\n const estimatedGasBN = hexToBN(estimatedGas);\n\n const maxGasBN = fractionBN(\n hexToBN(blockGasLimit),\n MAX_GAS_BLOCK_PERCENT,\n 100,\n );\n\n const paddedGasBN = fractionBN(estimatedGasBN, multiplier * 100, 100);\n\n if (estimatedGasBN.gt(maxGasBN)) {\n const estimatedGasHex = add0x(estimatedGas);\n log('Using estimated value', estimatedGasHex);\n return estimatedGasHex;\n }\n\n if (paddedGasBN.lt(maxGasBN)) {\n const paddedHex = add0x(BNToHex(paddedGasBN));\n log('Using padded estimate', paddedHex, multiplier);\n return paddedHex;\n }\n\n const maxHex = add0x(BNToHex(maxGasBN));\n log('Using 90% of block gas limit', maxHex);\n return maxHex;\n}\n\n/**\n * Simulate the required gas for a batch of transactions using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transactions.\n * @param options.from - The address of the sender.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transactions - The array of transactions within a batch request.\n * @returns An object containing the transactions with their gas limits and the total gas limit.\n */\nexport async function simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions,\n}: {\n chainId: Hex;\n from: Hex;\n getSimulationConfig: GetSimulationConfig;\n transactions: TransactionBatchSingleRequest[];\n}): Promise<{ gasLimit: Hex }> {\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: transactions.map((transaction) => ({\n ...transaction.params,\n from,\n })),\n });\n\n if (\n !response?.transactions ||\n response.transactions.length !== transactions.length\n ) {\n throw new Error('Simulation response does not match transaction count');\n }\n\n const totalGasLimit = response.transactions.reduce((acc, transaction) => {\n const gasLimit = transaction?.gasLimit;\n\n if (!gasLimit) {\n throw new Error(\n 'No simulated gas returned for one of the transactions',\n );\n }\n\n return acc.add(hexToBN(gasLimit));\n }, new BN(0));\n\n return {\n gasLimit: BNToHex(totalGasLimit), // Return the total gas limit as a hex string\n };\n } catch (error: unknown) {\n log('Error while simulating gas batch', error);\n throw new Error(\n 'Cannot estimate transaction batch total gas as simulation failed',\n );\n }\n}\n\n/**\n * Determine the gas for the provided request.\n *\n * @param request - The request object including the necessary parameters.\n * @returns The final gas value and the estimate used.\n */\nasync function getGas(\n request: UpdateGasRequest,\n): Promise<[string, TransactionMeta['simulationFails']?, string?]> {\n const {\n chainId,\n isCustomNetwork,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txMeta,\n } = request;\n const { disableGasBuffer } = txMeta;\n\n if (txMeta.txParams.gas) {\n log('Using value from request', txMeta.txParams.gas);\n return [txMeta.txParams.gas, undefined, txMeta.txParams.gas];\n }\n\n if (await requiresFixedGas(request)) {\n log('Using fixed value', FIXED_GAS);\n return [FIXED_GAS, undefined, FIXED_GAS];\n }\n\n const {\n blockGasLimit,\n estimatedGas,\n isUpgradeWithDataToSelf,\n simulationFails,\n } = await estimateGas({\n chainId,\n ethQuery: request.ethQuery,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txParams: txMeta.txParams,\n });\n\n log('Original estimated gas', estimatedGas);\n\n if (simulationFails) {\n log('Using original fallback estimate as simulation failed');\n }\n\n if (disableGasBuffer) {\n log('Gas buffer disabled');\n }\n\n if (simulationFails || disableGasBuffer) {\n return [estimatedGas, simulationFails, estimatedGas];\n }\n\n const bufferMultiplier = getGasEstimateBuffer({\n chainId,\n isCustomRPC: isCustomNetwork,\n isUpgradeWithDataToSelf,\n messenger,\n });\n\n log('Buffer', bufferMultiplier);\n\n const bufferedGas = addGasBuffer(\n estimatedGas,\n blockGasLimit,\n bufferMultiplier,\n );\n\n log('Buffered gas', bufferedGas);\n\n return [bufferedGas, simulationFails, estimatedGas];\n}\n\n/**\n * Determine if the gas for the provided request should be fixed.\n *\n * @param options - The options object.\n * @param options.ethQuery - The EthQuery instance to interact with the network.\n * @param options.txMeta - The transaction meta object.\n * @param options.isCustomNetwork - Whether the network is a custom network.\n * @returns Whether the gas should be fixed.\n */\nasync function requiresFixedGas({\n ethQuery,\n txMeta,\n isCustomNetwork,\n}: UpdateGasRequest): Promise<boolean> {\n const {\n txParams: { to, data, type },\n } = txMeta;\n\n if (\n isCustomNetwork ||\n !to ||\n data ||\n type === TransactionEnvelopeType.setCode\n ) {\n return false;\n }\n\n const code = await getCode(ethQuery, to);\n\n return !code || code === '0x';\n}\n\n/**\n * Get the contract code for the provided address.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param address - The address to get the code for.\n * @returns The contract code.\n */\nasync function getCode(\n ethQuery: EthQuery,\n address: string,\n): Promise<string | undefined> {\n return await query(ethQuery, 'getCode', [address]);\n}\n\n/**\n * Get the latest block from the network.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @returns The latest block number.\n */\nasync function getLatestBlock(\n ethQuery: EthQuery,\n): Promise<{ gasLimit: string; number: string }> {\n return await query(ethQuery, 'getBlockByNumber', ['latest', false]);\n}\n\n/**\n * Estimate the gas for a type 4 transaction.\n *\n * @param txParams - The transaction parameters.\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param chainId - The chain ID of the transaction.\n * @param getSimulationConfig - The function to get the simulation configuration.\n * @returns The estimated gas.\n */\nasync function estimateGasUpgradeWithDataToSelf(\n txParams: TransactionParams,\n ethQuery: EthQuery,\n chainId: Hex,\n getSimulationConfig: GetSimulationConfig,\n) {\n const upgradeGas = await query(ethQuery, 'estimateGas', [\n {\n ...txParams,\n data: '0x',\n },\n ]);\n\n log('Upgrade only gas', upgradeGas);\n\n const delegationAddress = txParams.authorizationList?.[0].address as Hex;\n\n let executeGas: Hex | undefined;\n\n try {\n executeGas = await simulateGas({\n chainId,\n delegationAddress,\n getSimulationConfig,\n transaction: txParams,\n });\n } catch (error: unknown) {\n log('Error while simulating data portion of upgrade', error);\n }\n\n if (executeGas === undefined) {\n try {\n executeGas = await estimateGasNode(\n ethQuery,\n { ...txParams, authorizationList: undefined, type: undefined },\n delegationAddress,\n );\n } catch (error: unknown) {\n log('Error while estimating data portion of upgrade', error);\n throw error;\n }\n\n log('Success estimating data portion of upgrade', executeGas);\n }\n\n log('Execute gas', executeGas);\n\n const total = BNToHex(\n hexToBN(upgradeGas)\n .add(hexToBN(executeGas as Hex))\n .subn(INTRINSIC_GAS),\n );\n\n log('Total type 4 gas', total);\n\n return total;\n}\n\n/**\n * Simulate the required gas using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transaction.\n * @param options.delegationAddress - The delegation address of the sender to mock.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transaction - The transaction parameters.\n * @returns The simulated gas.\n */\nasync function simulateGas({\n chainId,\n delegationAddress,\n getSimulationConfig,\n transaction,\n}: {\n chainId: Hex;\n delegationAddress?: Hex;\n getSimulationConfig: GetSimulationConfig;\n transaction: TransactionParams;\n}): Promise<Hex> {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n to: transaction.to as Hex,\n from: transaction.from as Hex,\n data: transaction.data as Hex,\n value: transaction.value as Hex,\n },\n ],\n overrides: {\n [transaction.from]: {\n code:\n delegationAddress &&\n ((DELEGATION_PREFIX + remove0x(delegationAddress)) as Hex),\n },\n },\n });\n\n const gasLimit = response?.transactions?.[0].gasLimit;\n\n if (!gasLimit) {\n throw new Error('No simulated gas returned');\n }\n\n return gasLimit;\n}\n\n/**\n * Populate the authorization list with dummy values.\n *\n * @param authorizationList - The authorization list to prepare.\n * @param chainId - The chain ID to use.\n * @returns The authorization list with dummy values.\n */\nfunction normalizeAuthorizationList(\n authorizationList: TransactionParams['authorizationList'],\n chainId: Hex,\n) {\n return authorizationList?.map((authorization) => ({\n ...authorization,\n chainId: authorization.chainId ?? chainId,\n nonce: authorization.nonce ?? '0x1',\n r: authorization.r ?? DUMMY_AUTHORIZATION_SIGNATURE,\n s: authorization.s ?? DUMMY_AUTHORIZATION_SIGNATURE,\n yParity: authorization.yParity ?? '0x1',\n }));\n}\n\n/**\n * Estimate the gas for a transaction using the `eth_estimateGas` method.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param txParams - The transaction parameters.\n * @param delegationAddress - The delegation address of the sender to mock.\n * @returns The estimated gas as a hex string.\n */\nfunction estimateGasNode(\n ethQuery: EthQuery,\n txParams: TransactionParams,\n delegationAddress?: Hex,\n) {\n const { from } = txParams;\n const params = [txParams] as Json[];\n\n if (delegationAddress) {\n params.push('latest');\n\n params.push({\n [from]: {\n code: DELEGATION_PREFIX + remove0x(delegationAddress),\n },\n });\n }\n\n return query(ethQuery, 'estimateGas', params);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layer1-gas-fee-flow.cjs","sourceRoot":"","sources":["../../src/utils/layer1-gas-fee-flow.ts"],"names":[],"mappings":";;;AACA,
|
|
1
|
+
{"version":3,"file":"layer1-gas-fee-flow.cjs","sourceRoot":"","sources":["../../src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CACnB,CAAC;IAEF,IAAI,CAAC;QACH,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,gBAAgB,CAAC,YAAY,CAAC;YACxD,QAAQ;YACR,eAAe;SAChB,CAAC,CAAC;QACH,OAAO,SAAS,CAAC;IACnB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,+BAA+B,EAAE,eAAe,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;QAChE,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAhCD,gEAgCC","sourcesContent":["import type { Provider } from '@metamask/network-controller';\nimport { createModuleLogger } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { Layer1GasFeeFlow, TransactionMeta } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'layer-1-gas-fee-flow');\n\nexport type UpdateLayer1GasFeeRequest = {\n layer1GasFeeFlows: Layer1GasFeeFlow[];\n messenger: TransactionControllerMessenger;\n provider: Provider;\n transactionMeta: TransactionMeta;\n};\n\n/**\n * Updates the given transactionMeta with the layer 1 gas fee.\n *\n * @param request - The request to use when getting the layer 1 gas fee.\n * @param request.provider - Provider used to create a new underlying EthQuery instance\n * @param request.transactionMeta - The transaction to get the layer 1 gas fee for.\n * @param request.layer1GasFeeFlows - The layer 1 gas fee flows to search.\n */\nexport async function updateTransactionLayer1GasFee(\n request: UpdateLayer1GasFeeRequest,\n) {\n const layer1GasFee = await getTransactionLayer1GasFee(request);\n\n if (!layer1GasFee) {\n return;\n }\n\n const { transactionMeta } = request;\n\n transactionMeta.layer1GasFee = layer1GasFee;\n\n log('Updated layer 1 gas fee', layer1GasFee, transactionMeta.id);\n}\n\n/**\n * Get the layer 1 gas fee flow for a transaction.\n *\n * @param transactionMeta - The transaction to get the layer 1 gas fee flow for.\n * @param layer1GasFeeFlows - The layer 1 gas fee flows to search.\n * @param messenger - The messenger instance.\n * @returns The layer 1 gas fee flow for the transaction, or undefined if none match.\n */\nasync function getLayer1GasFeeFlow(\n transactionMeta: TransactionMeta,\n layer1GasFeeFlows: Layer1GasFeeFlow[],\n messenger: TransactionControllerMessenger,\n): Promise<Layer1GasFeeFlow | undefined> {\n for (const layer1GasFeeFlow of layer1GasFeeFlows) {\n const matches = await layer1GasFeeFlow.matchesTransaction({\n transactionMeta,\n messenger,\n });\n\n if (matches) {\n return layer1GasFeeFlow;\n }\n }\n\n return undefined;\n}\n\n/**\n * Get the layer 1 gas fee for a transaction.\n *\n * @param request - The request to use when getting the layer 1 gas fee.\n * @param request.layer1GasFeeFlows - The layer 1 gas fee flows to search.\n * @param request.provider - The provider to use to get the layer 1 gas fee.\n * @param request.transactionMeta - The transaction to get the layer 1 gas fee for.\n * @param request.messenger - The messenger instance.\n * @returns The layer 1 gas fee.\n */\nexport async function getTransactionLayer1GasFee({\n layer1GasFeeFlows,\n messenger,\n provider,\n transactionMeta,\n}: UpdateLayer1GasFeeRequest): Promise<Hex | undefined> {\n const layer1GasFeeFlow = await getLayer1GasFeeFlow(\n transactionMeta,\n layer1GasFeeFlows,\n messenger,\n );\n\n if (!layer1GasFeeFlow) {\n return undefined;\n }\n\n log(\n 'Found layer 1 gas fee flow',\n layer1GasFeeFlow.constructor.name,\n transactionMeta.id,\n );\n\n try {\n const { layer1Fee } = await layer1GasFeeFlow.getLayer1Fee({\n provider,\n transactionMeta,\n });\n return layer1Fee;\n } catch (error) {\n log('Failed to get layer 1 gas fee', transactionMeta.id, error);\n return undefined;\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Provider } from "@metamask/network-controller";
|
|
2
|
-
import {
|
|
2
|
+
import type { Hex } from "@metamask/utils";
|
|
3
3
|
import type { TransactionControllerMessenger } from "../TransactionController.cjs";
|
|
4
4
|
import type { Layer1GasFeeFlow, TransactionMeta } from "../types.cjs";
|
|
5
5
|
export type UpdateLayer1GasFeeRequest = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layer1-gas-fee-flow.d.cts","sourceRoot":"","sources":["../../src/utils/layer1-gas-fee-flow.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,qCAAqC;
|
|
1
|
+
{"version":3,"file":"layer1-gas-fee-flow.d.cts","sourceRoot":"","sources":["../../src/utils/layer1-gas-fee-flow.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,qCAAqC;AAE7D,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAC/E,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,qBAAiB;AAIlE,MAAM,MAAM,yBAAyB,GAAG;IACtC,iBAAiB,EAAE,gBAAgB,EAAE,CAAC;IACtC,SAAS,EAAE,8BAA8B,CAAC;IAC1C,QAAQ,EAAE,QAAQ,CAAC;IACnB,eAAe,EAAE,eAAe,CAAC;CAClC,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,6BAA6B,CACjD,OAAO,EAAE,yBAAyB,iBAanC;AA6BD;;;;;;;;;GASG;AACH,wBAAsB,0BAA0B,CAAC,EAC/C,iBAAiB,EACjB,SAAS,EACT,QAAQ,EACR,eAAe,GAChB,EAAE,yBAAyB,GAAG,OAAO,CAAC,GAAG,GAAG,SAAS,CAAC,CA2BtD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Provider } from "@metamask/network-controller";
|
|
2
|
-
import {
|
|
2
|
+
import type { Hex } from "@metamask/utils";
|
|
3
3
|
import type { TransactionControllerMessenger } from "../TransactionController.mjs";
|
|
4
4
|
import type { Layer1GasFeeFlow, TransactionMeta } from "../types.mjs";
|
|
5
5
|
export type UpdateLayer1GasFeeRequest = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layer1-gas-fee-flow.d.mts","sourceRoot":"","sources":["../../src/utils/layer1-gas-fee-flow.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,qCAAqC;
|
|
1
|
+
{"version":3,"file":"layer1-gas-fee-flow.d.mts","sourceRoot":"","sources":["../../src/utils/layer1-gas-fee-flow.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,qCAAqC;AAE7D,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAC/E,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,qBAAiB;AAIlE,MAAM,MAAM,yBAAyB,GAAG;IACtC,iBAAiB,EAAE,gBAAgB,EAAE,CAAC;IACtC,SAAS,EAAE,8BAA8B,CAAC;IAC1C,QAAQ,EAAE,QAAQ,CAAC;IACnB,eAAe,EAAE,eAAe,CAAC;CAClC,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,6BAA6B,CACjD,OAAO,EAAE,yBAAyB,iBAanC;AA6BD;;;;;;;;;GASG;AACH,wBAAsB,0BAA0B,CAAC,EAC/C,iBAAiB,EACjB,SAAS,EACT,QAAQ,EACR,eAAe,GAChB,EAAE,yBAAyB,GAAG,OAAO,CAAC,GAAG,GAAG,SAAS,CAAC,CA2BtD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layer1-gas-fee-flow.mjs","sourceRoot":"","sources":["../../src/utils/layer1-gas-fee-flow.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,
|
|
1
|
+
{"version":3,"file":"layer1-gas-fee-flow.mjs","sourceRoot":"","sources":["../../src/utils/layer1-gas-fee-flow.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAGrD,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAI1C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,sBAAsB,CAAC,CAAC;AAStE;;;;;;;GA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S,CAAC;IACnB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,+BAA+B,EAAE,eAAe,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;QAChE,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["import type { Provider } from '@metamask/network-controller';\nimport { createModuleLogger } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { Layer1GasFeeFlow, TransactionMeta } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'layer-1-gas-fee-flow');\n\nexport type UpdateLayer1GasFeeRequest = {\n layer1GasFeeFlows: Layer1GasFeeFlow[];\n messenger: TransactionControllerMessenger;\n provider: Provider;\n transactionMeta: TransactionMeta;\n};\n\n/**\n * Updates the given transactionMeta with the layer 1 gas fee.\n *\n * @param request - The request to use when getting the layer 1 gas fee.\n * @param request.provider - Provider used to create a new underlying EthQuery instance\n * @param request.transactionMeta - The transaction to get the layer 1 gas fee for.\n * @param request.layer1GasFeeFlows - The layer 1 gas fee flows to search.\n */\nexport async function updateTransactionLayer1GasFee(\n request: UpdateLayer1GasFeeRequest,\n) {\n const layer1GasFee = await getTransactionLayer1GasFee(request);\n\n if (!layer1GasFee) {\n return;\n }\n\n const { transactionMeta } = request;\n\n transactionMeta.layer1GasFee = layer1GasFee;\n\n log('Updated layer 1 gas fee', layer1GasFee, transactionMeta.id);\n}\n\n/**\n * Get the layer 1 gas fee flow for a transaction.\n *\n * @param transactionMeta - The transaction to get the layer 1 gas fee flow for.\n * @param layer1GasFeeFlows - The layer 1 gas fee flows to search.\n * @param messenger - The messenger instance.\n * @returns The layer 1 gas fee flow for the transaction, or undefined if none match.\n */\nasync function getLayer1GasFeeFlow(\n transactionMeta: TransactionMeta,\n layer1GasFeeFlows: Layer1GasFeeFlow[],\n messenger: TransactionControllerMessenger,\n): Promise<Layer1GasFeeFlow | undefined> {\n for (const layer1GasFeeFlow of layer1GasFeeFlows) {\n const matches = await layer1GasFeeFlow.matchesTransaction({\n transactionMeta,\n messenger,\n });\n\n if (matches) {\n return layer1GasFeeFlow;\n }\n }\n\n return undefined;\n}\n\n/**\n * Get the layer 1 gas fee for a transaction.\n *\n * @param request - The request to use when getting the layer 1 gas fee.\n * @param request.layer1GasFeeFlows - The layer 1 gas fee flows to search.\n * @param request.provider - The provider to use to get the layer 1 gas fee.\n * @param request.transactionMeta - The transaction to get the layer 1 gas fee for.\n * @param request.messenger - The messenger instance.\n * @returns The layer 1 gas fee.\n */\nexport async function getTransactionLayer1GasFee({\n layer1GasFeeFlows,\n messenger,\n provider,\n transactionMeta,\n}: UpdateLayer1GasFeeRequest): Promise<Hex | undefined> {\n const layer1GasFeeFlow = await getLayer1GasFeeFlow(\n transactionMeta,\n layer1GasFeeFlows,\n messenger,\n );\n\n if (!layer1GasFeeFlow) {\n return undefined;\n }\n\n log(\n 'Found layer 1 gas fee flow',\n layer1GasFeeFlow.constructor.name,\n transactionMeta.id,\n );\n\n try {\n const { layer1Fee } = await layer1GasFeeFlow.getLayer1Fee({\n provider,\n transactionMeta,\n });\n return layer1Fee;\n } catch (error) {\n log('Failed to get layer 1 gas fee', transactionMeta.id, error);\n return undefined;\n }\n}\n"]}
|
package/dist/utils/retry.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.cjs","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":";;;AAAA,iEAAiE;AAEjE,2CAAwC;
|
|
1
|
+
{"version":3,"file":"retry.cjs","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":";;;AAAA,iEAAiE;AAEjE,2CAAwC;AAQxC;;;;;;;GAOG;AACH,SAAgB,uCAAuC,CACrD,yBAA4C,EAC5C,IAAY,EACZ,YAAqD;IAErD,MAAM,WAAW,GAAG,oBAAoB,CACtC,yBAAyB,EACzB,IAAI,EACJ,YAAY,CACb,CAAC;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;;GAOG;AACH,SAAS,oBAAoB,CAC3B,yBAA4C,EAC5C,IAAY,EACZ,YAAqD;IAErD,IAAI,YAAY,IAAI,UAAU,IAAI,YAAY,EAAE,CAAC;QAC/C,OAAO,YAAY,CAAC,QAAe,CAAC;IACtC,CAAC;IAED,MAAM,eAAe,GAAG,yBAAyB,CAAC,QAA2B,CAAC;IAE9E,IAAI,CAAC,eAAe,IAAI,eAAe,KAAK,KAAK,EAAE,CAAC;QAClD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,WAAW,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;AAC5C,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAAC,KAAsB,EAAE,UAAkB;IAC7D,MAAM,YAAY,GAAG,IAAA,sCAAmB,EAAC,KAAK,CAAC,CAAC;IAChD,MAAM,aAAa,GAAG,QAAQ,CAAC,GAAG,YAAY,GAAG,UAAU,EAAE,EAAE,EAAE,CAAC,CAAC;IAEnE,OAAO,IAAA,aAAK,EAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import { convertHexToDecimal } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { add0x } from '@metamask/utils';\n\nimport type {\n FeeMarketEIP1559Values,\n GasPriceValue,\n TransactionParams,\n} from '../types';\n\n/**\n * Returns new transaction parameters with increased gas fees.\n *\n * @param originalTransactionParams - The original transaction parameters.\n * @param rate - The rate by which to increase the existing gas fee properties.\n * @param newGasValues - Optional new gas values to use instead of increased the existing values.\n * @returns The new transaction parameters with the increased gas fee properties.\n */\nexport function getTransactionParamsWithIncreasedGasFee(\n originalTransactionParams: TransactionParams,\n rate: number,\n newGasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): TransactionParams {\n const newGasPrice = getIncreasedGasPrice(\n originalTransactionParams,\n rate,\n newGasValues,\n );\n\n const new1559Values = getIncreased1559Values(\n originalTransactionParams,\n rate,\n newGasValues,\n );\n\n if (new1559Values) {\n const newTxParams: TransactionParams = {\n ...originalTransactionParams,\n ...new1559Values,\n };\n\n delete newTxParams.gasPrice;\n\n return newTxParams;\n }\n\n if (newGasPrice) {\n const newTxParams: TransactionParams = {\n ...originalTransactionParams,\n gasPrice: newGasPrice,\n };\n\n delete newTxParams.maxFeePerGas;\n delete newTxParams.maxPriorityFeePerGas;\n\n return newTxParams;\n }\n\n throw new Error(\n 'Cannot increase gas fee as no current values and no new values were provided',\n );\n}\n\n/**\n * Generate the increased EIP-1559 gas properties.\n *\n * @param originalTransactionParams - The original transaction parameters.\n * @param rate - The rate by which to increase the existing gas fee properties.\n * @param newGasValues - Optional new gas values to use instead of increased the existing values.\n * @returns The new EIP-1559 gas properties.\n */\nfunction getIncreased1559Values(\n originalTransactionParams: TransactionParams,\n rate: number,\n newGasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): FeeMarketEIP1559Values | undefined {\n if (\n newGasValues &&\n 'maxFeePerGas' in newGasValues &&\n 'maxPriorityFeePerGas' in newGasValues\n ) {\n return newGasValues;\n }\n\n const currentMaxFeePerGas = originalTransactionParams.maxFeePerGas as\n | Hex\n | undefined;\n\n const currentMaxPriorityFeePerGas =\n originalTransactionParams.maxPriorityFeePerGas as Hex | undefined;\n\n if (\n !currentMaxFeePerGas ||\n !currentMaxPriorityFeePerGas ||\n currentMaxFeePerGas === '0x0' ||\n currentMaxPriorityFeePerGas === '0x0'\n ) {\n return undefined;\n }\n\n const maxFeePerGas = multiplyHex(currentMaxFeePerGas, rate);\n const maxPriorityFeePerGas = multiplyHex(currentMaxPriorityFeePerGas, rate);\n\n return { maxFeePerGas, maxPriorityFeePerGas };\n}\n\n/**\n * Generate the increased gas price.\n *\n * @param originalTransactionParams - The original transaction parameters.\n * @param rate - The rate by which to increase the existing gas fee properties.\n * @param newGasValues - Optional new gas values to use instead of increased the existing values.\n * @returns The new gas price.\n */\nfunction getIncreasedGasPrice(\n originalTransactionParams: TransactionParams,\n rate: number,\n newGasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): Hex | undefined {\n if (newGasValues && 'gasPrice' in newGasValues) {\n return newGasValues.gasPrice as Hex;\n }\n\n const currentGasPrice = originalTransactionParams.gasPrice as Hex | undefined;\n\n if (!currentGasPrice || currentGasPrice === '0x0') {\n return undefined;\n }\n\n return multiplyHex(currentGasPrice, rate);\n}\n\n/**\n * Multiply a hex value by a multiplier.\n *\n * @param value - The hex value to multiply.\n * @param multiplier - The multiplier.\n * @returns The multiplied hex value.\n */\nfunction multiplyHex(value: Hex | undefined, multiplier: number): Hex {\n const decimalValue = convertHexToDecimal(value);\n const decimalResult = parseInt(`${decimalValue * multiplier}`, 10);\n\n return add0x(decimalResult.toString(16));\n}\n"]}
|
package/dist/utils/retry.d.cts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type { FeeMarketEIP1559Values, GasPriceValue } from "../types.cjs";
|
|
2
|
-
import { type TransactionParams } from "../types.cjs";
|
|
1
|
+
import type { FeeMarketEIP1559Values, GasPriceValue, TransactionParams } from "../types.cjs";
|
|
3
2
|
/**
|
|
4
3
|
* Returns new transaction parameters with increased gas fees.
|
|
5
4
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.d.cts","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"retry.d.cts","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,sBAAsB,EACtB,aAAa,EACb,iBAAiB,EAClB,qBAAiB;AAElB;;;;;;;GAOG;AACH,wBAAgB,uCAAuC,CACrD,yBAAyB,EAAE,iBAAiB,EAC5C,IAAI,EAAE,MAAM,EACZ,YAAY,CAAC,EAAE,aAAa,GAAG,sBAAsB,GACpD,iBAAiB,CAuCnB"}
|
package/dist/utils/retry.d.mts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type { FeeMarketEIP1559Values, GasPriceValue } from "../types.mjs";
|
|
2
|
-
import { type TransactionParams } from "../types.mjs";
|
|
1
|
+
import type { FeeMarketEIP1559Values, GasPriceValue, TransactionParams } from "../types.mjs";
|
|
3
2
|
/**
|
|
4
3
|
* Returns new transaction parameters with increased gas fees.
|
|
5
4
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.d.mts","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"retry.d.mts","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,sBAAsB,EACtB,aAAa,EACb,iBAAiB,EAClB,qBAAiB;AAElB;;;;;;;GAOG;AACH,wBAAgB,uCAAuC,CACrD,yBAAyB,EAAE,iBAAiB,EAC5C,IAAI,EAAE,MAAM,EACZ,YAAY,CAAC,EAAE,aAAa,GAAG,sBAAsB,GACpD,iBAAiB,CAuCnB"}
|
package/dist/utils/retry.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.mjs","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,mCAAmC;AAEjE,OAAO,EAAE,KAAK,EAAE,wBAAwB;
|
|
1
|
+
{"version":3,"file":"retry.mjs","sourceRoot":"","sources":["../../src/utils/retry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,mCAAmC;AAEjE,OAAO,EAAE,KAAK,EAAE,wBAAwB;AAQxC;;;;;;;GAOG;AACH,MAAM,UAAU,uCAAuC,CACrD,yBAA4C,EAC5C,IAAY,EACZ,YAAqD;IAErD,MAAM,WAAW,GAAG,oBAAoB,CACtC,yBAAyB,EACzB,IAAI,EACJ,YAAY,CACb,CAAC;IAEF,MAAM,aAAa,GAAG,sBAAsB,CAC1C,yBAAyB,EACzB,IA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ErD,IAAI,YAAY,IAAI,UAAU,IAAI,YAAY,EAAE,CAAC;QAC/C,OAAO,YAAY,CAAC,QAAe,CAAC;IACtC,CAAC;IAED,MAAM,eAAe,GAAG,yBAAyB,CAAC,QAA2B,CAAC;IAE9E,IAAI,CAAC,eAAe,IAAI,eAAe,KAAK,KAAK,EAAE,CAAC;QAClD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,WAAW,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;AAC5C,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAAC,KAAsB,EAAE,UAAkB;IAC7D,MAAM,YAAY,GAAG,mBAAmB,CAAC,KAAK,CAAC,CAAC;IAChD,MAAM,aAAa,GAAG,QAAQ,CAAC,GAAG,YAAY,GAAG,UAAU,EAAE,EAAE,EAAE,CAAC,CAAC;IAEnE,OAAO,KAAK,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import { convertHexToDecimal } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { add0x } from '@metamask/utils';\n\nimport type {\n FeeMarketEIP1559Values,\n GasPriceValue,\n TransactionParams,\n} from '../types';\n\n/**\n * Returns new transaction parameters with increased gas fees.\n *\n * @param originalTransactionParams - The original transaction parameters.\n * @param rate - The rate by which to increase the existing gas fee properties.\n * @param newGasValues - Optional new gas values to use instead of increased the existing values.\n * @returns The new transaction parameters with the increased gas fee properties.\n */\nexport function getTransactionParamsWithIncreasedGasFee(\n originalTransactionParams: TransactionParams,\n rate: number,\n newGasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): TransactionParams {\n const newGasPrice = getIncreasedGasPrice(\n originalTransactionParams,\n rate,\n newGasValues,\n );\n\n const new1559Values = getIncreased1559Values(\n originalTransactionParams,\n rate,\n newGasValues,\n );\n\n if (new1559Values) {\n const newTxParams: TransactionParams = {\n ...originalTransactionParams,\n ...new1559Values,\n };\n\n delete newTxParams.gasPrice;\n\n return newTxParams;\n }\n\n if (newGasPrice) {\n const newTxParams: TransactionParams = {\n ...originalTransactionParams,\n gasPrice: newGasPrice,\n };\n\n delete newTxParams.maxFeePerGas;\n delete newTxParams.maxPriorityFeePerGas;\n\n return newTxParams;\n }\n\n throw new Error(\n 'Cannot increase gas fee as no current values and no new values were provided',\n );\n}\n\n/**\n * Generate the increased EIP-1559 gas properties.\n *\n * @param originalTransactionParams - The original transaction parameters.\n * @param rate - The rate by which to increase the existing gas fee properties.\n * @param newGasValues - Optional new gas values to use instead of increased the existing values.\n * @returns The new EIP-1559 gas properties.\n */\nfunction getIncreased1559Values(\n originalTransactionParams: TransactionParams,\n rate: number,\n newGasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): FeeMarketEIP1559Values | undefined {\n if (\n newGasValues &&\n 'maxFeePerGas' in newGasValues &&\n 'maxPriorityFeePerGas' in newGasValues\n ) {\n return newGasValues;\n }\n\n const currentMaxFeePerGas = originalTransactionParams.maxFeePerGas as\n | Hex\n | undefined;\n\n const currentMaxPriorityFeePerGas =\n originalTransactionParams.maxPriorityFeePerGas as Hex | undefined;\n\n if (\n !currentMaxFeePerGas ||\n !currentMaxPriorityFeePerGas ||\n currentMaxFeePerGas === '0x0' ||\n currentMaxPriorityFeePerGas === '0x0'\n ) {\n return undefined;\n }\n\n const maxFeePerGas = multiplyHex(currentMaxFeePerGas, rate);\n const maxPriorityFeePerGas = multiplyHex(currentMaxPriorityFeePerGas, rate);\n\n return { maxFeePerGas, maxPriorityFeePerGas };\n}\n\n/**\n * Generate the increased gas price.\n *\n * @param originalTransactionParams - The original transaction parameters.\n * @param rate - The rate by which to increase the existing gas fee properties.\n * @param newGasValues - Optional new gas values to use instead of increased the existing values.\n * @returns The new gas price.\n */\nfunction getIncreasedGasPrice(\n originalTransactionParams: TransactionParams,\n rate: number,\n newGasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): Hex | undefined {\n if (newGasValues && 'gasPrice' in newGasValues) {\n return newGasValues.gasPrice as Hex;\n }\n\n const currentGasPrice = originalTransactionParams.gasPrice as Hex | undefined;\n\n if (!currentGasPrice || currentGasPrice === '0x0') {\n return undefined;\n }\n\n return multiplyHex(currentGasPrice, rate);\n}\n\n/**\n * Multiply a hex value by a multiplier.\n *\n * @param value - The hex value to multiply.\n * @param multiplier - The multiplier.\n * @returns The multiplied hex value.\n */\nfunction multiplyHex(value: Hex | undefined, multiplier: number): Hex {\n const decimalValue = convertHexToDecimal(value);\n const decimalResult = parseInt(`${decimalValue * multiplier}`, 10);\n\n return add0x(decimalResult.toString(16));\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction-type.cjs","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":";;;AAAA,
|
|
1
|
+
{"version":3,"file":"transaction-type.cjs","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":";;;AAAA,4CAA+C;AAE/C,iEAAmD;AAEnD,mEAKqC;AAErC,2CAA8C;AAE9C,wCAA2C;AAE9B,QAAA,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,MAAM,cAAc,GAAG,IAAI,eAAS,CAAC,4BAAQ,CAAC,CAAC;AAC/C,MAAM,eAAe,GAAG,IAAI,eAAS,CAAC,6BAAS,CAAC,CAAC;AACjD,MAAM,gBAAgB,GAAG,IAAI,eAAS,CAAC,8BAAU,CAAC,CAAC;AACnD,MAAM,aAAa,GAAG,IAAI,eAAS,CAAC,kCAAc,CAAC,CAAC;AAEpD;;;;;;;;GAQG;AACI,KAAK,UAAU,wBAAwB,CAC5C,QAA2B,EAC3B,QAAmB;IAEnB,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,QAAQ,CAAC;IAE9B,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC;QAChB,OAAO,EAAE,IAAI,EAAE,uBAAe,CAAC,cAAc,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;IAC9E,CAAC;I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AG,YAAY;QACpC,CAAC,CAAC,YAAY,KAAK,IAAI;YACrB,YAAY,KAAK,KAAK;YACtB,CAAC,YAAY,CAAC,UAAU,CAAC,2BAAiB,CAAC;QAC7C,CAAC,CAAC,KAAK,CAAC;IACV,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAC7C,CAAC","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport type { TransactionDescription } from '@ethersproject/abi';\nimport { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport {\n abiERC721,\n abiERC20,\n abiERC1155,\n abiFiatTokenV2,\n} from '@metamask/metamask-eth-abis';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport type { InferTransactionTypeResult, TransactionParams } from '../types';\nimport { TransactionType } from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\nconst ERC20Interface = new Interface(abiERC20);\nconst ERC721Interface = new Interface(abiERC721);\nconst ERC1155Interface = new Interface(abiERC1155);\nconst USDCInterface = new Interface(abiFiatTokenV2);\n\n/**\n * Determines the type of the transaction by analyzing the txParams.\n * It will never return TRANSACTION_TYPE_CANCEL or TRANSACTION_TYPE_RETRY as these\n * represent specific events that we specify manually at transaction creation.\n *\n * @param txParams - Parameters for the transaction.\n * @param ethQuery - EthQuery instance.\n * @returns A object with the transaction type and the contract code response in Hex.\n */\nexport async function determineTransactionType(\n txParams: TransactionParams,\n ethQuery?: EthQuery,\n): Promise<InferTransactionTypeResult> {\n const { data, to } = txParams;\n\n if (data && !to) {\n return { type: TransactionType.deployContract, getCodeResponse: undefined };\n }\n\n let getCodeResponse;\n let isContractAddress = Boolean(data?.length);\n\n if (ethQuery) {\n const response = await readAddressAsContract(ethQuery, to);\n\n getCodeResponse = response.contractCode;\n isContractAddress = response.isContractAddress;\n }\n\n if (!isContractAddress) {\n return { type: TransactionType.simpleSend, getCodeResponse };\n }\n\n const hasValue = Number(txParams.value ?? '0') !== 0;\n\n const contractInteractionResult = {\n type: TransactionType.contractInteraction,\n getCodeResponse,\n };\n\n if (!data || hasValue) {\n return contractInteractionResult;\n }\n\n const name = getMethodName(data);\n\n if (!name) {\n return contractInteractionResult;\n }\n\n const tokenMethodName = [\n TransactionType.tokenMethodApprove,\n TransactionType.tokenMethodSetApprovalForAll,\n TransactionType.tokenMethodTransfer,\n TransactionType.tokenMethodTransferFrom,\n TransactionType.tokenMethodSafeTransferFrom,\n TransactionType.tokenMethodIncreaseAllowance,\n ].find((methodName) => methodName.toLowerCase() === name.toLowerCase());\n\n if (tokenMethodName) {\n return { type: tokenMethodName, getCodeResponse };\n }\n\n return contractInteractionResult;\n}\n\n/**\n * Parses transaction data using ABIs for three different token standards: ERC20, ERC721, ERC1155 and USDC.\n * The data will decode correctly if the transaction is an interaction with a contract that matches one of these\n * contract standards\n *\n * @param data - Encoded transaction data.\n * @param options - Options bag.\n * @param options.getMethodName - Whether to get the method name.\n * @returns A representation of an ethereum contract call.\n */\nexport function decodeTransactionData(\n data: string,\n options?: {\n getMethodName?: boolean;\n },\n): undefined | TransactionDescription | string {\n if (!data || data.length < 10) {\n return undefined;\n }\n\n const fourByte = data.substring(0, 10).toLowerCase();\n\n for (const iface of [\n ERC20Interface,\n ERC721Interface,\n ERC1155Interface,\n USDCInterface,\n ]) {\n try {\n if (options?.getMethodName) {\n return iface.getFunction(fourByte)?.name;\n }\n return iface.parseTransaction({ data });\n } catch {\n // Intentionally empty\n }\n }\n\n return undefined;\n}\n\n/**\n * Attempts to get the method name from the given transaction data.\n *\n * @param data - Encoded transaction data.\n * @returns The method name.\n */\nfunction getMethodName(data?: string): string | undefined {\n return decodeTransactionData(data as string, {\n getMethodName: true,\n }) as string | undefined;\n}\n\n/**\n * Reads an Ethereum address and determines if it is a contract address.\n *\n * @param ethQuery - The Ethereum query object used to interact with the Ethereum blockchain.\n * @param address - The Ethereum address.\n * @returns An object containing the contract code and a boolean indicating if it is a contract address.\n */\nasync function readAddressAsContract(\n ethQuery: EthQuery,\n address?: string,\n): Promise<{\n contractCode: string | null;\n isContractAddress: boolean;\n}> {\n let contractCode;\n try {\n contractCode = await query(ethQuery, 'getCode', [address]);\n // Not used\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (error) {\n contractCode = null;\n }\n\n const isContractAddress = contractCode\n ? contractCode !== '0x' &&\n contractCode !== '0x0' &&\n !contractCode.startsWith(DELEGATION_PREFIX)\n : false;\n return { contractCode, isContractAddress };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { TransactionDescription } from "@ethersproject/abi";
|
|
2
2
|
import type EthQuery from "@metamask/eth-query";
|
|
3
3
|
import type { InferTransactionTypeResult, TransactionParams } from "../types.cjs";
|
|
4
4
|
export declare const ESTIMATE_GAS_ERROR = "eth_estimateGas rpc method error";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction-type.d.cts","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"transaction-type.d.cts","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,2BAA2B;AAEjE,OAAO,KAAK,QAAQ,4BAA4B;AAShD,OAAO,KAAK,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,qBAAiB;AAG9E,eAAO,MAAM,kBAAkB,qCAAqC,CAAC;AAOrE;;;;;;;;GAQG;AACH,wBAAsB,wBAAwB,CAC5C,QAAQ,EAAE,iBAAiB,EAC3B,QAAQ,CAAC,EAAE,QAAQ,GAClB,OAAO,CAAC,0BAA0B,CAAC,CAoDrC;AAED;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE;IACR,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB,GACA,SAAS,GAAG,sBAAsB,GAAG,MAAM,CAwB7C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { TransactionDescription } from "@ethersproject/abi";
|
|
2
2
|
import type EthQuery from "@metamask/eth-query";
|
|
3
3
|
import type { InferTransactionTypeResult, TransactionParams } from "../types.mjs";
|
|
4
4
|
export declare const ESTIMATE_GAS_ERROR = "eth_estimateGas rpc method error";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction-type.d.mts","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"transaction-type.d.mts","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,2BAA2B;AAEjE,OAAO,KAAK,QAAQ,4BAA4B;AAShD,OAAO,KAAK,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,qBAAiB;AAG9E,eAAO,MAAM,kBAAkB,qCAAqC,CAAC;AAOrE;;;;;;;;GAQG;AACH,wBAAsB,wBAAwB,CAC5C,QAAQ,EAAE,iBAAiB,EAC3B,QAAQ,CAAC,EAAE,QAAQ,GAClB,OAAO,CAAC,0BAA0B,CAAC,CAoDrC;AAED;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE;IACR,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB,GACA,SAAS,GAAG,sBAAsB,GAAG,MAAM,CAwB7C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction-type.mjs","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,
|
|
1
|
+
{"version":3,"file":"transaction-type.mjs","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,2BAA2B;AAE/C,OAAO,EAAE,KAAK,EAAE,mCAAmC;AAEnD,OAAO,EACL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QAAQ,CAAC,EAAE,IAAI,CAAC;YAC3C,CAAC;YACD,OAAO,KAAK,CAAC,gBAAgB,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1C,CAAC;QAAC,MAAM,CAAC;YACP,sBAAsB;QACxB,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;GAKG;AACH,SAAS,aAAa,CAAC,IAAa;IAClC,OAAO,qBAAqB,CAAC,IAAc,EAAE;QAC3C,aAAa,EAAE,IAAI;KACpB,CAAuB,CAAC;AAC3B,CAAC;AAED;;;;;;GAMG;AACH,KAAK,UAAU,qBAAqB,CAClC,QAAkB,EAClB,OAAgB;IAKhB,IAAI,YAAY,CAAC;IACjB,IAAI,CAAC;QACH,YAAY,GAAG,MAAM,KAAK,CAAC,QAAQ,EAAE,SAAS,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;QAC3D,WAAW;QACX,6DAA6D;IAC/D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,YAAY,GAAG,IAAI,CAAC;IACtB,CAAC;IAED,MAAM,iBAAiB,GAAG,YAAY;QACpC,CAAC,CAAC,YAAY,KAAK,IAAI;YACrB,YAAY,KAAK,KAAK;YACtB,CAAC,YAAY,CAAC,UAAU,CAAC,iBAAiB,CAAC;QAC7C,CAAC,CAAC,KAAK,CAAC;IACV,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAC7C,CAAC","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport type { TransactionDescription } from '@ethersproject/abi';\nimport { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport {\n abiERC721,\n abiERC20,\n abiERC1155,\n abiFiatTokenV2,\n} from '@metamask/metamask-eth-abis';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport type { InferTransactionTypeResult, TransactionParams } from '../types';\nimport { TransactionType } from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\nconst ERC20Interface = new Interface(abiERC20);\nconst ERC721Interface = new Interface(abiERC721);\nconst ERC1155Interface = new Interface(abiERC1155);\nconst USDCInterface = new Interface(abiFiatTokenV2);\n\n/**\n * Determines the type of the transaction by analyzing the txParams.\n * It will never return TRANSACTION_TYPE_CANCEL or TRANSACTION_TYPE_RETRY as these\n * represent specific events that we specify manually at transaction creation.\n *\n * @param txParams - Parameters for the transaction.\n * @param ethQuery - EthQuery instance.\n * @returns A object with the transaction type and the contract code response in Hex.\n */\nexport async function determineTransactionType(\n txParams: TransactionParams,\n ethQuery?: EthQuery,\n): Promise<InferTransactionTypeResult> {\n const { data, to } = txParams;\n\n if (data && !to) {\n return { type: TransactionType.deployContract, getCodeResponse: undefined };\n }\n\n let getCodeResponse;\n let isContractAddress = Boolean(data?.length);\n\n if (ethQuery) {\n const response = await readAddressAsContract(ethQuery, to);\n\n getCodeResponse = response.contractCode;\n isContractAddress = response.isContractAddress;\n }\n\n if (!isContractAddress) {\n return { type: TransactionType.simpleSend, getCodeResponse };\n }\n\n const hasValue = Number(txParams.value ?? '0') !== 0;\n\n const contractInteractionResult = {\n type: TransactionType.contractInteraction,\n getCodeResponse,\n };\n\n if (!data || hasValue) {\n return contractInteractionResult;\n }\n\n const name = getMethodName(data);\n\n if (!name) {\n return contractInteractionResult;\n }\n\n const tokenMethodName = [\n TransactionType.tokenMethodApprove,\n TransactionType.tokenMethodSetApprovalForAll,\n TransactionType.tokenMethodTransfer,\n TransactionType.tokenMethodTransferFrom,\n TransactionType.tokenMethodSafeTransferFrom,\n TransactionType.tokenMethodIncreaseAllowance,\n ].find((methodName) => methodName.toLowerCase() === name.toLowerCase());\n\n if (tokenMethodName) {\n return { type: tokenMethodName, getCodeResponse };\n }\n\n return contractInteractionResult;\n}\n\n/**\n * Parses transaction data using ABIs for three different token standards: ERC20, ERC721, ERC1155 and USDC.\n * The data will decode correctly if the transaction is an interaction with a contract that matches one of these\n * contract standards\n *\n * @param data - Encoded transaction data.\n * @param options - Options bag.\n * @param options.getMethodName - Whether to get the method name.\n * @returns A representation of an ethereum contract call.\n */\nexport function decodeTransactionData(\n data: string,\n options?: {\n getMethodName?: boolean;\n },\n): undefined | TransactionDescription | string {\n if (!data || data.length < 10) {\n return undefined;\n }\n\n const fourByte = data.substring(0, 10).toLowerCase();\n\n for (const iface of [\n ERC20Interface,\n ERC721Interface,\n ERC1155Interface,\n USDCInterface,\n ]) {\n try {\n if (options?.getMethodName) {\n return iface.getFunction(fourByte)?.name;\n }\n return iface.parseTransaction({ data });\n } catch {\n // Intentionally empty\n }\n }\n\n return undefined;\n}\n\n/**\n * Attempts to get the method name from the given transaction data.\n *\n * @param data - Encoded transaction data.\n * @returns The method name.\n */\nfunction getMethodName(data?: string): string | undefined {\n return decodeTransactionData(data as string, {\n getMethodName: true,\n }) as string | undefined;\n}\n\n/**\n * Reads an Ethereum address and determines if it is a contract address.\n *\n * @param ethQuery - The Ethereum query object used to interact with the Ethereum blockchain.\n * @param address - The Ethereum address.\n * @returns An object containing the contract code and a boolean indicating if it is a contract address.\n */\nasync function readAddressAsContract(\n ethQuery: EthQuery,\n address?: string,\n): Promise<{\n contractCode: string | null;\n isContractAddress: boolean;\n}> {\n let contractCode;\n try {\n contractCode = await query(ethQuery, 'getCode', [address]);\n // Not used\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (error) {\n contractCode = null;\n }\n\n const isContractAddress = contractCode\n ? contractCode !== '0x' &&\n contractCode !== '0x0' &&\n !contractCode.startsWith(DELEGATION_PREFIX)\n : false;\n return { contractCode, isContractAddress };\n}\n"]}
|
package/dist/utils/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AAEA,2CAIyB;AACzB,kDAAuB;AASvB,wCAAsE;AAEzD,QAAA,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,gCAAgC;AAChC,8DAA8D;AAC9D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0CAaC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport type { Hex, Json } from '@metamask/utils';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport type {\n FeeMarketEIP1559Values,\n GasPriceValue,\n TransactionError,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport { TransactionEnvelopeType, TransactionStatus } 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 accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\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 if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\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 `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\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 `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\n/**\n * Create a BN from a hex string, accepting an optional 0x prefix.\n *\n * @param hex - Hex string with or without 0x prefix.\n * @returns BN parsed as base-16.\n */\nexport function bnFromHex(hex: string | Hex): BN {\n const str = typeof hex === 'string' ? hex : (hex as string);\n const withoutPrefix =\n str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;\n if (withoutPrefix.length === 0) {\n return new BN(0);\n }\n return new BN(withoutPrefix, 16);\n}\n\n/**\n * Convert various numeric-like values to a BN instance.\n * Accepts BN, ethers BigNumber, hex string, bigint, or number.\n *\n * @param value - The value to convert.\n * @returns BN representation of the input value.\n */\nexport function toBN(value: unknown): BN {\n if (value instanceof BN) {\n return value as BN;\n }\n if (\n typeof (BN as unknown as { isBN?: (v: unknown) => boolean }).isBN ===\n 'function' &&\n (BN as unknown as { isBN: (v: unknown) => boolean }).isBN(value)\n ) {\n return value as BN;\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { toHexString?: () => string }).toHexString === 'function'\n ) {\n return bnFromHex((value as { toHexString: () => string }).toHexString());\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { _hex?: string })._hex === 'string'\n ) {\n return bnFromHex((value as { _hex: string })._hex);\n }\n if (typeof value === 'string') {\n return bnFromHex(value);\n }\n if (typeof value === 'bigint') {\n return new BN(value.toString());\n }\n if (typeof value === 'number') {\n return new BN(value);\n }\n throw new Error('Unexpected value returned from oracle contract');\n}\n\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}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AG,+BAAuB,CAAC,OAAO,CAAC;IAClD,CAAC;SAAM,CAAC;QACN,QAAQ,CAAC,IAAI,GAAG,mBAAmB;YACjC,CAAC,CAAC,+BAAuB,CAAC,SAAS;YACnC,CAAC,CAAC,+BAAuB,CAAC,MAAM,CAAC;IACrC,CAAC;AACH,CAAC;AAbD,0CAaC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport type { Hex, Json } from '@metamask/utils';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport type {\n FeeMarketEIP1559Values,\n GasPriceValue,\n TransactionError,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport { TransactionEnvelopeType, TransactionStatus } 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 accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\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 if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\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 `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\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 `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\n/**\n * Create a BN from a hex string, accepting an optional 0x prefix.\n *\n * @param hex - Hex string with or without 0x prefix.\n * @returns BN parsed as base-16.\n */\nexport function bnFromHex(hex: string | Hex): BN {\n const str = typeof hex === 'string' ? hex : (hex as string);\n const withoutPrefix =\n str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;\n if (withoutPrefix.length === 0) {\n return new BN(0);\n }\n return new BN(withoutPrefix, 16);\n}\n\n/**\n * Convert various numeric-like values to a BN instance.\n * Accepts BN, ethers BigNumber, hex string, bigint, or number.\n *\n * @param value - The value to convert.\n * @returns BN representation of the input value.\n */\nexport function toBN(value: unknown): BN {\n if (value instanceof BN) {\n return value;\n }\n if (\n typeof (BN as unknown as { isBN?: (v: unknown) => boolean }).isBN ===\n 'function' &&\n (BN as unknown as { isBN: (v: unknown) => boolean }).isBN(value)\n ) {\n return value as BN;\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { toHexString?: () => string }).toHexString === 'function'\n ) {\n return bnFromHex((value as { toHexString: () => string }).toHexString());\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { _hex?: string })._hex === 'string'\n ) {\n return bnFromHex((value as { _hex: string })._hex);\n }\n if (typeof value === 'string') {\n return bnFromHex(value);\n }\n if (typeof value === 'bigint') {\n return new BN(value.toString());\n }\n if (typeof value === 'number') {\n return new BN(value);\n }\n throw new Error('Unexpected value returned from oracle contract');\n}\n\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}
|
package/dist/utils/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AAEA,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,iBAAiB,EAClB,wBAAwB;AACzB,OAAO,GAAE,cAAc;;AASvB,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,qBAAiB;AAEtE,MAAM,CAAC,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,gCAAgC;AAChC,8DAA8D;AAC9D,MAAM,WAAW,GAAgD;IAC/D,UAAU,EAAE,CAAC,UAAuB,EAAE,EAAE,CAAC,UAAU;IACnD,iBAAiB,EAAE,CAAC,iBAAqC,EAAE,EAAE,CAC3D,iBAAiB;IACnB,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE;IACjD,GAAG,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC;IAChC,QAAQ,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC;IACrC,QAAQ,EAAE,CAAC,QAAgB,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC;IAC/C,KAAK,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC;IACtC,EAAE,EAAE,CAAC,EAAU,EAAE,EAAE,CA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,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;QACxB,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,UAAU,CAAC;IACrD,CAAC;SAAM,IAAI,QAAQ,CAAC,iBAAiB,EAAE,CAAC;QACtC,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,OAAO,CAAC;IAClD,CAAC;SAAM,CAAC;QACN,QAAQ,CAAC,IAAI,GAAG,mBAAmB;YACjC,CAAC,CAAC,uBAAuB,CAAC,SAAS;YACnC,CAAC,CAAC,uBAAuB,CAAC,MAAM,CAAC;IACrC,CAAC;AACH,CAAC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport type { Hex, Json } from '@metamask/utils';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport type {\n FeeMarketEIP1559Values,\n GasPriceValue,\n TransactionError,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport { TransactionEnvelopeType, TransactionStatus } 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 accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\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 if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\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 `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\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 `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\n/**\n * Create a BN from a hex string, accepting an optional 0x prefix.\n *\n * @param hex - Hex string with or without 0x prefix.\n * @returns BN parsed as base-16.\n */\nexport function bnFromHex(hex: string | Hex): BN {\n const str = typeof hex === 'string' ? hex : (hex as string);\n const withoutPrefix =\n str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;\n if (withoutPrefix.length === 0) {\n return new BN(0);\n }\n return new BN(withoutPrefix, 16);\n}\n\n/**\n * Convert various numeric-like values to a BN instance.\n * Accepts BN, ethers BigNumber, hex string, bigint, or number.\n *\n * @param value - The value to convert.\n * @returns BN representation of the input value.\n */\nexport function toBN(value: unknown): BN {\n if (value instanceof BN) {\n return value as BN;\n }\n if (\n typeof (BN as unknown as { isBN?: (v: unknown) => boolean }).isBN ===\n 'function' &&\n (BN as unknown as { isBN: (v: unknown) => boolean }).isBN(value)\n ) {\n return value as BN;\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { toHexString?: () => string }).toHexString === 'function'\n ) {\n return bnFromHex((value as { toHexString: () => string }).toHexString());\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { _hex?: string })._hex === 'string'\n ) {\n return bnFromHex((value as { _hex: string })._hex);\n }\n if (typeof value === 'string') {\n return bnFromHex(value);\n }\n if (typeof value === 'bigint') {\n return new BN(value.toString());\n }\n if (typeof value === 'number') {\n return new BN(value);\n }\n throw new Error('Unexpected value returned from oracle contract');\n}\n\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AAEA,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,iBAAiB,EAClB,wBAAwB;AACzB,OAAO,GAAE,cAAc;;AASvB,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,qBAAiB;AAEtE,MAAM,CAAC,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,gCAAgC;AAChC,8DAA8D;AAC9D,MAAM,WAAW,GAAgD;IAC/D,UAAU,EAAE,CAAC,UAAuB,EAAE,EAAE,CAAC,UAAU;IACnD,iBAAiB,EAAE,CAAC,iBAAqC,EAAE,EAAE,CAC3D,iBAAiB;IACnB,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE;IACjD,GAAG,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC;IAChC,QAAQ,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC;IACrC,QAAQ,EAAE,CAAC,QAAgB,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,C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,EAAE,CAAC,QAAQ,EAAE,CAAC;AAC3E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,QAA2B,EAC3B,mBAA4B;IAE5B,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;QACxB,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,UAAU,CAAC;IACrD,CAAC;SAAM,IAAI,QAAQ,CAAC,iBAAiB,EAAE,CAAC;QACtC,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,OAAO,CAAC;IAClD,CAAC;SAAM,CAAC;QACN,QAAQ,CAAC,IAAI,GAAG,mBAAmB;YACjC,CAAC,CAAC,uBAAuB,CAAC,SAAS;YACnC,CAAC,CAAC,uBAAuB,CAAC,MAAM,CAAC;IACrC,CAAC;AACH,CAAC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport type { Hex, Json } from '@metamask/utils';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport type {\n FeeMarketEIP1559Values,\n GasPriceValue,\n TransactionError,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport { TransactionEnvelopeType, TransactionStatus } 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 accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\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 if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\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 `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\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 `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\n/**\n * Create a BN from a hex string, accepting an optional 0x prefix.\n *\n * @param hex - Hex string with or without 0x prefix.\n * @returns BN parsed as base-16.\n */\nexport function bnFromHex(hex: string | Hex): BN {\n const str = typeof hex === 'string' ? hex : (hex as string);\n const withoutPrefix =\n str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;\n if (withoutPrefix.length === 0) {\n return new BN(0);\n }\n return new BN(withoutPrefix, 16);\n}\n\n/**\n * Convert various numeric-like values to a BN instance.\n * Accepts BN, ethers BigNumber, hex string, bigint, or number.\n *\n * @param value - The value to convert.\n * @returns BN representation of the input value.\n */\nexport function toBN(value: unknown): BN {\n if (value instanceof BN) {\n return value;\n }\n if (\n typeof (BN as unknown as { isBN?: (v: unknown) => boolean }).isBN ===\n 'function' &&\n (BN as unknown as { isBN: (v: unknown) => boolean }).isBN(value)\n ) {\n return value as BN;\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { toHexString?: () => string }).toHexString === 'function'\n ) {\n return bnFromHex((value as { toHexString: () => string }).toHexString());\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { _hex?: string })._hex === 'string'\n ) {\n return bnFromHex((value as { _hex: string })._hex);\n }\n if (typeof value === 'string') {\n return bnFromHex(value);\n }\n if (typeof value === 'bigint') {\n return new BN(value.toString());\n }\n if (typeof value === 'number') {\n return new BN(value);\n }\n throw new Error('Unexpected value returned from oracle contract');\n}\n\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}
|