@metamask/transaction-controller 62.5.0 → 62.6.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 +21 -1
- package/dist/TransactionController.cjs +105 -48
- package/dist/TransactionController.cjs.map +1 -1
- package/dist/TransactionController.d.cts +33 -21
- package/dist/TransactionController.d.cts.map +1 -1
- package/dist/TransactionController.d.mts +33 -21
- package/dist/TransactionController.d.mts.map +1 -1
- package/dist/TransactionController.mjs +106 -49
- package/dist/TransactionController.mjs.map +1 -1
- package/dist/api/accounts-api.cjs +1 -1
- package/dist/api/accounts-api.cjs.map +1 -1
- package/dist/api/accounts-api.mjs +1 -1
- package/dist/api/accounts-api.mjs.map +1 -1
- package/dist/api/simulation-api.cjs +1 -1
- package/dist/api/simulation-api.cjs.map +1 -1
- package/dist/api/simulation-api.mjs +1 -1
- package/dist/api/simulation-api.mjs.map +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.mjs.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs +28 -17
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.cts +1 -6
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.cts.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.mts +1 -6
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.mts.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs +28 -17
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs.map +1 -1
- package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs +1 -0
- 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 +1 -0
- package/dist/gas-flows/OracleLayer1GasFeeFlow.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.mjs.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.cjs.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.d.cts.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.d.mts.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.mjs.map +1 -1
- package/dist/helpers/MultichainTrackingHelper.cjs +2 -2
- 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 +2 -2
- package/dist/helpers/MultichainTrackingHelper.mjs.map +1 -1
- package/dist/helpers/PendingTransactionTracker.cjs +88 -22
- package/dist/helpers/PendingTransactionTracker.cjs.map +1 -1
- package/dist/helpers/PendingTransactionTracker.d.cts +7 -6
- package/dist/helpers/PendingTransactionTracker.d.cts.map +1 -1
- package/dist/helpers/PendingTransactionTracker.d.mts +7 -6
- package/dist/helpers/PendingTransactionTracker.d.mts.map +1 -1
- package/dist/helpers/PendingTransactionTracker.mjs +88 -22
- package/dist/helpers/PendingTransactionTracker.mjs.map +1 -1
- package/dist/helpers/ResimulateHelper.cjs.map +1 -1
- package/dist/helpers/ResimulateHelper.d.cts +1 -4
- package/dist/helpers/ResimulateHelper.d.cts.map +1 -1
- package/dist/helpers/ResimulateHelper.d.mts +1 -4
- package/dist/helpers/ResimulateHelper.d.mts.map +1 -1
- package/dist/helpers/ResimulateHelper.mjs.map +1 -1
- package/dist/helpers/TransactionPoller.cjs.map +1 -1
- package/dist/helpers/TransactionPoller.d.cts.map +1 -1
- package/dist/helpers/TransactionPoller.d.mts.map +1 -1
- package/dist/helpers/TransactionPoller.mjs.map +1 -1
- package/dist/hooks/CollectPublishHook.cjs +1 -1
- package/dist/hooks/CollectPublishHook.cjs.map +1 -1
- package/dist/hooks/CollectPublishHook.d.cts.map +1 -1
- package/dist/hooks/CollectPublishHook.d.mts.map +1 -1
- package/dist/hooks/CollectPublishHook.mjs +1 -1
- package/dist/hooks/CollectPublishHook.mjs.map +1 -1
- package/dist/hooks/ExtraTransactionsPublishHook.cjs.map +1 -1
- package/dist/hooks/ExtraTransactionsPublishHook.mjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/types.cjs +5 -0
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +6 -0
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +6 -0
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs +5 -0
- package/dist/types.mjs.map +1 -1
- package/dist/utils/balance-changes.cjs +5 -5
- package/dist/utils/balance-changes.cjs.map +1 -1
- package/dist/utils/balance-changes.d.cts.map +1 -1
- package/dist/utils/balance-changes.d.mts.map +1 -1
- package/dist/utils/balance-changes.mjs +5 -5
- package/dist/utils/balance-changes.mjs.map +1 -1
- package/dist/utils/balance.cjs.map +1 -1
- package/dist/utils/balance.d.cts.map +1 -1
- package/dist/utils/balance.d.mts.map +1 -1
- package/dist/utils/balance.mjs.map +1 -1
- package/dist/utils/batch.cjs +9 -4
- package/dist/utils/batch.cjs.map +1 -1
- package/dist/utils/batch.d.cts.map +1 -1
- package/dist/utils/batch.d.mts.map +1 -1
- package/dist/utils/batch.mjs +9 -4
- package/dist/utils/batch.mjs.map +1 -1
- package/dist/utils/eip7702.cjs +4 -3
- 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 +4 -3
- package/dist/utils/eip7702.mjs.map +1 -1
- package/dist/utils/external-transactions.cjs.map +1 -1
- package/dist/utils/external-transactions.d.cts.map +1 -1
- package/dist/utils/external-transactions.d.mts.map +1 -1
- package/dist/utils/external-transactions.mjs.map +1 -1
- package/dist/utils/feature-flags.cjs +22 -7
- package/dist/utils/feature-flags.cjs.map +1 -1
- package/dist/utils/feature-flags.d.cts +24 -0
- package/dist/utils/feature-flags.d.cts.map +1 -1
- package/dist/utils/feature-flags.d.mts +24 -0
- package/dist/utils/feature-flags.d.mts.map +1 -1
- package/dist/utils/feature-flags.mjs +20 -6
- package/dist/utils/feature-flags.mjs.map +1 -1
- package/dist/utils/first-time-interaction.cjs +3 -5
- package/dist/utils/first-time-interaction.cjs.map +1 -1
- package/dist/utils/first-time-interaction.d.cts.map +1 -1
- package/dist/utils/first-time-interaction.d.mts.map +1 -1
- package/dist/utils/first-time-interaction.mjs +3 -5
- package/dist/utils/first-time-interaction.mjs.map +1 -1
- package/dist/utils/gas-fee-tokens.cjs +1 -1
- package/dist/utils/gas-fee-tokens.cjs.map +1 -1
- package/dist/utils/gas-fee-tokens.d.cts.map +1 -1
- package/dist/utils/gas-fee-tokens.d.mts.map +1 -1
- package/dist/utils/gas-fee-tokens.mjs +1 -1
- package/dist/utils/gas-fee-tokens.mjs.map +1 -1
- package/dist/utils/gas-fees.cjs +1 -3
- package/dist/utils/gas-fees.cjs.map +1 -1
- package/dist/utils/gas-fees.d.cts +1 -1
- package/dist/utils/gas-fees.d.cts.map +1 -1
- package/dist/utils/gas-fees.d.mts +1 -1
- package/dist/utils/gas-fees.d.mts.map +1 -1
- package/dist/utils/gas-fees.mjs +1 -3
- package/dist/utils/gas-fees.mjs.map +1 -1
- package/dist/utils/gas.cjs +71 -15
- package/dist/utils/gas.cjs.map +1 -1
- package/dist/utils/gas.d.cts +18 -12
- package/dist/utils/gas.d.cts.map +1 -1
- package/dist/utils/gas.d.mts +18 -12
- package/dist/utils/gas.d.mts.map +1 -1
- package/dist/utils/gas.mjs +70 -15
- 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.map +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/prepare.cjs.map +1 -1
- package/dist/utils/prepare.d.cts +1 -1
- package/dist/utils/prepare.d.cts.map +1 -1
- package/dist/utils/prepare.d.mts +1 -1
- package/dist/utils/prepare.d.mts.map +1 -1
- package/dist/utils/prepare.mjs.map +1 -1
- package/dist/utils/swaps.cjs.map +1 -1
- package/dist/utils/swaps.mjs.map +1 -1
- package/dist/utils/utils.cjs +10 -10
- package/dist/utils/utils.cjs.map +1 -1
- package/dist/utils/utils.d.cts +4 -4
- package/dist/utils/utils.d.cts.map +1 -1
- package/dist/utils/utils.d.mts +4 -4
- package/dist/utils/utils.d.mts.map +1 -1
- package/dist/utils/utils.mjs +10 -10
- package/dist/utils/utils.mjs.map +1 -1
- package/dist/utils/validation.cjs.map +1 -1
- package/dist/utils/validation.d.cts.map +1 -1
- package/dist/utils/validation.d.mts.map +1 -1
- package/dist/utils/validation.mjs.map +1 -1
- package/package.json +1 -1
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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ACtD;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 { 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
|
+
{"version":3,"file":"gas.mjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EACP,UAAU,EACV,OAAO,EACP,K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BAA6B;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,IAAI,CAAC,EAAE;gBACN,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 { BigNumber } from 'bignumber.js';\n\nimport { DELEGATION_PREFIX, generateEIP7702BatchTransaction } 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 AuthorizationList,\n BatchTransactionParams,\n GetSimulationConfig,\n IsAtomicBatchSupportedRequest,\n IsAtomicBatchSupportedResult,\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): Promise<void> {\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 txMeta.defaultGasEstimates ??= {};\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}): Promise<{\n blockGasLimit: string;\n estimatedGas: string;\n isUpgradeWithDataToSelf: boolean;\n simulationFails: TransactionMeta['simulationFails'];\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\nexport async function estimateGasBatch({\n chainId,\n ethQuery,\n from,\n getSimulationConfig,\n isAtomicBatchSupported,\n messenger,\n transactions,\n}: {\n chainId: Hex;\n ethQuery: EthQuery;\n from: Hex;\n getSimulationConfig: GetSimulationConfig;\n isAtomicBatchSupported: (\n request: IsAtomicBatchSupportedRequest,\n ) => Promise<IsAtomicBatchSupportedResult>;\n messenger: TransactionControllerMessenger;\n transactions: BatchTransactionParams[];\n}): Promise<{ totalGasLimit: number; gasLimits: number[] }> {\n const is7702Result = await isAtomicBatchSupported({\n address: from,\n chainIds: [chainId],\n });\n\n const chainResult = is7702Result.find((result) => result.chainId === chainId);\n const isUpgradeRequired = Boolean(chainResult && !chainResult.isSupported);\n\n if (isUpgradeRequired && !chainResult?.upgradeContractAddress) {\n throw new Error('Upgrade contract address not found');\n }\n\n if (chainResult) {\n const authorizationList = isUpgradeRequired\n ? [{ address: chainResult.upgradeContractAddress as Hex }]\n : undefined;\n\n const type = isUpgradeRequired\n ? TransactionEnvelopeType.setCode\n : undefined;\n\n const params: TransactionParams = {\n ...generateEIP7702BatchTransaction(from, transactions),\n authorizationList,\n from,\n type,\n };\n\n const { estimatedGas: gasLimitHex } = await estimateGas({\n chainId,\n ethQuery,\n isSimulationEnabled: true,\n getSimulationConfig,\n messenger,\n txParams: params,\n });\n\n const totalGasLimit = new BigNumber(gasLimitHex).toNumber();\n\n log('Estimated EIP-7702 gas limit', totalGasLimit);\n\n return { totalGasLimit, gasLimits: [totalGasLimit] };\n }\n\n const allTransactionsHaveGas = transactions.every(\n (transaction) => transaction.gas !== undefined,\n );\n\n if (allTransactionsHaveGas) {\n const gasLimits = transactions.map((transaction) =>\n new BigNumber(transaction.gas as Hex).toNumber(),\n );\n\n const total = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);\n\n log('Using batch parameter gas limits', { gasLimits, total });\n\n return { totalGasLimit: total, gasLimits };\n }\n\n const { gasLimits: gasLimitsHex } = await simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions: transactions.map((transaction) => ({\n params: transaction,\n })),\n });\n\n const gasLimits = transactions.map((transaction, index) =>\n transaction.gas\n ? new BigNumber(transaction.gas).toNumber()\n : new BigNumber(gasLimitsHex[index]).toNumber(),\n );\n\n const totalGasLimit = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);\n\n log('Simulated batch gas limits', { totalGasLimit, gasLimits });\n\n return { totalGasLimit, gasLimits };\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): string {\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<{ totalGasLimit: Hex; gasLimits: 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 return response.transactions.reduce<{\n totalGasLimit: Hex;\n gasLimits: Hex[];\n }>(\n (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 acc.gasLimits.push(gasLimit);\n\n acc.totalGasLimit = BNToHex(\n hexToBN(acc.totalGasLimit).add(hexToBN(gasLimit)),\n );\n\n return acc;\n },\n {\n totalGasLimit: '0x0',\n gasLimits: [],\n },\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): Promise<Hex> {\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).add(hexToBN(executeGas)).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: AuthorizationList | undefined,\n chainId: Hex,\n): AuthorizationList | undefined {\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): Promise<Hex> {\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,2CAAqD;AAGrD,0CAA0C;AAI1C,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,sBAAsB,CAAC,CAAC;AAStE;;;;;;;GAOG;AACI,KAAK,UAAU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O,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
|
+
{"version":3,"file":"layer1-gas-fee-flow.cjs","sourceRoot":"","sources":["../../src/utils/layer1-gas-fee-flow.ts"],"names":[],"mappings":";;;AACA,2CAAqD;AAGrD,0CAA0C;AAI1C,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,sBAAsB,CAAC,CAAC;AAStE;;;;;;;GAOG;AACI,KAAK,UAAU,6BAA6B,CACjD,OAAkC;IAElC,MAAM,YAAY,GAAG,MAAM,0BAA0B,CAAC,OAAO,CAAC,CAAC;IAE/D,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,EAAE,eAAe,EAAE,GAAG,OAAO,CAAC;IAEpC,eAAe,CAAC,YAAY,GAAG,YAAY,CAAC;IAE5C,GAAG,CAAC,yBAAyB,EAAE,YAAY,EAAE,eAAe,CAAC,EAAE,CAAC,CAAC;AACnE,CAAC;AAdD,sEAcC;AAED;;;;;;;GAOG;AACH,KAAK,UAAU,mBAAmB,CAChC,eAAgC,EAChC,iBAAqC,EACrC,SAAyC;IAEzC,KAAK,MAAM,gBAAgB,IAAI,iBAAiB,EAAE,CAAC;QACjD,MAAM,OAAO,GAAG,MAAM,gBAAgB,CAAC,kBAAkB,CAAC;YACxD,eAAe;YACf,SAAS;SACV,CAAC,CAAC;QAEH,IAAI,OAAO,EAAE,CAAC;YACZ,OAAO,gBAAgB,CAAC;QAC1B,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;;;;;GASG;AACI,KAAK,UAAU,0BAA0B,CAAC,EAC/C,iBAAiB,EACjB,SAAS,EACT,QAAQ,EACR,eAAe,GACW;IAC1B,MAAM,gBAAgB,GAAG,MAAM,mBAAmB,CAChD,eAAe,EACf,iBAAiB,EACjB,SAAS,CACV,CAAC;IAEF,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,GAAG,CACD,4BAA4B,EAC5B,gBAAgB,CAAC,WAAW,CAAC,IAAI,EACjC,eAAe,CAAC,EAAE,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): Promise<void> {\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 +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;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,
|
|
1
|
+
{"version":3,"file":"layer1-gas-fee-flow.d.cts","sourceRoot":"","sources":["../../src/utils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B,6BAA6B,CACjD,OAAO,EAAE,yBAAyB,
|
|
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,GACjC,OAAO,CAAC,IAAI,CAAC,CAYf;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,EAAE,wBAAwB;AAGrD,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAI1C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,sBAAsB,CAAC,CAAC;AAStE;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAkC;IAElC,MAAM,YAAY,GAAG,MAAM,0BAA0B,CAAC,OAAO,CAAC,CAAC;IAE/D,IAAI,CAAC,YAA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S,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"]}
|
|
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;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAkC;IAElC,MAAM,YAAY,GAAG,MAAM,0BAA0B,CAAC,OAAO,CAAC,CAAC;IAE/D,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO;IACT,CAAC;IAED,MAAM,EAAE,eAAe,EAAE,GAAG,OAAO,CAAC;IAEpC,eAAe,CAAC,YAAY,GAAG,YAAY,CAAC;IAE5C,GAAG,CAAC,yBAAyB,EAAE,YAAY,EAAE,eAAe,CAAC,EAAE,CAAC,CAAC;AACnE,CAAC;AAED;;;;;;;GAOG;AACH,KAAK,UAAU,mBAAmB,CAChC,eAAgC,EAChC,iBAAqC,EACrC,SAAyC;IAEzC,KAAK,MAAM,gBAAgB,IAAI,iBAAiB,EAAE,CAAC;QACjD,MAAM,OAAO,GAAG,MAAM,gBAAgB,CAAC,kBAAkB,CAAC;YACxD,eAAe;YACf,SAAS;SACV,CAAC,CAAC;QAEH,IAAI,OAAO,EAAE,CAAC;YACZ,OAAO,gBAAgB,CAAC;QAC1B,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAAC,EAC/C,iBAAiB,EACjB,SAAS,EACT,QAAQ,EACR,eAAe,GACW;IAC1B,MAAM,gBAAgB,GAAG,MAAM,mBAAmB,CAChD,eAAe,EACf,iBAAiB,EACjB,SAAS,CACV,CAAC;IAEF,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,GAAG,CACD,4BAA4B,EAC5B,gBAAgB,CAAC,WAAW,CAAC,IAAI,EACjC,eAAe,CAAC,EAAE,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","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): Promise<void> {\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare.cjs","sourceRoot":"","sources":["../../src/utils/prepare.ts"],"names":[],"mappings":";;;AACA,+CAAsD;AAEtD,uCAAoD;AACpD,2CAA6C;AAE7C,mCAAmC;AAItB,QAAA,QAAQ,GAAG,iBAAQ,CAAC,MAAM,CAAC;AAExC;;;;;;GAMG;AACH,SAAgB,kBAAkB,CAChC,OAAY,EACZ,QAA2B;IAE3B,MAAM,cAAc,GAAG,eAAe,CAAC,QAAQ,CAAC,CAAC;IAEjD,oDAAoD;IACpD,MAAM,IAAI,GAAG,cAA6B,CAAC;IAE3C,OAAO,uBAAkB,CAAC,UAAU,CAAC,IAAI,EAAE;QACzC,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,sBAAsB,CAAC,OAAO,CAAC;KACxC,CAAC,CAAC;AACL,CAAC;AAbD,gDAaC;AAED;;;;;GAKG;AACH,SAAgB,oBAAoB,CAAC,WAA6B;IAChE,OAAO,IAAA,kBAAU,EAAC,WAAW,CAAC,SAAS,EAAE,CAAC,CAAC;AAC7C,CAAC;AAFD,oDAEC;AAED;;;;;GAKG;AACH,SAAS,sBAAsB,CAAC,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ethereumjs/common';\nimport type { TypedTransaction, TypedTxData } from '@ethereumjs/tx';\nimport { TransactionFactory } from '@ethereumjs/tx';\nimport { bytesToHex } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\nimport { cloneDeep } from 'lodash';\n\nimport type { AuthorizationList, TransactionParams } from '../types';\n\nexport const HARDFORK = Hardfork.Prague;\n\n/**\n * Creates an `etheruemjs/tx` transaction object from the raw transaction parameters.\n *\n * @param chainId - Chain ID of the transaction.\n * @param txParams - Transaction parameters.\n * @returns The transaction object.\n */\nexport function prepareTransaction(\n chainId: Hex,\n txParams: TransactionParams,\n): TypedTransaction {\n const normalizedData = normalizeParams(txParams);\n\n // Does not allow `gasPrice` on type 4 transactions.\n const data = normalizedData as TypedTxData;\n\n return TransactionFactory.fromTxData(data, {\n freeze: false,\n common: getCommonConfiguration(chainId),\n });\n}\n\n/**\n * Serializes a transaction object into a hex string.\n *\n * @param transaction - The transaction object.\n * @returns The prefixed hex string.\n */\nexport function serializeTransaction(transaction: TypedTransaction): Hex {\n return bytesToHex(transaction.serialize());\n}\n\n/**\n * Generates the configuration used to prepare transactions.\n *\n * @param chainId - Chain ID.\n * @returns The common configuration.\n */\nfunction getCommonConfiguration(chainId: Hex): Common {\n const customChainParams: Partial<ChainConfig> = {\n chainId: parseInt(chainId, 16),\n defaultHardfork: HARDFORK,\n };\n\n return Common.custom(customChainParams, {\n eips: [7702],\n });\n}\n\n/**\n * Normalize the transaction parameters for compatibility with `ethereumjs/tx`.\n *\n * @param params - The transaction parameters to normalize.\n * @returns The normalized transaction parameters.\n */\nfunction normalizeParams(params: TransactionParams): TransactionParams {\n const newParams = cloneDeep(params);\n normalizeAuthorizationList(newParams.authorizationList);\n return newParams;\n}\n\n/**\n * Normalize the authorization list for `ethereumjs/tx` compatibility.\n *\n * @param authorizationList - The list of authorizations to normalize.\n */\nfunction normalizeAuthorizationList(\n authorizationList?: AuthorizationList,\n): void {\n if (!authorizationList) {\n return;\n }\n\n for (const authorization of authorizationList) {\n authorization.nonce = removeLeadingZeroes(authorization.nonce);\n authorization.r = removeLeadingZeroes(authorization.r);\n authorization.s = removeLeadingZeroes(authorization.s);\n authorization.yParity = removeLeadingZeroes(authorization.yParity);\n }\n}\n\n/**\n * Remove leading zeroes from a hexadecimal string.\n *\n * @param value - The hexadecimal string to process.\n * @returns The processed hexadecimal string.\n */\nfunction removeLeadingZeroes(value: Hex | undefined): Hex | undefined {\n if (!value) {\n return value;\n }\n\n if (value === '0x0') {\n return '0x';\n }\n\n return (value.replace?.(/^0x(00)+/u, '0x') as Hex) ?? value;\n}\n"]}
|
package/dist/utils/prepare.d.cts
CHANGED
|
@@ -17,5 +17,5 @@ export declare function prepareTransaction(chainId: Hex, txParams: TransactionPa
|
|
|
17
17
|
* @param transaction - The transaction object.
|
|
18
18
|
* @returns The prefixed hex string.
|
|
19
19
|
*/
|
|
20
|
-
export declare function serializeTransaction(transaction: TypedTransaction):
|
|
20
|
+
export declare function serializeTransaction(transaction: TypedTransaction): Hex;
|
|
21
21
|
//# sourceMappingURL=prepare.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare.d.cts","sourceRoot":"","sources":["../../src/utils/prepare.ts"],"names":[],"mappings":"AACA,OAAO,EAAU,QAAQ,EAAE,2BAA2B;AACtD,OAAO,KAAK,EAAE,gBAAgB,EAAe,uBAAuB;AAGpE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EAAqB,iBAAiB,EAAE,qBAAiB;AAErE,eAAO,MAAM,QAAQ,kBAAkB,CAAC;AAExC;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,GAAG,EACZ,QAAQ,EAAE,iBAAiB,GAC1B,gBAAgB,CAUlB;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,WAAW,EAAE,gBAAgB,
|
|
1
|
+
{"version":3,"file":"prepare.d.cts","sourceRoot":"","sources":["../../src/utils/prepare.ts"],"names":[],"mappings":"AACA,OAAO,EAAU,QAAQ,EAAE,2BAA2B;AACtD,OAAO,KAAK,EAAE,gBAAgB,EAAe,uBAAuB;AAGpE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EAAqB,iBAAiB,EAAE,qBAAiB;AAErE,eAAO,MAAM,QAAQ,kBAAkB,CAAC;AAExC;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,GAAG,EACZ,QAAQ,EAAE,iBAAiB,GAC1B,gBAAgB,CAUlB;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,WAAW,EAAE,gBAAgB,GAAG,GAAG,CAEvE"}
|
package/dist/utils/prepare.d.mts
CHANGED
|
@@ -17,5 +17,5 @@ export declare function prepareTransaction(chainId: Hex, txParams: TransactionPa
|
|
|
17
17
|
* @param transaction - The transaction object.
|
|
18
18
|
* @returns The prefixed hex string.
|
|
19
19
|
*/
|
|
20
|
-
export declare function serializeTransaction(transaction: TypedTransaction):
|
|
20
|
+
export declare function serializeTransaction(transaction: TypedTransaction): Hex;
|
|
21
21
|
//# sourceMappingURL=prepare.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare.d.mts","sourceRoot":"","sources":["../../src/utils/prepare.ts"],"names":[],"mappings":"AACA,OAAO,EAAU,QAAQ,EAAE,2BAA2B;AACtD,OAAO,KAAK,EAAE,gBAAgB,EAAe,uBAAuB;AAGpE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EAAqB,iBAAiB,EAAE,qBAAiB;AAErE,eAAO,MAAM,QAAQ,kBAAkB,CAAC;AAExC;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,GAAG,EACZ,QAAQ,EAAE,iBAAiB,GAC1B,gBAAgB,CAUlB;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,WAAW,EAAE,gBAAgB,
|
|
1
|
+
{"version":3,"file":"prepare.d.mts","sourceRoot":"","sources":["../../src/utils/prepare.ts"],"names":[],"mappings":"AACA,OAAO,EAAU,QAAQ,EAAE,2BAA2B;AACtD,OAAO,KAAK,EAAE,gBAAgB,EAAe,uBAAuB;AAGpE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EAAqB,iBAAiB,EAAE,qBAAiB;AAErE,eAAO,MAAM,QAAQ,kBAAkB,CAAC;AAExC;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,GAAG,EACZ,QAAQ,EAAE,iBAAiB,GAC1B,gBAAgB,CAUlB;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,WAAW,EAAE,gBAAgB,GAAG,GAAG,CAEvE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare.mjs","sourceRoot":"","sources":["../../src/utils/prepare.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,2BAA2B;AAEtD,OAAO,EAAE,kBAAkB,EAAE,uBAAuB;AACpD,OAAO,EAAE,UAAU,EAAE,wBAAwB;;;AAM7C,MAAM,CAAC,MAAM,QAAQ,GAAG,QAAQ,CAAC,MAAM,CAAC;AAExC;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAAY,EACZ,QAA2B;IAE3B,MAAM,cAAc,GAAG,eAAe,CAAC,QAAQ,CAAC,CAAC;IAEjD,oDAAoD;IACpD,MAAM,IAAI,GAAG,cAA6B,CAAC;IAE3C,OAAO,kBAAkB,CAAC,UAAU,CAAC,IAAI,EAAE;QACzC,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,sBAAsB,CAAC,OAAO,CAAC;KACxC,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,WAA6B;IAChE,OAAO,UAAU,CAAC,WAAW,CAAC,SAAS,EAAE,CAAC,C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,IAAI,CAAS,IAAI,KAAK,CAAC;AAC9D,CAAC","sourcesContent":["import type { ChainConfig } from '@ethereumjs/common';\nimport { Common, Hardfork } from '@ethereumjs/common';\nimport type { TypedTransaction, TypedTxData } from '@ethereumjs/tx';\nimport { TransactionFactory } from '@ethereumjs/tx';\nimport { bytesToHex } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\nimport { cloneDeep } from 'lodash';\n\nimport type { AuthorizationList, TransactionParams } from '../types';\n\nexport const HARDFORK = Hardfork.Prague;\n\n/**\n * Creates an `etheruemjs/tx` transaction object from the raw transaction parameters.\n *\n * @param chainId - Chain ID of the transaction.\n * @param txParams - Transaction parameters.\n * @returns The transaction object.\n */\nexport function prepareTransaction(\n chainId: Hex,\n txParams: TransactionParams,\n): TypedTransaction {\n const normalizedData = normalizeParams(txParams);\n\n // Does not allow `gasPrice` on type 4 transactions.\n const data = normalizedData as TypedTxData;\n\n return TransactionFactory.fromTxData(data, {\n freeze: false,\n common: getCommonConfiguration(chainId),\n });\n}\n\n/**\n * Serializes a transaction object into a hex string.\n *\n * @param transaction - The transaction object.\n * @returns The prefixed hex string.\n */\nexport function serializeTransaction(transaction: TypedTransaction): Hex {\n return bytesToHex(transaction.serialize());\n}\n\n/**\n * Generates the configuration used to prepare transactions.\n *\n * @param chainId - Chain ID.\n * @returns The common configuration.\n */\nfunction getCommonConfiguration(chainId: Hex): Common {\n const customChainParams: Partial<ChainConfig> = {\n chainId: parseInt(chainId, 16),\n defaultHardfork: HARDFORK,\n };\n\n return Common.custom(customChainParams, {\n eips: [7702],\n });\n}\n\n/**\n * Normalize the transaction parameters for compatibility with `ethereumjs/tx`.\n *\n * @param params - The transaction parameters to normalize.\n * @returns The normalized transaction parameters.\n */\nfunction normalizeParams(params: TransactionParams): TransactionParams {\n const newParams = cloneDeep(params);\n normalizeAuthorizationList(newParams.authorizationList);\n return newParams;\n}\n\n/**\n * Normalize the authorization list for `ethereumjs/tx` compatibility.\n *\n * @param authorizationList - The list of authorizations to normalize.\n */\nfunction normalizeAuthorizationList(\n authorizationList?: AuthorizationList,\n): void {\n if (!authorizationList) {\n return;\n }\n\n for (const authorization of authorizationList) {\n authorization.nonce = removeLeadingZeroes(authorization.nonce);\n authorization.r = removeLeadingZeroes(authorization.r);\n authorization.s = removeLeadingZeroes(authorization.s);\n authorization.yParity = removeLeadingZeroes(authorization.yParity);\n }\n}\n\n/**\n * Remove leading zeroes from a hexadecimal string.\n *\n * @param value - The hexadecimal string to process.\n * @returns The processed hexadecimal string.\n */\nfunction removeLeadingZeroes(value: Hex | undefined): Hex | undefined {\n if (!value) {\n return value;\n }\n\n if (value === '0x0') {\n return '0x';\n }\n\n return (value.replace?.(/^0x(00)+/u, '0x') as Hex) ?? value;\n}\n"]}
|
package/dist/utils/swaps.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swaps.cjs","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":";;;AAAA,iEAAmD;AAEnD,mCAAuC;AAEvC,uCAA0D;AAC1D,gDAAyC;AACzC,0CAA8D;AAG9D,wCAA2C;AAE3C,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;GAEG;AACU,QAAA,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG;AACU,QAAA,+BAA+B,GAAG,CAAC,CAAC;AAEjD,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC;;GAEG;AACU,QAAA,qBAAqB,GAChC,4CAA4C,CAAC;AAmB/C,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACb,CAAC;AAEF,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,cAAc;IACpB,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,wBAAwB,GAAqB;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jE,uBAAuB,GAAG,IAAA,eAAM,EAAC;QAC/B,IAAI;QACJ,iBAAiB;KAClB,CAA6B,CAAC;IAE/B,OAAO,IAAA,cAAK,EAAC,EAAE,EAAE,eAAe,EAAE,uBAAuB,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,0BAA0B,CAAC,OAAe,EAAE,OAAe;IAClE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CACL,OAAO;QACP,uCAA+B,CAC7B,OAAuD,CACxD,EAAE,OAAO,CACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { merge, pickBy } from 'lodash';\n\nimport { validateIfTransactionUnapproved } from './utils';\nimport { CHAIN_IDS } from '../constants';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'swaps');\n\n/**\n * Interval in milliseconds between checks of post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;\n\n/**\n * Retry attempts for checking post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;\n\nconst SWAPS_TESTNET_CHAIN_ID = '0x539';\n\n/**\n * An address that the metaswap-api recognizes as the default token for the current network, in place of the token address that ERC-20 tokens have\n */\nexport const DEFAULT_TOKEN_ADDRESS =\n '0x0000000000000000000000000000000000000000';\n\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface SwapsTokenObject {\n /**\n * The name for the network\n */\n name: string;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n}\n\nconst ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n};\n\nconst BNB_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Binance Coin',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MATIC_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Matic',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst AVAX_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Avalanche',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst TEST_ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Test Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst GOERLI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst ARBITRUM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst OPTIMISM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst ZKSYNC_ERA_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst SEI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Sei',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MONAD_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Mon',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nexport const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {\n [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,\n [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.SEI]: SEI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.MONAD]: MONAD_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapAndSend,\n TransactionType.swapApproval,\n];\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - The transaction meta object to update\n * @param transactionType - The type of the transaction\n * @param swaps - The swaps object\n * @param swaps.hasApproveTx - Whether the swap has an approval transaction\n * @param swaps.meta - The swap meta object\n * @param updateSwapsTransactionRequest - Dependency bag\n * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled\n * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction\n * @param updateSwapsTransactionRequest.messenger - TransactionController messenger\n * @returns A copy of the transaction meta object with updates, or the same\n * transaction meta object if no updates were made.\n */\nexport function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n messenger,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n messenger: TransactionControllerMessenger;\n },\n): TransactionMeta {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return transactionMeta;\n }\n\n // The simulationFails property is added if the estimateGas call fails. In cases\n // when no swaps approval tx is required, this indicates that the swap will likely\n // fail. There was an earlier estimateGas call made by the swaps controller,\n // but it is possible that external conditions have change since then, and\n // a previously succeeding estimate gas call could now fail. By checking for\n // the `simulationFails` property here, we can reduce the number of swap\n // transactions that get published to the blockchain only to fail and thereby\n // waste the user's funds on gas.\n if (\n transactionType === TransactionType.swap &&\n swaps?.hasApproveTx === false &&\n transactionMeta.simulationFails\n ) {\n cancelTransaction(transactionMeta.id);\n throw new Error('Simulation failed');\n }\n\n const swapsMeta = swaps?.meta as Partial<TransactionMeta>;\n\n if (!swapsMeta) {\n return transactionMeta;\n }\n\n let updatedTransactionMeta = transactionMeta;\n\n if (transactionType === TransactionType.swapApproval) {\n updatedTransactionMeta = updateSwapApprovalTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapApproval', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swapAndSend) {\n updatedTransactionMeta = updateSwapAndSendTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapAndSend', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updatedTransactionMeta = updateSwapTransaction(transactionMeta, swapsMeta);\n messenger.publish('TransactionController:transactionNewSwap', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n return updatedTransactionMeta;\n}\n\n/**\n * Attempts to update the post transaction balance of the provided transaction\n *\n * @param transactionMeta - Transaction meta object to update\n * @param updatePostTransactionBalanceRequest - Dependency bag\n * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object\n * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state\n * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function\n * @returns Updated transaction metadata and approval transaction metadata if applicable.\n */\nexport async function updatePostTransactionBalance(\n transactionMeta: TransactionMeta,\n {\n ethQuery,\n getTransaction,\n updateTransaction,\n }: {\n ethQuery: EthQuery;\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;\n },\n): Promise<{\n updatedTransactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n}> {\n log('Updating post transaction balance', transactionMeta.id);\n\n const transactionId = transactionMeta.id;\n let latestTransactionMeta: TransactionMeta | undefined;\n let approvalTransactionMeta;\n\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n log('Querying balance', { attempt: i });\n\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n\n latestTransactionMeta = {\n ...(getTransaction(transactionId) ?? ({} as TransactionMeta)),\n };\n\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n\n const isDefaultTokenAddress = isSwapsDefaultTokenAddress(\n transactionMeta.destinationTokenAddress as string,\n transactionMeta.chainId,\n );\n\n if (\n !isDefaultTokenAddress ||\n transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance\n ) {\n log('Finishing post balance update', {\n isDefaultTokenAddress,\n preTxBalance: transactionMeta.preTxBalance,\n postTxBalance: latestTransactionMeta.postTxBalance,\n });\n\n break;\n }\n\n log('Waiting for balance to update', {\n delay: UPDATE_POST_TX_BALANCE_TIMEOUT,\n });\n\n await sleep(UPDATE_POST_TX_BALANCE_TIMEOUT);\n }\n\n updateTransaction(\n latestTransactionMeta as TransactionMeta,\n 'TransactionController#updatePostTransactionBalance - Add post transaction balance',\n );\n\n log('Completed post balance update', latestTransactionMeta?.postTxBalance);\n\n return {\n updatedTransactionMeta: latestTransactionMeta as TransactionMeta,\n approvalTransactionMeta,\n };\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapTransaction(\n transactionMeta: TransactionMeta,\n {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.destinationTokenAmount - The raw amount of the destination token\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.sourceTokenAddress - The address of the source token\n * @param propsToUpdate.sourceTokenAmount - The raw amount of the source token\n * @param propsToUpdate.sourceTokenDecimals - The decimals of the source token\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.swapAndSendRecipient - The recipient of the swap and send transaction\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped – possibly the same as sourceTokenAmount; included for consistency\n * @param propsToUpdate.type - Type of the transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapAndSendTransaction(\n transactionMeta: TransactionMeta,\n {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap approval information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @returns The updated transaction meta object.\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n\n return merge({}, transactionMeta, swapApprovalTransaction);\n}\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nfunction isSwapsDefaultTokenAddress(address: string, chainId: string) {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.address\n );\n}\n\n/**\n * Sleeps for the provided number of milliseconds\n *\n * @param ms - Number of milliseconds to sleep\n * @returns Promise that resolves after the provided number of milliseconds\n */\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"swaps.cjs","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":";;;AAAA,iEAAmD;AAEnD,mCAAuC;AAEvC,uCAA0D;AAC1D,gDAAyC;AACzC,0CAA8D;AAG9D,wCAA2C;AAE3C,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;GAEG;AACU,QAAA,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG;AACU,QAAA,+BAA+B,GAAG,CAAC,CAAC;AAEjD,MAAM,sBAAsB,GAAG,OAAO,CAA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IAAA,cAAK,EAAC,EAAE,EAAE,eAAe,EAAE,eAAe,CAAC,CAAC;AACrD,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,6BAA6B,CACpC,eAAgC,EAChC,EAAE,IAAI,EAAE,iBAAiB,EAA4B;IAErD,IAAA,uCAA+B,EAC7B,eAAe,EACf,+BAA+B,CAChC,CAAC;IAEF,gCAAgC;IAChC,8DAA8D;IAC9D,IAAI,uBAAuB,GAAG,EAAE,IAAI,EAAE,iBAAiB,EAAS,CAAC;IACjE,uBAAuB,GAAG,IAAA,eAAM,EAAC;QAC/B,IAAI;QACJ,iBAAiB;KAClB,CAA6B,CAAC;IAE/B,OAAO,IAAA,cAAK,EAAC,EAAE,EAAE,eAAe,EAAE,uBAAuB,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,0BAA0B,CAAC,OAAe,EAAE,OAAe;IAClE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CACL,OAAO;QACP,uCAA+B,CAC7B,OAAuD,CACxD,EAAE,OAAO,CACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { merge, pickBy } from 'lodash';\n\nimport { validateIfTransactionUnapproved } from './utils';\nimport { CHAIN_IDS } from '../constants';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'swaps');\n\n/**\n * Interval in milliseconds between checks of post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;\n\n/**\n * Retry attempts for checking post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;\n\nconst SWAPS_TESTNET_CHAIN_ID = '0x539';\n\n/**\n * An address that the metaswap-api recognizes as the default token for the current network, in place of the token address that ERC-20 tokens have\n */\nexport const DEFAULT_TOKEN_ADDRESS =\n '0x0000000000000000000000000000000000000000';\n\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface SwapsTokenObject {\n /**\n * The name for the network\n */\n name: string;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n}\n\nconst ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n};\n\nconst BNB_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Binance Coin',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MATIC_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Matic',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst AVAX_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Avalanche',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst TEST_ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Test Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst GOERLI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst ARBITRUM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst OPTIMISM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst ZKSYNC_ERA_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst SEI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Sei',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MONAD_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Mon',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nexport const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {\n [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,\n [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.SEI]: SEI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.MONAD]: MONAD_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapAndSend,\n TransactionType.swapApproval,\n];\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - The transaction meta object to update\n * @param transactionType - The type of the transaction\n * @param swaps - The swaps object\n * @param swaps.hasApproveTx - Whether the swap has an approval transaction\n * @param swaps.meta - The swap meta object\n * @param updateSwapsTransactionRequest - Dependency bag\n * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled\n * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction\n * @param updateSwapsTransactionRequest.messenger - TransactionController messenger\n * @returns A copy of the transaction meta object with updates, or the same\n * transaction meta object if no updates were made.\n */\nexport function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n messenger,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n messenger: TransactionControllerMessenger;\n },\n): TransactionMeta {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return transactionMeta;\n }\n\n // The simulationFails property is added if the estimateGas call fails. In cases\n // when no swaps approval tx is required, this indicates that the swap will likely\n // fail. There was an earlier estimateGas call made by the swaps controller,\n // but it is possible that external conditions have change since then, and\n // a previously succeeding estimate gas call could now fail. By checking for\n // the `simulationFails` property here, we can reduce the number of swap\n // transactions that get published to the blockchain only to fail and thereby\n // waste the user's funds on gas.\n if (\n transactionType === TransactionType.swap &&\n swaps?.hasApproveTx === false &&\n transactionMeta.simulationFails\n ) {\n cancelTransaction(transactionMeta.id);\n throw new Error('Simulation failed');\n }\n\n const swapsMeta = swaps?.meta as Partial<TransactionMeta>;\n\n if (!swapsMeta) {\n return transactionMeta;\n }\n\n let updatedTransactionMeta = transactionMeta;\n\n if (transactionType === TransactionType.swapApproval) {\n updatedTransactionMeta = updateSwapApprovalTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapApproval', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swapAndSend) {\n updatedTransactionMeta = updateSwapAndSendTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapAndSend', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updatedTransactionMeta = updateSwapTransaction(transactionMeta, swapsMeta);\n messenger.publish('TransactionController:transactionNewSwap', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n return updatedTransactionMeta;\n}\n\n/**\n * Attempts to update the post transaction balance of the provided transaction\n *\n * @param transactionMeta - Transaction meta object to update\n * @param updatePostTransactionBalanceRequest - Dependency bag\n * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object\n * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state\n * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function\n * @returns Updated transaction metadata and approval transaction metadata if applicable.\n */\nexport async function updatePostTransactionBalance(\n transactionMeta: TransactionMeta,\n {\n ethQuery,\n getTransaction,\n updateTransaction,\n }: {\n ethQuery: EthQuery;\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;\n },\n): Promise<{\n updatedTransactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n}> {\n log('Updating post transaction balance', transactionMeta.id);\n\n const transactionId = transactionMeta.id;\n let latestTransactionMeta: TransactionMeta | undefined;\n let approvalTransactionMeta;\n\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n log('Querying balance', { attempt: i });\n\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n\n latestTransactionMeta = {\n ...(getTransaction(transactionId) ?? ({} as TransactionMeta)),\n };\n\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n\n const isDefaultTokenAddress = isSwapsDefaultTokenAddress(\n transactionMeta.destinationTokenAddress as string,\n transactionMeta.chainId,\n );\n\n if (\n !isDefaultTokenAddress ||\n transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance\n ) {\n log('Finishing post balance update', {\n isDefaultTokenAddress,\n preTxBalance: transactionMeta.preTxBalance,\n postTxBalance: latestTransactionMeta.postTxBalance,\n });\n\n break;\n }\n\n log('Waiting for balance to update', {\n delay: UPDATE_POST_TX_BALANCE_TIMEOUT,\n });\n\n await sleep(UPDATE_POST_TX_BALANCE_TIMEOUT);\n }\n\n updateTransaction(\n latestTransactionMeta as TransactionMeta,\n 'TransactionController#updatePostTransactionBalance - Add post transaction balance',\n );\n\n log('Completed post balance update', latestTransactionMeta?.postTxBalance);\n\n return {\n updatedTransactionMeta: latestTransactionMeta as TransactionMeta,\n approvalTransactionMeta,\n };\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapTransaction(\n transactionMeta: TransactionMeta,\n {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.destinationTokenAmount - The raw amount of the destination token\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.sourceTokenAddress - The address of the source token\n * @param propsToUpdate.sourceTokenAmount - The raw amount of the source token\n * @param propsToUpdate.sourceTokenDecimals - The decimals of the source token\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.swapAndSendRecipient - The recipient of the swap and send transaction\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped – possibly the same as sourceTokenAmount; included for consistency\n * @param propsToUpdate.type - Type of the transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapAndSendTransaction(\n transactionMeta: TransactionMeta,\n {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap approval information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @returns The updated transaction meta object.\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n\n return merge({}, transactionMeta, swapApprovalTransaction);\n}\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nfunction isSwapsDefaultTokenAddress(address: string, chainId: string): boolean {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.address\n );\n}\n\n/**\n * Sleeps for the provided number of milliseconds\n *\n * @param ms - Number of milliseconds to sleep\n * @returns Promise that resolves after the provided number of milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
package/dist/utils/swaps.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-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AU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { merge, pickBy } from 'lodash';\n\nimport { validateIfTransactionUnapproved } from './utils';\nimport { CHAIN_IDS } from '../constants';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'swaps');\n\n/**\n * Interval in milliseconds between checks of post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;\n\n/**\n * Retry attempts for checking post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;\n\nconst SWAPS_TESTNET_CHAIN_ID = '0x539';\n\n/**\n * An address that the metaswap-api recognizes as the default token for the current network, in place of the token address that ERC-20 tokens have\n */\nexport const DEFAULT_TOKEN_ADDRESS =\n '0x0000000000000000000000000000000000000000';\n\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface SwapsTokenObject {\n /**\n * The name for the network\n */\n name: string;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n}\n\nconst ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n};\n\nconst BNB_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Binance Coin',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MATIC_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Matic',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst AVAX_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Avalanche',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst TEST_ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Test Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst GOERLI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst ARBITRUM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst OPTIMISM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst ZKSYNC_ERA_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst SEI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Sei',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MONAD_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Mon',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nexport const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {\n [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,\n [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.SEI]: SEI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.MONAD]: MONAD_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapAndSend,\n TransactionType.swapApproval,\n];\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - The transaction meta object to update\n * @param transactionType - The type of the transaction\n * @param swaps - The swaps object\n * @param swaps.hasApproveTx - Whether the swap has an approval transaction\n * @param swaps.meta - The swap meta object\n * @param updateSwapsTransactionRequest - Dependency bag\n * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled\n * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction\n * @param updateSwapsTransactionRequest.messenger - TransactionController messenger\n * @returns A copy of the transaction meta object with updates, or the same\n * transaction meta object if no updates were made.\n */\nexport function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n messenger,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n messenger: TransactionControllerMessenger;\n },\n): TransactionMeta {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return transactionMeta;\n }\n\n // The simulationFails property is added if the estimateGas call fails. In cases\n // when no swaps approval tx is required, this indicates that the swap will likely\n // fail. There was an earlier estimateGas call made by the swaps controller,\n // but it is possible that external conditions have change since then, and\n // a previously succeeding estimate gas call could now fail. By checking for\n // the `simulationFails` property here, we can reduce the number of swap\n // transactions that get published to the blockchain only to fail and thereby\n // waste the user's funds on gas.\n if (\n transactionType === TransactionType.swap &&\n swaps?.hasApproveTx === false &&\n transactionMeta.simulationFails\n ) {\n cancelTransaction(transactionMeta.id);\n throw new Error('Simulation failed');\n }\n\n const swapsMeta = swaps?.meta as Partial<TransactionMeta>;\n\n if (!swapsMeta) {\n return transactionMeta;\n }\n\n let updatedTransactionMeta = transactionMeta;\n\n if (transactionType === TransactionType.swapApproval) {\n updatedTransactionMeta = updateSwapApprovalTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapApproval', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swapAndSend) {\n updatedTransactionMeta = updateSwapAndSendTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapAndSend', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updatedTransactionMeta = updateSwapTransaction(transactionMeta, swapsMeta);\n messenger.publish('TransactionController:transactionNewSwap', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n return updatedTransactionMeta;\n}\n\n/**\n * Attempts to update the post transaction balance of the provided transaction\n *\n * @param transactionMeta - Transaction meta object to update\n * @param updatePostTransactionBalanceRequest - Dependency bag\n * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object\n * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state\n * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function\n * @returns Updated transaction metadata and approval transaction metadata if applicable.\n */\nexport async function updatePostTransactionBalance(\n transactionMeta: TransactionMeta,\n {\n ethQuery,\n getTransaction,\n updateTransaction,\n }: {\n ethQuery: EthQuery;\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;\n },\n): Promise<{\n updatedTransactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n}> {\n log('Updating post transaction balance', transactionMeta.id);\n\n const transactionId = transactionMeta.id;\n let latestTransactionMeta: TransactionMeta | undefined;\n let approvalTransactionMeta;\n\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n log('Querying balance', { attempt: i });\n\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n\n latestTransactionMeta = {\n ...(getTransaction(transactionId) ?? ({} as TransactionMeta)),\n };\n\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n\n const isDefaultTokenAddress = isSwapsDefaultTokenAddress(\n transactionMeta.destinationTokenAddress as string,\n transactionMeta.chainId,\n );\n\n if (\n !isDefaultTokenAddress ||\n transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance\n ) {\n log('Finishing post balance update', {\n isDefaultTokenAddress,\n preTxBalance: transactionMeta.preTxBalance,\n postTxBalance: latestTransactionMeta.postTxBalance,\n });\n\n break;\n }\n\n log('Waiting for balance to update', {\n delay: UPDATE_POST_TX_BALANCE_TIMEOUT,\n });\n\n await sleep(UPDATE_POST_TX_BALANCE_TIMEOUT);\n }\n\n updateTransaction(\n latestTransactionMeta as TransactionMeta,\n 'TransactionController#updatePostTransactionBalance - Add post transaction balance',\n );\n\n log('Completed post balance update', latestTransactionMeta?.postTxBalance);\n\n return {\n updatedTransactionMeta: latestTransactionMeta as TransactionMeta,\n approvalTransactionMeta,\n };\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapTransaction(\n transactionMeta: TransactionMeta,\n {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.destinationTokenAmount - The raw amount of the destination token\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.sourceTokenAddress - The address of the source token\n * @param propsToUpdate.sourceTokenAmount - The raw amount of the source token\n * @param propsToUpdate.sourceTokenDecimals - The decimals of the source token\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.swapAndSendRecipient - The recipient of the swap and send transaction\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped – possibly the same as sourceTokenAmount; included for consistency\n * @param propsToUpdate.type - Type of the transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapAndSendTransaction(\n transactionMeta: TransactionMeta,\n {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap approval information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @returns The updated transaction meta object.\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n\n return merge({}, transactionMeta, swapApprovalTransaction);\n}\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nfunction isSwapsDefaultTokenAddress(address: string, chainId: string) {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.address\n );\n}\n\n/**\n * Sleeps for the provided number of milliseconds\n *\n * @param ms - Number of milliseconds to sleep\n * @returns Promise that resolves after the provided number of milliseconds\n */\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"swaps.mjs","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,mCAAmC;;;AAInD,OAAO,EAAE,+BAA+B,EAAE,oBAAgB;AAC1D,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,sBAAkB;AAG9D,OAAO,EAAE,eAAe,EAAE,qBAAiB;AAE3C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAAG,CAAC,CAAC;AAEjD,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAChC,4CAA4C,CAAC;AAmB/C,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,EAAE;CACb,CAAC;AAEF,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,cAAc;IACpB,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,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ACJ,iBAAiB;KAClB,CAA6B,CAAC;IAE/B,OAAO,KAAK,CAAC,EAAE,EAAE,eAAe,EAAE,uBAAuB,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,0BAA0B,CAAC,OAAe,EAAE,OAAe;IAClE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CACL,OAAO;QACP,+BAA+B,CAC7B,OAAuD,CACxD,EAAE,OAAO,CACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { merge, pickBy } from 'lodash';\n\nimport { validateIfTransactionUnapproved } from './utils';\nimport { CHAIN_IDS } from '../constants';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'swaps');\n\n/**\n * Interval in milliseconds between checks of post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;\n\n/**\n * Retry attempts for checking post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;\n\nconst SWAPS_TESTNET_CHAIN_ID = '0x539';\n\n/**\n * An address that the metaswap-api recognizes as the default token for the current network, in place of the token address that ERC-20 tokens have\n */\nexport const DEFAULT_TOKEN_ADDRESS =\n '0x0000000000000000000000000000000000000000';\n\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface SwapsTokenObject {\n /**\n * The name for the network\n */\n name: string;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n}\n\nconst ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n};\n\nconst BNB_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Binance Coin',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MATIC_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Matic',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst AVAX_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Avalanche',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst TEST_ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Test Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst GOERLI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst ARBITRUM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst OPTIMISM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst ZKSYNC_ERA_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst SEI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Sei',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MONAD_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Mon',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nexport const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {\n [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,\n [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.SEI]: SEI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.MONAD]: MONAD_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapAndSend,\n TransactionType.swapApproval,\n];\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - The transaction meta object to update\n * @param transactionType - The type of the transaction\n * @param swaps - The swaps object\n * @param swaps.hasApproveTx - Whether the swap has an approval transaction\n * @param swaps.meta - The swap meta object\n * @param updateSwapsTransactionRequest - Dependency bag\n * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled\n * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction\n * @param updateSwapsTransactionRequest.messenger - TransactionController messenger\n * @returns A copy of the transaction meta object with updates, or the same\n * transaction meta object if no updates were made.\n */\nexport function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n messenger,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n messenger: TransactionControllerMessenger;\n },\n): TransactionMeta {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return transactionMeta;\n }\n\n // The simulationFails property is added if the estimateGas call fails. In cases\n // when no swaps approval tx is required, this indicates that the swap will likely\n // fail. There was an earlier estimateGas call made by the swaps controller,\n // but it is possible that external conditions have change since then, and\n // a previously succeeding estimate gas call could now fail. By checking for\n // the `simulationFails` property here, we can reduce the number of swap\n // transactions that get published to the blockchain only to fail and thereby\n // waste the user's funds on gas.\n if (\n transactionType === TransactionType.swap &&\n swaps?.hasApproveTx === false &&\n transactionMeta.simulationFails\n ) {\n cancelTransaction(transactionMeta.id);\n throw new Error('Simulation failed');\n }\n\n const swapsMeta = swaps?.meta as Partial<TransactionMeta>;\n\n if (!swapsMeta) {\n return transactionMeta;\n }\n\n let updatedTransactionMeta = transactionMeta;\n\n if (transactionType === TransactionType.swapApproval) {\n updatedTransactionMeta = updateSwapApprovalTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapApproval', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swapAndSend) {\n updatedTransactionMeta = updateSwapAndSendTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapAndSend', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updatedTransactionMeta = updateSwapTransaction(transactionMeta, swapsMeta);\n messenger.publish('TransactionController:transactionNewSwap', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n return updatedTransactionMeta;\n}\n\n/**\n * Attempts to update the post transaction balance of the provided transaction\n *\n * @param transactionMeta - Transaction meta object to update\n * @param updatePostTransactionBalanceRequest - Dependency bag\n * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object\n * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state\n * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function\n * @returns Updated transaction metadata and approval transaction metadata if applicable.\n */\nexport async function updatePostTransactionBalance(\n transactionMeta: TransactionMeta,\n {\n ethQuery,\n getTransaction,\n updateTransaction,\n }: {\n ethQuery: EthQuery;\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;\n },\n): Promise<{\n updatedTransactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n}> {\n log('Updating post transaction balance', transactionMeta.id);\n\n const transactionId = transactionMeta.id;\n let latestTransactionMeta: TransactionMeta | undefined;\n let approvalTransactionMeta;\n\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n log('Querying balance', { attempt: i });\n\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n\n latestTransactionMeta = {\n ...(getTransaction(transactionId) ?? ({} as TransactionMeta)),\n };\n\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n\n const isDefaultTokenAddress = isSwapsDefaultTokenAddress(\n transactionMeta.destinationTokenAddress as string,\n transactionMeta.chainId,\n );\n\n if (\n !isDefaultTokenAddress ||\n transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance\n ) {\n log('Finishing post balance update', {\n isDefaultTokenAddress,\n preTxBalance: transactionMeta.preTxBalance,\n postTxBalance: latestTransactionMeta.postTxBalance,\n });\n\n break;\n }\n\n log('Waiting for balance to update', {\n delay: UPDATE_POST_TX_BALANCE_TIMEOUT,\n });\n\n await sleep(UPDATE_POST_TX_BALANCE_TIMEOUT);\n }\n\n updateTransaction(\n latestTransactionMeta as TransactionMeta,\n 'TransactionController#updatePostTransactionBalance - Add post transaction balance',\n );\n\n log('Completed post balance update', latestTransactionMeta?.postTxBalance);\n\n return {\n updatedTransactionMeta: latestTransactionMeta as TransactionMeta,\n approvalTransactionMeta,\n };\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapTransaction(\n transactionMeta: TransactionMeta,\n {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.destinationTokenAmount - The raw amount of the destination token\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.sourceTokenAddress - The address of the source token\n * @param propsToUpdate.sourceTokenAmount - The raw amount of the source token\n * @param propsToUpdate.sourceTokenDecimals - The decimals of the source token\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.swapAndSendRecipient - The recipient of the swap and send transaction\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped – possibly the same as sourceTokenAmount; included for consistency\n * @param propsToUpdate.type - Type of the transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapAndSendTransaction(\n transactionMeta: TransactionMeta,\n {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap approval information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @returns The updated transaction meta object.\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n\n return merge({}, transactionMeta, swapApprovalTransaction);\n}\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nfunction isSwapsDefaultTokenAddress(address: string, chainId: string): boolean {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.address\n );\n}\n\n/**\n * Sleeps for the provided number of milliseconds\n *\n * @param ms - Number of milliseconds to sleep\n * @returns Promise that resolves after the provided number of milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
package/dist/utils/utils.cjs
CHANGED
|
@@ -39,9 +39,7 @@ function normalizeTransactionParams(txParams) {
|
|
|
39
39
|
normalizedTxParams[key] = NORMALIZERS[key](txParams[key]);
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
|
-
|
|
43
|
-
normalizedTxParams.value = '0x0';
|
|
44
|
-
}
|
|
42
|
+
normalizedTxParams.value ?? (normalizedTxParams.value = '0x0');
|
|
45
43
|
if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {
|
|
46
44
|
normalizedTxParams.gas = normalizedTxParams.gasLimit;
|
|
47
45
|
}
|
|
@@ -141,12 +139,14 @@ function isJsonCompatible(value) {
|
|
|
141
139
|
* Ensure a hex string is of even length by adding a leading 0 if necessary.
|
|
142
140
|
* Any existing `0x` prefix is preserved but is not added if missing.
|
|
143
141
|
*
|
|
144
|
-
* @param
|
|
142
|
+
* @param hexValue - The hex string to ensure is even.
|
|
145
143
|
* @returns The hex string with an even length.
|
|
146
144
|
*/
|
|
147
|
-
function padHexToEvenLength(
|
|
148
|
-
const prefix =
|
|
149
|
-
|
|
145
|
+
function padHexToEvenLength(hexValue) {
|
|
146
|
+
const prefix = hexValue.toLowerCase().startsWith('0x')
|
|
147
|
+
? hexValue.slice(0, 2)
|
|
148
|
+
: '';
|
|
149
|
+
const data = prefix ? hexValue.slice(2) : hexValue;
|
|
150
150
|
const evenData = data.length % 2 === 0 ? data : `0${data}`;
|
|
151
151
|
return prefix + evenData;
|
|
152
152
|
}
|
|
@@ -154,11 +154,11 @@ exports.padHexToEvenLength = padHexToEvenLength;
|
|
|
154
154
|
/**
|
|
155
155
|
* Create a BN from a hex string, accepting an optional 0x prefix.
|
|
156
156
|
*
|
|
157
|
-
* @param
|
|
157
|
+
* @param hexValue - Hex string with or without 0x prefix.
|
|
158
158
|
* @returns BN parsed as base-16.
|
|
159
159
|
*/
|
|
160
|
-
function bnFromHex(
|
|
161
|
-
const str = typeof
|
|
160
|
+
function bnFromHex(hexValue) {
|
|
161
|
+
const str = typeof hexValue === 'string' ? hexValue : hexValue;
|
|
162
162
|
const withoutPrefix = str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;
|
|
163
163
|
if (withoutPrefix.length === 0) {
|
|
164
164
|
return new bn_js_1.default(0);
|