@metamask/transaction-controller 56.3.0 → 57.1.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 +18 -55
- package/dist/TransactionController.cjs.map +1 -1
- package/dist/TransactionController.d.cts.map +1 -1
- package/dist/TransactionController.d.mts.map +1 -1
- package/dist/TransactionController.mjs +21 -58
- package/dist/TransactionController.mjs.map +1 -1
- package/dist/api/simulation-api.cjs.map +1 -1
- package/dist/api/simulation-api.d.cts +22 -5
- package/dist/api/simulation-api.d.cts.map +1 -1
- package/dist/api/simulation-api.d.mts +22 -5
- package/dist/api/simulation-api.d.mts.map +1 -1
- package/dist/api/simulation-api.mjs.map +1 -1
- package/dist/hooks/ExtraTransactionsPublishHook.cjs +3 -1
- package/dist/hooks/ExtraTransactionsPublishHook.cjs.map +1 -1
- package/dist/hooks/ExtraTransactionsPublishHook.d.cts.map +1 -1
- package/dist/hooks/ExtraTransactionsPublishHook.d.mts.map +1 -1
- package/dist/hooks/ExtraTransactionsPublishHook.mjs +3 -1
- package/dist/hooks/ExtraTransactionsPublishHook.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +23 -4
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +23 -4
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/{simulation.cjs → balance-changes.cjs} +103 -112
- package/dist/utils/balance-changes.cjs.map +1 -0
- package/dist/utils/balance-changes.d.cts +30 -0
- package/dist/utils/balance-changes.d.cts.map +1 -0
- package/dist/utils/balance-changes.d.mts +30 -0
- package/dist/utils/balance-changes.d.mts.map +1 -0
- package/dist/utils/{simulation.mjs → balance-changes.mjs} +107 -111
- package/dist/utils/balance-changes.mjs.map +1 -0
- package/dist/utils/batch.cjs +77 -35
- package/dist/utils/batch.cjs.map +1 -1
- package/dist/utils/batch.d.cts +1 -0
- package/dist/utils/batch.d.cts.map +1 -1
- package/dist/utils/batch.d.mts +1 -0
- package/dist/utils/batch.d.mts.map +1 -1
- package/dist/utils/batch.mjs +78 -36
- package/dist/utils/batch.mjs.map +1 -1
- package/dist/utils/gas-fee-tokens.cjs +123 -0
- package/dist/utils/gas-fee-tokens.cjs.map +1 -0
- package/dist/utils/gas-fee-tokens.d.cts +22 -0
- package/dist/utils/gas-fee-tokens.d.cts.map +1 -0
- package/dist/utils/gas-fee-tokens.d.mts +22 -0
- package/dist/utils/gas-fee-tokens.d.mts.map +1 -0
- package/dist/utils/gas-fee-tokens.mjs +119 -0
- package/dist/utils/gas-fee-tokens.mjs.map +1 -0
- package/dist/utils/gas.cjs +40 -1
- package/dist/utils/gas.cjs.map +1 -1
- package/dist/utils/gas.d.cts +17 -0
- package/dist/utils/gas.d.cts.map +1 -1
- package/dist/utils/gas.d.mts +17 -0
- package/dist/utils/gas.d.mts.map +1 -1
- package/dist/utils/gas.mjs +38 -0
- package/dist/utils/gas.mjs.map +1 -1
- package/package.json +4 -4
- package/dist/utils/simulation.cjs.map +0 -1
- package/dist/utils/simulation.d.cts +0 -60
- package/dist/utils/simulation.d.cts.map +0 -1
- package/dist/utils/simulation.d.mts +0 -60
- package/dist/utils/simulation.d.mts.map +0 -1
- package/dist/utils/simulation.mjs.map +0 -1
package/dist/utils/gas.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas.cjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";;;AAAA,iEAMoC;AAGpC,2CAAsE;AAEtE,2CAA8C;AAC9C,uDAA+E;AAC/E,8DAA6D;AAC7D,0CAA0C;AAE1C,wCAIkB;AAWL,QAAA,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,KAAK,CAAC,CAAC;AAE/C,QAAA,SAAS,GAAG,QAAQ,CAAC;AACrB,QAAA,sBAAsB,GAAG,GAAG,CAAC;AAC7B,QAAA,qBAAqB,GAAG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AE,WAAW,CAAC,IAAW;gBAC7B,KAAK,EAAE,WAAW,CAAC,KAAY;aAChC;SACF;QACD,SAAS,EAAE;YACT,CAAC,WAAW,CAAC,IAAc,CAAC,EAAE;gBAC5B,IAAI,EACF,iBAAiB;oBAChB,CAAC,2BAAiB,GAAG,IAAA,gBAAQ,EAAC,iBAAiB,CAAC,CAAS;aAC7D;SACF;KACF,CAAC,CAAC;IAEH,MAAM,QAAQ,GAAG,QAAQ,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;IAEtD,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;KAC9C;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,0BAA0B,CACjC,iBAAyD,EACzD,OAAY;IAEZ,OAAO,iBAAiB,EAAE,GAAG,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC;QAChD,GAAG,aAAa;QAChB,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,OAAO;QACzC,KAAK,EAAE,aAAa,CAAC,KAAK,IAAI,KAAK;QACnC,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,qCAA6B;QACnD,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,qCAA6B;QACnD,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,KAAK;KACxC,CAAC,CAAC,CAAC;AACN,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 } from '@metamask/utils';\nimport { add0x, createModuleLogger, remove0x } from '@metamask/utils';\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 {\n TransactionEnvelopeType,\n type TransactionMeta,\n type TransactionParams,\n} from '../types';\n\nexport type UpdateGasRequest = {\n chainId: Hex;\n ethQuery: EthQuery;\n isCustomNetwork: boolean;\n isSimulationEnabled: boolean;\n 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.isSimulationEnabled - Whether the simulation is enabled.\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 isSimulationEnabled,\n messenger,\n txParams,\n}: {\n chainId: Hex;\n ethQuery: EthQuery;\n isSimulationEnabled: boolean;\n messenger: TransactionControllerMessenger;\n txParams: TransactionParams;\n}) {\n const request = { ...txParams };\n const { authorizationList, data, from, value, to } = request;\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 );\n } else {\n estimatedGas = await query(ethQuery, 'estimateGas', [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 * 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 { chainId, isCustomNetwork, isSimulationEnabled, messenger, 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: request.chainId,\n ethQuery: request.ethQuery,\n isSimulationEnabled,\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 * @returns The estimated gas.\n */\nasync function estimateGasUpgradeWithDataToSelf(\n txParams: TransactionParams,\n ethQuery: EthQuery,\n chainId: Hex,\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 const executeGas = await simulateGas({\n chainId: chainId as Hex,\n delegationAddress,\n transaction: txParams,\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.transaction - The transaction parameters.\n * @returns The simulated gas.\n */\nasync function simulateGas({\n chainId,\n delegationAddress,\n transaction,\n}: {\n chainId: Hex;\n delegationAddress?: Hex;\n transaction: TransactionParams;\n}): Promise<Hex> {\n const response = await simulateTransactions(chainId, {\n transactions: [\n {\n to: transaction.to as Hex,\n from: transaction.from as Hex,\n data: transaction.data as Hex,\n value: transaction.value as Hex,\n },\n ],\n overrides: {\n [transaction.from as string]: {\n code:\n delegationAddress &&\n ((DELEGATION_PREFIX + remove0x(delegationAddress)) as Hex),\n },\n },\n });\n\n const gasLimit = response?.transactions?.[0].gasLimit;\n\n if (!gasLimit) {\n throw new Error('No simulated gas returned');\n }\n\n return gasLimit;\n}\n\n/**\n * Populate the authorization list with dummy values.\n *\n * @param authorizationList - The authorization list to prepare.\n * @param chainId - The chain ID to use.\n * @returns The authorization list with dummy values.\n */\nfunction normalizeAuthorizationList(\n authorizationList: TransactionParams['authorizationList'],\n chainId: Hex,\n) {\n return authorizationList?.map((authorization) => ({\n ...authorization,\n chainId: authorization.chainId ?? chainId,\n nonce: authorization.nonce ?? '0x1',\n r: authorization.r ?? DUMMY_AUTHORIZATION_SIGNATURE,\n s: authorization.s ?? DUMMY_AUTHORIZATION_SIGNATURE,\n yParity: authorization.yParity ?? '0x1',\n }));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gas.cjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";;;AAAA,iEAMoC;AAGpC,2CAAsE;AACtE,iCAA2B;AAE3B,2CAA8C;AAC9C,uDAA+E;AAC/E,8DAA6D;AAC7D,0CAA0C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E,WAAW,CAAC,EAAS;gBACzB,IAAI,EAAE,WAAW,CAAC,IAAW;gBAC7B,IAAI,EAAE,WAAW,CAAC,IAAW;gBAC7B,KAAK,EAAE,WAAW,CAAC,KAAY;aAChC;SACF;QACD,SAAS,EAAE;YACT,CAAC,WAAW,CAAC,IAAc,CAAC,EAAE;gBAC5B,IAAI,EACF,iBAAiB;oBAChB,CAAC,2BAAiB,GAAG,IAAA,gBAAQ,EAAC,iBAAiB,CAAC,CAAS;aAC7D;SACF;KACF,CAAC,CAAC;IAEH,MAAM,QAAQ,GAAG,QAAQ,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;IAEtD,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;KAC9C;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,0BAA0B,CACjC,iBAAyD,EACzD,OAAY;IAEZ,OAAO,iBAAiB,EAAE,GAAG,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC;QAChD,GAAG,aAAa;QAChB,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,OAAO;QACzC,KAAK,EAAE,aAAa,CAAC,KAAK,IAAI,KAAK;QACnC,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,qCAA6B;QACnD,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,qCAA6B;QACnD,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,KAAK;KACxC,CAAC,CAAC,CAAC;AACN,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 } from '@metamask/utils';\nimport { add0x, createModuleLogger, remove0x } from '@metamask/utils';\nimport { BN } from 'bn.js';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport { getGasEstimateBuffer, getGasEstimateFallback } from './feature-flags';\nimport { simulateTransactions } from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionBatchSingleRequest } from '../types';\nimport {\n TransactionEnvelopeType,\n type TransactionMeta,\n type TransactionParams,\n} from '../types';\n\nexport type UpdateGasRequest = {\n chainId: Hex;\n ethQuery: EthQuery;\n isCustomNetwork: boolean;\n isSimulationEnabled: boolean;\n 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.isSimulationEnabled - Whether the simulation is enabled.\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 isSimulationEnabled,\n messenger,\n txParams,\n}: {\n chainId: Hex;\n ethQuery: EthQuery;\n isSimulationEnabled: boolean;\n messenger: TransactionControllerMessenger;\n txParams: TransactionParams;\n}) {\n const request = { ...txParams };\n const { authorizationList, data, from, value, to } = request;\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 );\n } else {\n estimatedGas = await query(ethQuery, 'estimateGas', [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.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 transactions,\n}: {\n chainId: Hex;\n from: Hex;\n transactions: TransactionBatchSingleRequest[];\n}): Promise<{ gasLimit: Hex }> {\n try {\n const response = await simulateTransactions(chainId, {\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 { chainId, isCustomNetwork, isSimulationEnabled, messenger, 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: request.chainId,\n ethQuery: request.ethQuery,\n isSimulationEnabled,\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 * @returns The estimated gas.\n */\nasync function estimateGasUpgradeWithDataToSelf(\n txParams: TransactionParams,\n ethQuery: EthQuery,\n chainId: Hex,\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 const executeGas = await simulateGas({\n chainId: chainId as Hex,\n delegationAddress,\n transaction: txParams,\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.transaction - The transaction parameters.\n * @returns The simulated gas.\n */\nasync function simulateGas({\n chainId,\n delegationAddress,\n transaction,\n}: {\n chainId: Hex;\n delegationAddress?: Hex;\n transaction: TransactionParams;\n}): Promise<Hex> {\n const response = await simulateTransactions(chainId, {\n transactions: [\n {\n to: transaction.to as Hex,\n from: transaction.from as Hex,\n data: transaction.data as Hex,\n value: transaction.value as Hex,\n },\n ],\n overrides: {\n [transaction.from as string]: {\n code:\n delegationAddress &&\n ((DELEGATION_PREFIX + remove0x(delegationAddress)) as Hex),\n },\n },\n });\n\n const gasLimit = response?.transactions?.[0].gasLimit;\n\n if (!gasLimit) {\n throw new Error('No simulated gas returned');\n }\n\n return gasLimit;\n}\n\n/**\n * Populate the authorization list with dummy values.\n *\n * @param authorizationList - The authorization list to prepare.\n * @param chainId - The chain ID to use.\n * @returns The authorization list with dummy values.\n */\nfunction normalizeAuthorizationList(\n authorizationList: TransactionParams['authorizationList'],\n chainId: Hex,\n) {\n return authorizationList?.map((authorization) => ({\n ...authorization,\n chainId: authorization.chainId ?? chainId,\n nonce: authorization.nonce ?? '0x1',\n r: authorization.r ?? DUMMY_AUTHORIZATION_SIGNATURE,\n s: authorization.s ?? DUMMY_AUTHORIZATION_SIGNATURE,\n yParity: authorization.yParity ?? '0x1',\n }));\n}\n"]}
|
package/dist/utils/gas.d.cts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import type EthQuery from "@metamask/eth-query";
|
|
3
3
|
import type { Hex } from "@metamask/utils";
|
|
4
4
|
import type { TransactionControllerMessenger } from "../TransactionController.cjs";
|
|
5
|
+
import type { TransactionBatchSingleRequest } from "../types.cjs";
|
|
5
6
|
import { type TransactionMeta, type TransactionParams } from "../types.cjs";
|
|
6
7
|
export type UpdateGasRequest = {
|
|
7
8
|
chainId: Hex;
|
|
@@ -64,4 +65,20 @@ export declare function estimateGas({ chainId, ethQuery, isSimulationEnabled, me
|
|
|
64
65
|
* @returns The gas with the buffer applied.
|
|
65
66
|
*/
|
|
66
67
|
export declare function addGasBuffer(estimatedGas: string, blockGasLimit: string, multiplier: number): `0x${string}`;
|
|
68
|
+
/**
|
|
69
|
+
* Simulate the required gas for a batch of transactions using the simulation API.
|
|
70
|
+
*
|
|
71
|
+
* @param options - The options object.
|
|
72
|
+
* @param options.chainId - The chain ID of the transactions.
|
|
73
|
+
* @param options.from - The address of the sender.
|
|
74
|
+
* @param options.transactions - The array of transactions within a batch request.
|
|
75
|
+
* @returns An object containing the transactions with their gas limits and the total gas limit.
|
|
76
|
+
*/
|
|
77
|
+
export declare function simulateGasBatch({ chainId, from, transactions, }: {
|
|
78
|
+
chainId: Hex;
|
|
79
|
+
from: Hex;
|
|
80
|
+
transactions: TransactionBatchSingleRequest[];
|
|
81
|
+
}): Promise<{
|
|
82
|
+
gasLimit: Hex;
|
|
83
|
+
}>;
|
|
67
84
|
//# sourceMappingURL=gas.d.cts.map
|
package/dist/utils/gas.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas.d.cts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";AAOA,OAAO,KAAK,QAAQ,4BAA4B;AAChD,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;
|
|
1
|
+
{"version":3,"file":"gas.d.cts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";AAOA,OAAO,KAAK,QAAQ,4BAA4B;AAChD,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAQ3C,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAC/E,OAAO,KAAK,EAAE,6BAA6B,EAAE,qBAAiB;AAC9D,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACvB,qBAAiB;AAElB,MAAM,MAAM,gBAAgB,GAAG;IAC7B,OAAO,EAAE,GAAG,CAAC;IACb,QAAQ,EAAE,QAAQ,CAAC;IACnB,eAAe,EAAE,OAAO,CAAC;IACzB,mBAAmB,EAAE,OAAO,CAAC;IAC7B,SAAS,EAAE,8BAA8B,CAAC;IAC1C,MAAM,EAAE,eAAe,CAAC;CACzB,CAAC;AAEF,eAAO,MAAM,GAAG,0BAA2C,CAAC;AAE5D,eAAO,MAAM,SAAS,WAAW,CAAC;AAClC,eAAO,MAAM,sBAAsB,MAAM,CAAC;AAC1C,eAAO,MAAM,qBAAqB,KAAK,CAAC;AACxC,eAAO,MAAM,aAAa,QAAQ,CAAC;AAEnC,eAAO,MAAM,6BAA6B,uEAC4B,CAAC;AAEvE;;;;GAIG;AACH,wBAAsB,SAAS,CAAC,OAAO,EAAE,gBAAgB,iBAmBxD;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,WAAW,CAAC,EAChC,OAAO,EACP,QAAQ,EACR,mBAAmB,EACnB,SAAS,EACT,QAAQ,GACT,EAAE;IACD,OAAO,EAAE,GAAG,CAAC;IACb,QAAQ,EAAE,QAAQ,CAAC;IACnB,mBAAmB,EAAE,OAAO,CAAC;IAC7B,SAAS,EAAE,8BAA8B,CAAC;IAC1C,QAAQ,EAAE,iBAAiB,CAAC;CAC7B;;;;;;;;;;;;GAoEA;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAC1B,YAAY,EAAE,MAAM,EACpB,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,MAAM,iBA2BnB;AAED;;;;;;;;GAQG;AACH,wBAAsB,gBAAgB,CAAC,EACrC,OAAO,EACP,IAAI,EACJ,YAAY,GACb,EAAE;IACD,OAAO,EAAE,GAAG,CAAC;IACb,IAAI,EAAE,GAAG,CAAC;IACV,YAAY,EAAE,6BAA6B,EAAE,CAAC;CAC/C,GAAG,OAAO,CAAC;IAAE,QAAQ,EAAE,GAAG,CAAA;CAAE,CAAC,CAqC7B"}
|
package/dist/utils/gas.d.mts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import type EthQuery from "@metamask/eth-query";
|
|
3
3
|
import type { Hex } from "@metamask/utils";
|
|
4
4
|
import type { TransactionControllerMessenger } from "../TransactionController.mjs";
|
|
5
|
+
import type { TransactionBatchSingleRequest } from "../types.mjs";
|
|
5
6
|
import { type TransactionMeta, type TransactionParams } from "../types.mjs";
|
|
6
7
|
export type UpdateGasRequest = {
|
|
7
8
|
chainId: Hex;
|
|
@@ -64,4 +65,20 @@ export declare function estimateGas({ chainId, ethQuery, isSimulationEnabled, me
|
|
|
64
65
|
* @returns The gas with the buffer applied.
|
|
65
66
|
*/
|
|
66
67
|
export declare function addGasBuffer(estimatedGas: string, blockGasLimit: string, multiplier: number): `0x${string}`;
|
|
68
|
+
/**
|
|
69
|
+
* Simulate the required gas for a batch of transactions using the simulation API.
|
|
70
|
+
*
|
|
71
|
+
* @param options - The options object.
|
|
72
|
+
* @param options.chainId - The chain ID of the transactions.
|
|
73
|
+
* @param options.from - The address of the sender.
|
|
74
|
+
* @param options.transactions - The array of transactions within a batch request.
|
|
75
|
+
* @returns An object containing the transactions with their gas limits and the total gas limit.
|
|
76
|
+
*/
|
|
77
|
+
export declare function simulateGasBatch({ chainId, from, transactions, }: {
|
|
78
|
+
chainId: Hex;
|
|
79
|
+
from: Hex;
|
|
80
|
+
transactions: TransactionBatchSingleRequest[];
|
|
81
|
+
}): Promise<{
|
|
82
|
+
gasLimit: Hex;
|
|
83
|
+
}>;
|
|
67
84
|
//# sourceMappingURL=gas.d.mts.map
|
package/dist/utils/gas.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas.d.mts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";AAOA,OAAO,KAAK,QAAQ,4BAA4B;AAChD,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;
|
|
1
|
+
{"version":3,"file":"gas.d.mts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";AAOA,OAAO,KAAK,QAAQ,4BAA4B;AAChD,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAQ3C,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAC/E,OAAO,KAAK,EAAE,6BAA6B,EAAE,qBAAiB;AAC9D,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACvB,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AC,CAqC7B"}
|
package/dist/utils/gas.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { BNToHex, fractionBN, hexToBN, query, toHex } from "@metamask/controller-utils";
|
|
2
2
|
import { add0x, createModuleLogger, remove0x } from "@metamask/utils";
|
|
3
|
+
import { BN } from "bn.js";
|
|
3
4
|
import { DELEGATION_PREFIX } from "./eip7702.mjs";
|
|
4
5
|
import { getGasEstimateBuffer, getGasEstimateFallback } from "./feature-flags.mjs";
|
|
5
6
|
import { simulateTransactions } from "../api/simulation-api.mjs";
|
|
@@ -120,6 +121,43 @@ export function addGasBuffer(estimatedGas, blockGasLimit, multiplier) {
|
|
|
120
121
|
log('Using 90% of block gas limit', maxHex);
|
|
121
122
|
return maxHex;
|
|
122
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* Simulate the required gas for a batch of transactions using the simulation API.
|
|
126
|
+
*
|
|
127
|
+
* @param options - The options object.
|
|
128
|
+
* @param options.chainId - The chain ID of the transactions.
|
|
129
|
+
* @param options.from - The address of the sender.
|
|
130
|
+
* @param options.transactions - The array of transactions within a batch request.
|
|
131
|
+
* @returns An object containing the transactions with their gas limits and the total gas limit.
|
|
132
|
+
*/
|
|
133
|
+
export async function simulateGasBatch({ chainId, from, transactions, }) {
|
|
134
|
+
try {
|
|
135
|
+
const response = await simulateTransactions(chainId, {
|
|
136
|
+
transactions: transactions.map((transaction) => ({
|
|
137
|
+
...transaction.params,
|
|
138
|
+
from,
|
|
139
|
+
})),
|
|
140
|
+
});
|
|
141
|
+
if (!response?.transactions ||
|
|
142
|
+
response.transactions.length !== transactions.length) {
|
|
143
|
+
throw new Error('Simulation response does not match transaction count');
|
|
144
|
+
}
|
|
145
|
+
const totalGasLimit = response.transactions.reduce((acc, transaction) => {
|
|
146
|
+
const gasLimit = transaction?.gasLimit;
|
|
147
|
+
if (!gasLimit) {
|
|
148
|
+
throw new Error('No simulated gas returned for one of the transactions');
|
|
149
|
+
}
|
|
150
|
+
return acc.add(hexToBN(gasLimit));
|
|
151
|
+
}, new BN(0));
|
|
152
|
+
return {
|
|
153
|
+
gasLimit: BNToHex(totalGasLimit), // Return the total gas limit as a hex string
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
log('Error while simulating gas batch', error);
|
|
158
|
+
throw new Error('Cannot estimate transaction batch total gas as simulation failed');
|
|
159
|
+
}
|
|
160
|
+
}
|
|
123
161
|
/**
|
|
124
162
|
* Determine the gas for the provided request.
|
|
125
163
|
*
|
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;AAEtE,OAAO,EAAE,iBAAiB,EAAE,sBAAkB;AAC9C,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,4BAAwB;AAC/E,OAAO,EAAE,oBAAoB,EAAE,kCAA8B;AAC7D,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAE1C,OAAO,EACL,uBAAuB,EAGxB,qBAAiB;AAWlB,MAAM,CAAC,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;AAE5D,MAAM,CAAC,MAAM,SAAS,GAAG,QAAQ,CAAC;AAClC,MAAM,CAAC,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAC1C,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,CAAC;AACxC,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,CAAC;AAEnC,MAAM,CAAC,MAAM,6BAA6B,GACxC,oEAAoE,CAAC;AAEvE;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,OAAyB;IACvD,MA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AC;AAClB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,0BAA0B,CACjC,iBAAyD,EACzD,OAAY;IAEZ,OAAO,iBAAiB,EAAE,GAAG,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC;QAChD,GAAG,aAAa;QAChB,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,OAAO;QACzC,KAAK,EAAE,aAAa,CAAC,KAAK,IAAI,KAAK;QACnC,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,6BAA6B;QACnD,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,6BAA6B;QACnD,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,KAAK;KACxC,CAAC,CAAC,CAAC;AACN,CAAC","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 } from '@metamask/utils';\nimport { add0x, createModuleLogger, remove0x } from '@metamask/utils';\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 {\n TransactionEnvelopeType,\n type TransactionMeta,\n type TransactionParams,\n} from '../types';\n\nexport type UpdateGasRequest = {\n chainId: Hex;\n ethQuery: EthQuery;\n isCustomNetwork: boolean;\n isSimulationEnabled: boolean;\n 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.isSimulationEnabled - Whether the simulation is enabled.\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 isSimulationEnabled,\n messenger,\n txParams,\n}: {\n chainId: Hex;\n ethQuery: EthQuery;\n isSimulationEnabled: boolean;\n messenger: TransactionControllerMessenger;\n txParams: TransactionParams;\n}) {\n const request = { ...txParams };\n const { authorizationList, data, from, value, to } = request;\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 );\n } else {\n estimatedGas = await query(ethQuery, 'estimateGas', [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 * 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 { chainId, isCustomNetwork, isSimulationEnabled, messenger, 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: request.chainId,\n ethQuery: request.ethQuery,\n isSimulationEnabled,\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 * @returns The estimated gas.\n */\nasync function estimateGasUpgradeWithDataToSelf(\n txParams: TransactionParams,\n ethQuery: EthQuery,\n chainId: Hex,\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 const executeGas = await simulateGas({\n chainId: chainId as Hex,\n delegationAddress,\n transaction: txParams,\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.transaction - The transaction parameters.\n * @returns The simulated gas.\n */\nasync function simulateGas({\n chainId,\n delegationAddress,\n transaction,\n}: {\n chainId: Hex;\n delegationAddress?: Hex;\n transaction: TransactionParams;\n}): Promise<Hex> {\n const response = await simulateTransactions(chainId, {\n transactions: [\n {\n to: transaction.to as Hex,\n from: transaction.from as Hex,\n data: transaction.data as Hex,\n value: transaction.value as Hex,\n },\n ],\n overrides: {\n [transaction.from as string]: {\n code:\n delegationAddress &&\n ((DELEGATION_PREFIX + remove0x(delegationAddress)) as Hex),\n },\n },\n });\n\n const gasLimit = response?.transactions?.[0].gasLimit;\n\n if (!gasLimit) {\n throw new Error('No simulated gas returned');\n }\n\n return gasLimit;\n}\n\n/**\n * Populate the authorization list with dummy values.\n *\n * @param authorizationList - The authorization list to prepare.\n * @param chainId - The chain ID to use.\n * @returns The authorization list with dummy values.\n */\nfunction normalizeAuthorizationList(\n authorizationList: TransactionParams['authorizationList'],\n chainId: Hex,\n) {\n return authorizationList?.map((authorization) => ({\n ...authorization,\n chainId: authorization.chainId ?? chainId,\n nonce: authorization.nonce ?? '0x1',\n r: authorization.r ?? DUMMY_AUTHORIZATION_SIGNATURE,\n s: authorization.s ?? DUMMY_AUTHORIZATION_SIGNATURE,\n yParity: authorization.yParity ?? '0x1',\n }));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gas.mjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EACP,UAAU,EACV,OAAO,EACP,KAAK,EACL,KAAK,EACN,mCAAmC;AAGpC,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,QAAQ,EAAE,wBAAwB;AACtE,OAAO,EAAE,EAAE,EAAE,cAAc;AAE3B,OAAO,EAAE,iBAAiB,EAAE,sBAAkB;AAC9C,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,4BAAwB;AAC/E,OAAO,EAAE,oBAAoB,EAAE,kCAA8B;AAC7D,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAG1C,OAAO,EACL,uBAAuB,EAGxB,qBAAiB;AAWlB,MAAM,CAAC,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;AAE5D,MAAM,CAAC,MAAM,SAAS,GAAG,QAAQ,CAAC;AAClC,MAAM,CAAC,MAA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D,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;KAC9C;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,0BAA0B,CACjC,iBAAyD,EACzD,OAAY;IAEZ,OAAO,iBAAiB,EAAE,GAAG,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC;QAChD,GAAG,aAAa;QAChB,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,OAAO;QACzC,KAAK,EAAE,aAAa,CAAC,KAAK,IAAI,KAAK;QACnC,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,6BAA6B;QACnD,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,6BAA6B;QACnD,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,KAAK;KACxC,CAAC,CAAC,CAAC;AACN,CAAC","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 } from '@metamask/utils';\nimport { add0x, createModuleLogger, remove0x } from '@metamask/utils';\nimport { BN } from 'bn.js';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport { getGasEstimateBuffer, getGasEstimateFallback } from './feature-flags';\nimport { simulateTransactions } from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionBatchSingleRequest } from '../types';\nimport {\n TransactionEnvelopeType,\n type TransactionMeta,\n type TransactionParams,\n} from '../types';\n\nexport type UpdateGasRequest = {\n chainId: Hex;\n ethQuery: EthQuery;\n isCustomNetwork: boolean;\n isSimulationEnabled: boolean;\n 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.isSimulationEnabled - Whether the simulation is enabled.\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 isSimulationEnabled,\n messenger,\n txParams,\n}: {\n chainId: Hex;\n ethQuery: EthQuery;\n isSimulationEnabled: boolean;\n messenger: TransactionControllerMessenger;\n txParams: TransactionParams;\n}) {\n const request = { ...txParams };\n const { authorizationList, data, from, value, to } = request;\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 );\n } else {\n estimatedGas = await query(ethQuery, 'estimateGas', [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.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 transactions,\n}: {\n chainId: Hex;\n from: Hex;\n transactions: TransactionBatchSingleRequest[];\n}): Promise<{ gasLimit: Hex }> {\n try {\n const response = await simulateTransactions(chainId, {\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 { chainId, isCustomNetwork, isSimulationEnabled, messenger, 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: request.chainId,\n ethQuery: request.ethQuery,\n isSimulationEnabled,\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 * @returns The estimated gas.\n */\nasync function estimateGasUpgradeWithDataToSelf(\n txParams: TransactionParams,\n ethQuery: EthQuery,\n chainId: Hex,\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 const executeGas = await simulateGas({\n chainId: chainId as Hex,\n delegationAddress,\n transaction: txParams,\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.transaction - The transaction parameters.\n * @returns The simulated gas.\n */\nasync function simulateGas({\n chainId,\n delegationAddress,\n transaction,\n}: {\n chainId: Hex;\n delegationAddress?: Hex;\n transaction: TransactionParams;\n}): Promise<Hex> {\n const response = await simulateTransactions(chainId, {\n transactions: [\n {\n to: transaction.to as Hex,\n from: transaction.from as Hex,\n data: transaction.data as Hex,\n value: transaction.value as Hex,\n },\n ],\n overrides: {\n [transaction.from as string]: {\n code:\n delegationAddress &&\n ((DELEGATION_PREFIX + remove0x(delegationAddress)) as Hex),\n },\n },\n });\n\n const gasLimit = response?.transactions?.[0].gasLimit;\n\n if (!gasLimit) {\n throw new Error('No simulated gas returned');\n }\n\n return gasLimit;\n}\n\n/**\n * Populate the authorization list with dummy values.\n *\n * @param authorizationList - The authorization list to prepare.\n * @param chainId - The chain ID to use.\n * @returns The authorization list with dummy values.\n */\nfunction normalizeAuthorizationList(\n authorizationList: TransactionParams['authorizationList'],\n chainId: Hex,\n) {\n return authorizationList?.map((authorization) => ({\n ...authorization,\n chainId: authorization.chainId ?? chainId,\n nonce: authorization.nonce ?? '0x1',\n r: authorization.r ?? DUMMY_AUTHORIZATION_SIGNATURE,\n s: authorization.s ?? DUMMY_AUTHORIZATION_SIGNATURE,\n yParity: authorization.yParity ?? '0x1',\n }));\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/transaction-controller",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "57.1.0",
|
|
4
4
|
"description": "Stores transactions alongside their periodically updated statuses and manages interactions such as approval and cancellation",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -70,14 +70,14 @@
|
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
72
|
"@babel/runtime": "^7.23.9",
|
|
73
|
-
"@metamask/accounts-controller": "^
|
|
73
|
+
"@metamask/accounts-controller": "^30.0.0",
|
|
74
74
|
"@metamask/approval-controller": "^7.1.3",
|
|
75
75
|
"@metamask/auto-changelog": "^3.4.4",
|
|
76
76
|
"@metamask/eth-block-tracker": "^12.0.1",
|
|
77
77
|
"@metamask/eth-json-rpc-provider": "^4.1.8",
|
|
78
78
|
"@metamask/ethjs-provider-http": "^0.3.0",
|
|
79
79
|
"@metamask/gas-fee-controller": "^23.0.0",
|
|
80
|
-
"@metamask/network-controller": "^23.5.
|
|
80
|
+
"@metamask/network-controller": "^23.5.1",
|
|
81
81
|
"@metamask/remote-feature-flag-controller": "^1.6.0",
|
|
82
82
|
"@types/bn.js": "^5.1.5",
|
|
83
83
|
"@types/jest": "^27.4.1",
|
|
@@ -94,7 +94,7 @@
|
|
|
94
94
|
},
|
|
95
95
|
"peerDependencies": {
|
|
96
96
|
"@babel/runtime": "^7.0.0",
|
|
97
|
-
"@metamask/accounts-controller": "^
|
|
97
|
+
"@metamask/accounts-controller": "^30.0.0",
|
|
98
98
|
"@metamask/approval-controller": "^7.0.0",
|
|
99
99
|
"@metamask/eth-block-tracker": ">=9",
|
|
100
100
|
"@metamask/gas-fee-controller": "^23.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"simulation.cjs","sourceRoot":"","sources":["../../src/utils/simulation.ts"],"names":[],"mappings":";;;AACA,4CAA+C;AAC/C,iEAA4D;AAC5D,mEAA8E;AAC9E,2CAA+D;AAE/D,8DAA6D;AAS7D,gDAGsB;AACtB,0CAImB;AACnB,0CAA0C;AAQ1C,wCAAmD;AAEnD,IAAY,cAMX;AAND,WAAY,cAAc;IACxB,iCAAe,CAAA;IACf,mCAAiB,CAAA;IACjB,qCAAmB,CAAA;IACnB,gDAA8B,CAAA;IAC9B,gDAA8B,CAAA;AAChC,CAAC,EANW,cAAc,8BAAd,cAAc,QAMzB;AAgCD,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,YAAY,CAAC,CAAC;AAE5D,MAAM,gBAAgB,GAAG;IACvB,UAAU;IACV,gBAAgB;IAChB,eAAe;IACf,SAAS;IACT,YAAY;CACb,CAAC;AAEF,MAAM,oBAAoB,GAAG;IAC3B,CAAC,cAAc,CAAC,KAAK,CAAC,EAAE;QACtB,GAAG,EAAE,4BAAQ;QACb,QAAQ,EAAE,+BAAuB,CAAC,KAAK;KACxC;IACD,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE;QACvB,GAAG,EAAE,6BAAS;QACd,QAAQ,EAAE,+BAAuB,CAAC,MAAM;KACzC;IACD,CAAC,cAAc,CAAC,OAAO,CAAC,EAAE;QACxB,GAAG,EAAE,8BAAU;QACf,QAAQ,EAAE,+BAAuB,CAAC,OAAO;KAC1C;IACD,CAAC,cAAc,CAAC,aAAa,CAAC,EAAE;QAC9B,GAAG,EAAE,wCAA4B;QACjC,QAAQ,EAAE,+BAAuB,CAAC,KAAK;KACxC;IACD,CAAC,cAAc,CAAC,aAAa,CA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CAAC,CAAC;AACN,CAAC;AAED;;;;;;;;;;GAUG;AACH,KAAK,UAAU,WAAW,CAAC,EACzB,OAAO,EACP,IAAI,EACJ,OAAO,EACP,MAAM,EACN,YAAY,GAOb;IACC,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC;IAE1C,OAAO,MAAM,IAAA,qCAAoB,EAAC,OAAc,EAAE;QAChD,YAAY;QACZ,GAAG,MAAM;QACT,GAAG,CAAC,SAAS,IAAI;YACf,cAAc,EAAE;gBACd,GAAG,MAAM,EAAE,cAAc;gBACzB,IAAI,EAAE,IAAA,wBAAK,EAAC,SAAS,CAAC;aACvB;SACF,CAAC;QACF,GAAG,CAAC,UAAU,IAAI;YAChB,SAAS,EAAE;gBACT,GAAG,MAAM,EAAE,SAAS;gBACpB,CAAC,IAAI,CAAC,EAAE;oBACN,GAAG,MAAM,EAAE,SAAS,EAAE,CAAC,IAAI,CAAC;oBAC5B,IAAI,EAAE,UAAU;iBACjB;aACF;SACF,CAAC;KACH,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { Fragment, LogDescription, Result } from '@ethersproject/abi';\nimport { Interface } from '@ethersproject/abi';\nimport { hexToBN, toHex } from '@metamask/controller-utils';\nimport { abiERC20, abiERC721, abiERC1155 } from '@metamask/metamask-eth-abis';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport { simulateTransactions } from '../api/simulation-api';\nimport type {\n SimulationResponseLog,\n SimulationRequestTransaction,\n SimulationResponse,\n SimulationResponseCallTrace,\n SimulationResponseTransaction,\n SimulationRequest,\n} from '../api/simulation-api';\nimport {\n ABI_SIMULATION_ERC20_WRAPPED,\n ABI_SIMULATION_ERC721_LEGACY,\n} from '../constants';\nimport {\n SimulationError,\n SimulationInvalidResponseError,\n SimulationRevertedError,\n} from '../errors';\nimport { projectLogger } from '../logger';\nimport type {\n SimulationBalanceChange,\n SimulationData,\n SimulationTokenBalanceChange,\n SimulationToken,\n GasFeeToken,\n} from '../types';\nimport { SimulationTokenStandard } from '../types';\n\nexport enum SupportedToken {\n ERC20 = 'erc20',\n ERC721 = 'erc721',\n ERC1155 = 'erc1155',\n ERC20_WRAPPED = 'erc20Wrapped',\n ERC721_LEGACY = 'erc721Legacy',\n}\n\ntype ABI = Fragment[];\n\nexport type GetSimulationDataRequest = {\n authorizationList?: SimulationRequestTransaction['authorizationList'];\n chainId: Hex;\n data?: Hex;\n from: Hex;\n to?: Hex;\n value?: Hex;\n};\n\nexport type GetSimulationDataResult = {\n gasFeeTokens: GasFeeToken[];\n simulationData: SimulationData;\n};\n\ntype ParsedEvent = {\n contractAddress: Hex;\n tokenStandard: SimulationTokenStandard;\n name: string;\n args: Record<string, Hex | Hex[]>;\n abi: ABI;\n};\n\ntype GetSimulationDataOptions = {\n blockTime?: number;\n senderCode?: Hex;\n use7702Fees?: boolean;\n};\n\nconst log = createModuleLogger(projectLogger, 'simulation');\n\nconst SUPPORTED_EVENTS = [\n 'Transfer',\n 'TransferSingle',\n 'TransferBatch',\n 'Deposit',\n 'Withdrawal',\n];\n\nconst SUPPORTED_TOKEN_ABIS = {\n [SupportedToken.ERC20]: {\n abi: abiERC20,\n standard: SimulationTokenStandard.erc20,\n },\n [SupportedToken.ERC721]: {\n abi: abiERC721,\n standard: SimulationTokenStandard.erc721,\n },\n [SupportedToken.ERC1155]: {\n abi: abiERC1155,\n standard: SimulationTokenStandard.erc1155,\n },\n [SupportedToken.ERC20_WRAPPED]: {\n abi: ABI_SIMULATION_ERC20_WRAPPED,\n standard: SimulationTokenStandard.erc20,\n },\n [SupportedToken.ERC721_LEGACY]: {\n abi: ABI_SIMULATION_ERC721_LEGACY,\n standard: SimulationTokenStandard.erc721,\n },\n};\n\nconst REVERTED_ERRORS = ['execution reverted', 'insufficient funds for gas'];\n\ntype BalanceTransactionMap = Map<SimulationToken, SimulationRequestTransaction>;\n\n/**\n * Generate simulation data for a transaction.\n *\n * @param request - The transaction to simulate.\n * @param request.chainId - The chain ID of the transaction.\n * @param request.from - The sender of the transaction.\n * @param request.to - The recipient of the transaction.\n * @param request.value - The value of the transaction.\n * @param request.data - The data of the transaction.\n * @param options - Additional options.\n * @param options.blockTime - An optional block time to simulate the transaction at.\n * @returns The simulation data.\n */\nexport async function getSimulationData(\n request: GetSimulationDataRequest,\n options: GetSimulationDataOptions = {},\n): Promise<GetSimulationDataResult> {\n const { authorizationList, chainId, from, to, value, data } = request;\n const { use7702Fees } = options;\n\n log('Getting simulation data', { request, options });\n\n try {\n const response = await baseRequest({\n chainId,\n from,\n options,\n params: {\n suggestFees: {\n withFeeTransfer: true,\n withTransfer: true,\n ...(use7702Fees ? { with7702: true } : {}),\n },\n withCallTrace: true,\n withLogs: true,\n },\n transactions: [\n {\n authorizationList,\n data,\n from,\n to,\n value,\n },\n ],\n });\n\n const transactionError = response.transactions?.[0]?.error;\n\n if (transactionError) {\n throw new SimulationError(transactionError);\n }\n\n const nativeBalanceChange = getNativeBalanceChange(request.from, response);\n const events = getEvents(response);\n\n log('Parsed events', events);\n\n const tokenBalanceChanges = await getTokenBalanceChanges(\n request,\n events,\n options,\n );\n\n const simulationData = {\n nativeBalanceChange,\n tokenBalanceChanges,\n };\n\n let gasFeeTokens: GasFeeToken[] = [];\n\n try {\n gasFeeTokens = getGasFeeTokens(response);\n } catch (error) {\n log('Failed to parse gas fee tokens', error, response);\n }\n\n return {\n gasFeeTokens,\n simulationData,\n };\n } catch (error) {\n log('Failed to get simulation data', error, request);\n\n let simulationError = error as SimulationError;\n\n if (\n REVERTED_ERRORS.some((revertErrorMessage) =>\n simulationError.message?.includes(revertErrorMessage),\n )\n ) {\n simulationError = new SimulationRevertedError();\n }\n\n const { code, message } = simulationError;\n\n return {\n gasFeeTokens: [],\n simulationData: {\n tokenBalanceChanges: [],\n error: {\n code,\n message,\n },\n },\n };\n }\n}\n\n/**\n * Extract the native balance change from a simulation response.\n *\n * @param userAddress - The user's account address.\n * @param response - The simulation response.\n * @returns The native balance change or undefined if unchanged.\n */\nfunction getNativeBalanceChange(\n userAddress: Hex,\n response: SimulationResponse,\n): SimulationBalanceChange | undefined {\n const transactionResponse = response.transactions[0];\n\n /* istanbul ignore next */\n if (!transactionResponse) {\n return undefined;\n }\n\n const { stateDiff } = transactionResponse;\n const previousBalance = stateDiff?.pre?.[userAddress]?.balance;\n const newBalance = stateDiff?.post?.[userAddress]?.balance;\n\n if (!previousBalance || !newBalance) {\n return undefined;\n }\n\n return getSimulationBalanceChange(previousBalance, newBalance);\n}\n\n/**\n * Extract events from a simulation response.\n *\n * @param response - The simulation response.\n * @returns The parsed events.\n */\nexport function getEvents(response: SimulationResponse): ParsedEvent[] {\n /* istanbul ignore next */\n const logs = extractLogs(\n response.transactions[0]?.callTrace ?? ({} as SimulationResponseCallTrace),\n );\n\n log('Extracted logs', logs);\n\n const interfaces = getContractInterfaces();\n\n return logs\n .map((currentLog) => {\n const event = parseLog(currentLog, interfaces);\n\n if (!event) {\n log('Failed to parse log', currentLog);\n return undefined;\n }\n\n /* istanbul ignore next */\n const inputs = event.abi.find((e) => e.name === event.name)?.inputs;\n\n /* istanbul ignore if */\n if (!inputs) {\n log('Failed to find inputs for event', event);\n return undefined;\n }\n\n if (!SUPPORTED_EVENTS.includes(event.name)) {\n log('Ignoring unsupported event', event.name, event);\n return undefined;\n }\n\n log('Normalizing event args', event.name, event);\n\n const args = normalizeEventArgs(event.args, inputs);\n\n return {\n contractAddress: currentLog.address,\n tokenStandard: event.standard,\n name: event.name,\n args,\n abi: event.abi,\n };\n })\n .filter((e) => e !== undefined) as ParsedEvent[];\n}\n\n/**\n * Normalize event arguments using ABI input definitions.\n *\n * @param args - The raw event arguments.\n * @param abiInputs - The ABI input definitions.\n * @returns The normalized event arguments.\n */\nfunction normalizeEventArgs(\n args: Result,\n abiInputs: { name: string }[],\n): Record<string, Hex | Hex[]> {\n return args.reduce((result, arg, index) => {\n const name = abiInputs[index].name.replace('_', '');\n const value = normalizeEventArgValue(arg);\n\n result[name] = value;\n\n return result;\n }, {});\n}\n\n/**\n * Normalize an event argument value.\n *\n * @param value - The event argument value.\n * @returns The normalized event argument value.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalizeEventArgValue(value: any): any {\n if (Array.isArray(value)) {\n return value.map(normalizeEventArgValue);\n }\n\n let normalizedValue = value;\n\n normalizedValue = normalizedValue.toHexString?.() ?? normalizedValue;\n normalizedValue = normalizedValue.toLowerCase?.() ?? normalizedValue;\n\n return normalizedValue;\n}\n\n/**\n * Generate token balance changes from parsed events.\n *\n * @param request - The transaction that was simulated.\n * @param events - The parsed events.\n * @param options - Additional options.\n * @param options.blockTime - An optional block time to simulate the transaction at.\n * @returns An array of token balance changes.\n */\nasync function getTokenBalanceChanges(\n request: GetSimulationDataRequest,\n events: ParsedEvent[],\n options: GetSimulationDataOptions,\n): Promise<SimulationTokenBalanceChange[]> {\n const { chainId, from } = request;\n const balanceTxs = getTokenBalanceTransactions(request, events);\n\n log('Generated balance transactions', [...balanceTxs.after.values()]);\n\n const transactions = [\n ...balanceTxs.before.values(),\n request,\n ...balanceTxs.after.values(),\n ];\n\n if (transactions.length === 1) {\n return [];\n }\n\n const response = await baseRequest({\n chainId,\n from,\n options,\n transactions,\n });\n\n log('Balance simulation response', response);\n\n if (response.transactions.length !== transactions.length) {\n throw new SimulationInvalidResponseError();\n }\n\n let prevBalanceTxIndex = 0;\n return [...balanceTxs.after.keys()]\n .map((token, index) => {\n const previousBalanceCheckSkipped = !balanceTxs.before.get(token);\n const previousBalance = previousBalanceCheckSkipped\n ? '0x0'\n : getAmountFromBalanceTransactionResult(\n request.from,\n token,\n // eslint-disable-next-line no-plusplus\n response.transactions[prevBalanceTxIndex++],\n );\n\n const newBalance = getAmountFromBalanceTransactionResult(\n request.from,\n token,\n response.transactions[index + balanceTxs.before.size + 1],\n );\n\n const balanceChange = getSimulationBalanceChange(\n previousBalance,\n newBalance,\n );\n\n if (!balanceChange) {\n return undefined;\n }\n\n return {\n ...token,\n ...balanceChange,\n };\n })\n .filter((change) => change !== undefined) as SimulationTokenBalanceChange[];\n}\n\n/**\n * Generate transactions to check token balances.\n *\n * @param request - The transaction that was simulated.\n * @param events - The parsed events.\n * @returns A map of token balance transactions keyed by token.\n */\nfunction getTokenBalanceTransactions(\n request: GetSimulationDataRequest,\n events: ParsedEvent[],\n): {\n before: BalanceTransactionMap;\n after: BalanceTransactionMap;\n} {\n const tokenKeys = new Set();\n const before = new Map();\n const after = new Map();\n\n const userEvents = events.filter((event) =>\n [event.args.from, event.args.to].includes(request.from),\n );\n\n log('Filtered user events', userEvents);\n\n for (const event of userEvents) {\n const tokenIds = getEventTokenIds(event);\n\n log('Extracted token IDs', tokenIds);\n\n for (const tokenId of tokenIds) {\n const simulationToken: SimulationToken = {\n address: event.contractAddress,\n standard: event.tokenStandard,\n id: tokenId,\n };\n\n const tokenKey = JSON.stringify(simulationToken);\n\n if (tokenKeys.has(tokenKey)) {\n log(\n 'Ignoring additional event with same contract and token ID',\n simulationToken,\n );\n continue;\n }\n\n tokenKeys.add(tokenKey);\n\n const data = getBalanceTransactionData(\n event.tokenStandard,\n request.from,\n tokenId,\n );\n\n const transaction: SimulationRequestTransaction = {\n from: request.from,\n to: event.contractAddress,\n data,\n };\n\n if (skipPriorBalanceCheck(event)) {\n after.set(simulationToken, transaction);\n } else {\n before.set(simulationToken, transaction);\n after.set(simulationToken, transaction);\n }\n }\n }\n\n return { before, after };\n}\n\n/**\n * Check if an event needs to check the previous balance.\n *\n * @param event - The parsed event.\n * @returns True if the prior balance check should be skipped.\n */\nfunction skipPriorBalanceCheck(event: ParsedEvent): boolean {\n // In the case of an NFT mint, we cannot check the NFT owner before the mint\n // as the balance check transaction would revert.\n return (\n event.name === 'Transfer' &&\n event.tokenStandard === SimulationTokenStandard.erc721 &&\n parseInt(event.args.from as string, 16) === 0\n );\n}\n\n/**\n * Extract token IDs from a parsed event.\n *\n * @param event - The parsed event.\n * @returns An array of token IDs.\n */\nfunction getEventTokenIds(event: ParsedEvent): (Hex | undefined)[] {\n if (event.tokenStandard === SimulationTokenStandard.erc721) {\n return [event.args.tokenId as Hex];\n }\n\n if (\n event.tokenStandard === SimulationTokenStandard.erc1155 &&\n event.name === 'TransferSingle'\n ) {\n return [event.args.id as Hex];\n }\n\n if (\n event.tokenStandard === SimulationTokenStandard.erc1155 &&\n event.name === 'TransferBatch'\n ) {\n return event.args.ids as Hex[];\n }\n\n // ERC-20 does not have a token ID so default to undefined.\n return [undefined];\n}\n\n/**\n * Get the interface for a token standard.\n *\n * @param tokenStandard - The token standard.\n * @returns The interface for the token standard.\n */\nfunction getContractInterface(\n tokenStandard: SimulationTokenStandard,\n): Interface {\n switch (tokenStandard) {\n case SimulationTokenStandard.erc721:\n return new Interface(abiERC721);\n case SimulationTokenStandard.erc1155:\n return new Interface(abiERC1155);\n default:\n return new Interface(abiERC20);\n }\n}\n\n/**\n * Extract the value from a balance transaction response using the correct ABI.\n *\n * @param from - The address to check the balance of.\n * @param token - The token to check the balance of.\n * @param response - The balance transaction response.\n * @returns The value of the balance transaction as Hex.\n */\nfunction getAmountFromBalanceTransactionResult(\n from: Hex,\n token: SimulationToken,\n response: SimulationResponseTransaction,\n): Hex {\n const contract = getContractInterface(token.standard);\n\n try {\n if (token.standard === SimulationTokenStandard.erc721) {\n const result = contract.decodeFunctionResult('ownerOf', response.return);\n const owner = result[0];\n return owner.toLowerCase() === from.toLowerCase() ? '0x1' : '0x0';\n }\n\n const result = contract.decodeFunctionResult('balanceOf', response.return);\n return toHex(result[0]);\n } catch (error) {\n log('Failed to decode balance transaction', error, { token, response });\n throw new SimulationError(\n `Failed to decode balance transaction for token ${\n token.address\n }: ${String(error)}`,\n );\n }\n}\n\n/**\n * Generate the balance transaction data for a token.\n *\n * @param tokenStandard - The token standard.\n * @param from - The address to check the balance of.\n * @param tokenId - The token ID to check the balance of.\n * @returns The balance transaction data.\n */\nfunction getBalanceTransactionData(\n tokenStandard: SimulationTokenStandard,\n from: Hex,\n tokenId?: Hex,\n): Hex {\n const contract = getContractInterface(tokenStandard);\n switch (tokenStandard) {\n case SimulationTokenStandard.erc721:\n return contract.encodeFunctionData('ownerOf', [tokenId]) as Hex;\n\n case SimulationTokenStandard.erc1155:\n return contract.encodeFunctionData('balanceOf', [from, tokenId]) as Hex;\n\n default:\n return contract.encodeFunctionData('balanceOf', [from]) as Hex;\n }\n}\n\n/**\n * Parse a raw event log using known ABIs.\n *\n * @param eventLog - The raw event log.\n * @param interfaces - The contract interfaces.\n * @returns The parsed event log or undefined if it could not be parsed.\n */\nfunction parseLog(\n eventLog: SimulationResponseLog,\n interfaces: Map<SupportedToken, Interface>,\n):\n | (LogDescription & { abi: ABI; standard: SimulationTokenStandard })\n | undefined {\n const supportedTokens = Object.values(SupportedToken);\n\n for (const token of supportedTokens) {\n try {\n const contractInterface = interfaces.get(token) as Interface;\n const { abi, standard } = SUPPORTED_TOKEN_ABIS[token];\n\n return {\n ...contractInterface.parseLog(eventLog),\n abi,\n standard,\n };\n // Not used\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n continue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extract all logs from a call trace tree.\n *\n * @param call - The root call trace.\n * @returns An array of logs.\n */\nfunction extractLogs(\n call: SimulationResponseCallTrace,\n): SimulationResponseLog[] {\n /* istanbul ignore next */\n const logs = call.logs ?? [];\n\n /* istanbul ignore next */\n const nestedCalls = call.calls ?? [];\n\n return [\n ...logs,\n ...nestedCalls.map((nestedCall) => extractLogs(nestedCall)).flat(),\n ];\n}\n\n/**\n * Generate balance change data from previous and new balances.\n *\n * @param previousBalance - The previous balance.\n * @param newBalance - The new balance.\n * @returns The balance change data or undefined if unchanged.\n */\nfunction getSimulationBalanceChange(\n previousBalance: Hex,\n newBalance: Hex,\n): SimulationBalanceChange | undefined {\n const differenceBN = hexToBN(newBalance).sub(hexToBN(previousBalance));\n const isDecrease = differenceBN.isNeg();\n const difference = toHex(differenceBN.abs());\n\n if (differenceBN.isZero()) {\n log('Balance change is zero');\n return undefined;\n }\n\n return {\n previousBalance,\n newBalance,\n difference,\n isDecrease,\n };\n}\n\n/**\n * Get the contract interfaces for all supported tokens.\n *\n * @returns A map of supported tokens to their contract interfaces.\n */\nfunction getContractInterfaces(): Map<SupportedToken, Interface> {\n const supportedTokens = Object.values(SupportedToken);\n\n return new Map(\n supportedTokens.map((tokenType) => {\n const { abi } = SUPPORTED_TOKEN_ABIS[tokenType];\n const contractInterface = new Interface(abi);\n return [tokenType, contractInterface];\n }),\n );\n}\n\n/**\n * Extract gas fee tokens from a simulation response.\n *\n * @param response - The simulation response.\n * @returns An array of gas fee tokens.\n */\nfunction getGasFeeTokens(response: SimulationResponse): GasFeeToken[] {\n const feeLevel = response.transactions?.[0]\n ?.fees?.[0] as Required<SimulationResponseTransaction>['fees'][0];\n\n const tokenFees = feeLevel?.tokenFees ?? [];\n\n return tokenFees.map((tokenFee) => ({\n amount: tokenFee.balanceNeededToken,\n balance: tokenFee.currentBalanceToken,\n decimals: tokenFee.token.decimals,\n gas: feeLevel.gas,\n gasTransfer: tokenFee.transferEstimate,\n maxFeePerGas: feeLevel.maxFeePerGas,\n maxPriorityFeePerGas: feeLevel.maxPriorityFeePerGas,\n rateWei: tokenFee.rateWei,\n recipient: tokenFee.feeRecipient,\n symbol: tokenFee.token.symbol,\n tokenAddress: tokenFee.token.address,\n }));\n}\n\n/**\n * Base request to simulation API.\n *\n * @param request - The request object.\n * @param request.chainId - Chain ID of the transaction.\n * @param request.from - Address of the sender.\n * @param request.options - Options for the simulation.\n * @param request.params - Additional parameters for the request.\n * @param request.transactions - Transactions to simulate.\n * @returns The simulation response.\n */\nasync function baseRequest({\n chainId,\n from,\n options,\n params,\n transactions,\n}: {\n chainId: Hex;\n from: Hex;\n options: GetSimulationDataOptions;\n params?: Partial<SimulationRequest>;\n transactions: SimulationRequestTransaction[];\n}): Promise<SimulationResponse> {\n const { blockTime, senderCode } = options;\n\n return await simulateTransactions(chainId as Hex, {\n transactions,\n ...params,\n ...(blockTime && {\n blockOverrides: {\n ...params?.blockOverrides,\n time: toHex(blockTime),\n },\n }),\n ...(senderCode && {\n overrides: {\n ...params?.overrides,\n [from]: {\n ...params?.overrides?.[from],\n code: senderCode,\n },\n },\n }),\n });\n}\n"]}
|
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
import type { Fragment } from "@ethersproject/abi";
|
|
2
|
-
import { type Hex } from "@metamask/utils";
|
|
3
|
-
import type { SimulationRequestTransaction, SimulationResponse } from "../api/simulation-api.cjs";
|
|
4
|
-
import type { SimulationData, GasFeeToken } from "../types.cjs";
|
|
5
|
-
import { SimulationTokenStandard } from "../types.cjs";
|
|
6
|
-
export declare enum SupportedToken {
|
|
7
|
-
ERC20 = "erc20",
|
|
8
|
-
ERC721 = "erc721",
|
|
9
|
-
ERC1155 = "erc1155",
|
|
10
|
-
ERC20_WRAPPED = "erc20Wrapped",
|
|
11
|
-
ERC721_LEGACY = "erc721Legacy"
|
|
12
|
-
}
|
|
13
|
-
type ABI = Fragment[];
|
|
14
|
-
export type GetSimulationDataRequest = {
|
|
15
|
-
authorizationList?: SimulationRequestTransaction['authorizationList'];
|
|
16
|
-
chainId: Hex;
|
|
17
|
-
data?: Hex;
|
|
18
|
-
from: Hex;
|
|
19
|
-
to?: Hex;
|
|
20
|
-
value?: Hex;
|
|
21
|
-
};
|
|
22
|
-
export type GetSimulationDataResult = {
|
|
23
|
-
gasFeeTokens: GasFeeToken[];
|
|
24
|
-
simulationData: SimulationData;
|
|
25
|
-
};
|
|
26
|
-
type ParsedEvent = {
|
|
27
|
-
contractAddress: Hex;
|
|
28
|
-
tokenStandard: SimulationTokenStandard;
|
|
29
|
-
name: string;
|
|
30
|
-
args: Record<string, Hex | Hex[]>;
|
|
31
|
-
abi: ABI;
|
|
32
|
-
};
|
|
33
|
-
type GetSimulationDataOptions = {
|
|
34
|
-
blockTime?: number;
|
|
35
|
-
senderCode?: Hex;
|
|
36
|
-
use7702Fees?: boolean;
|
|
37
|
-
};
|
|
38
|
-
/**
|
|
39
|
-
* Generate simulation data for a transaction.
|
|
40
|
-
*
|
|
41
|
-
* @param request - The transaction to simulate.
|
|
42
|
-
* @param request.chainId - The chain ID of the transaction.
|
|
43
|
-
* @param request.from - The sender of the transaction.
|
|
44
|
-
* @param request.to - The recipient of the transaction.
|
|
45
|
-
* @param request.value - The value of the transaction.
|
|
46
|
-
* @param request.data - The data of the transaction.
|
|
47
|
-
* @param options - Additional options.
|
|
48
|
-
* @param options.blockTime - An optional block time to simulate the transaction at.
|
|
49
|
-
* @returns The simulation data.
|
|
50
|
-
*/
|
|
51
|
-
export declare function getSimulationData(request: GetSimulationDataRequest, options?: GetSimulationDataOptions): Promise<GetSimulationDataResult>;
|
|
52
|
-
/**
|
|
53
|
-
* Extract events from a simulation response.
|
|
54
|
-
*
|
|
55
|
-
* @param response - The simulation response.
|
|
56
|
-
* @returns The parsed events.
|
|
57
|
-
*/
|
|
58
|
-
export declare function getEvents(response: SimulationResponse): ParsedEvent[];
|
|
59
|
-
export {};
|
|
60
|
-
//# sourceMappingURL=simulation.d.cts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"simulation.d.cts","sourceRoot":"","sources":["../../src/utils/simulation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAA0B,2BAA2B;AAI3E,OAAO,EAAsB,KAAK,GAAG,EAAE,wBAAwB;AAG/D,OAAO,KAAK,EAEV,4BAA4B,EAC5B,kBAAkB,EAInB,kCAA8B;AAW/B,OAAO,KAAK,EAEV,cAAc,EAGd,WAAW,EACZ,qBAAiB;AAClB,OAAO,EAAE,uBAAuB,EAAE,qBAAiB;AAEnD,oBAAY,cAAc;IACxB,KAAK,UAAU;IACf,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,aAAa,iBAAiB;IAC9B,aAAa,iBAAiB;CAC/B;AAED,KAAK,GAAG,GAAG,QAAQ,EAAE,CAAC;AAEtB,MAAM,MAAM,wBAAwB,GAAG;IACrC,iBAAiB,CAAC,EAAE,4BAA4B,CAAC,mBAAmB,CAAC,CAAC;IACtE,OAAO,EAAE,GAAG,CAAC;IACb,IAAI,CAAC,EAAE,GAAG,CAAC;IACX,IAAI,EAAE,GAAG,CAAC;IACV,EAAE,CAAC,EAAE,GAAG,CAAC;IACT,KAAK,CAAC,EAAE,GAAG,CAAC;CACb,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG;IACpC,YAAY,EAAE,WAAW,EAAE,CAAC;IAC5B,cAAc,EAAE,cAAc,CAAC;CAChC,CAAC;AAEF,KAAK,WAAW,GAAG;IACjB,eAAe,EAAE,GAAG,CAAC;IACrB,aAAa,EAAE,uBAAuB,CAAC;IACvC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,GAAG,GAAG,EAAE,CAAC,CAAC;IAClC,GAAG,EAAE,GAAG,CAAC;CACV,CAAC;AAEF,KAAK,wBAAwB,GAAG;IAC9B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,GAAG,CAAC;IACjB,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,CAAC;AAuCF;;;;;;;;;;;;GAYG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,wBAAwB,EACjC,OAAO,GAAE,wBAA6B,GACrC,OAAO,CAAC,uBAAuB,CAAC,CA2FlC;AA+BD;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,QAAQ,EAAE,kBAAkB,GAAG,WAAW,EAAE,CA8CrE"}
|
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
import type { Fragment } from "@ethersproject/abi";
|
|
2
|
-
import { type Hex } from "@metamask/utils";
|
|
3
|
-
import type { SimulationRequestTransaction, SimulationResponse } from "../api/simulation-api.mjs";
|
|
4
|
-
import type { SimulationData, GasFeeToken } from "../types.mjs";
|
|
5
|
-
import { SimulationTokenStandard } from "../types.mjs";
|
|
6
|
-
export declare enum SupportedToken {
|
|
7
|
-
ERC20 = "erc20",
|
|
8
|
-
ERC721 = "erc721",
|
|
9
|
-
ERC1155 = "erc1155",
|
|
10
|
-
ERC20_WRAPPED = "erc20Wrapped",
|
|
11
|
-
ERC721_LEGACY = "erc721Legacy"
|
|
12
|
-
}
|
|
13
|
-
type ABI = Fragment[];
|
|
14
|
-
export type GetSimulationDataRequest = {
|
|
15
|
-
authorizationList?: SimulationRequestTransaction['authorizationList'];
|
|
16
|
-
chainId: Hex;
|
|
17
|
-
data?: Hex;
|
|
18
|
-
from: Hex;
|
|
19
|
-
to?: Hex;
|
|
20
|
-
value?: Hex;
|
|
21
|
-
};
|
|
22
|
-
export type GetSimulationDataResult = {
|
|
23
|
-
gasFeeTokens: GasFeeToken[];
|
|
24
|
-
simulationData: SimulationData;
|
|
25
|
-
};
|
|
26
|
-
type ParsedEvent = {
|
|
27
|
-
contractAddress: Hex;
|
|
28
|
-
tokenStandard: SimulationTokenStandard;
|
|
29
|
-
name: string;
|
|
30
|
-
args: Record<string, Hex | Hex[]>;
|
|
31
|
-
abi: ABI;
|
|
32
|
-
};
|
|
33
|
-
type GetSimulationDataOptions = {
|
|
34
|
-
blockTime?: number;
|
|
35
|
-
senderCode?: Hex;
|
|
36
|
-
use7702Fees?: boolean;
|
|
37
|
-
};
|
|
38
|
-
/**
|
|
39
|
-
* Generate simulation data for a transaction.
|
|
40
|
-
*
|
|
41
|
-
* @param request - The transaction to simulate.
|
|
42
|
-
* @param request.chainId - The chain ID of the transaction.
|
|
43
|
-
* @param request.from - The sender of the transaction.
|
|
44
|
-
* @param request.to - The recipient of the transaction.
|
|
45
|
-
* @param request.value - The value of the transaction.
|
|
46
|
-
* @param request.data - The data of the transaction.
|
|
47
|
-
* @param options - Additional options.
|
|
48
|
-
* @param options.blockTime - An optional block time to simulate the transaction at.
|
|
49
|
-
* @returns The simulation data.
|
|
50
|
-
*/
|
|
51
|
-
export declare function getSimulationData(request: GetSimulationDataRequest, options?: GetSimulationDataOptions): Promise<GetSimulationDataResult>;
|
|
52
|
-
/**
|
|
53
|
-
* Extract events from a simulation response.
|
|
54
|
-
*
|
|
55
|
-
* @param response - The simulation response.
|
|
56
|
-
* @returns The parsed events.
|
|
57
|
-
*/
|
|
58
|
-
export declare function getEvents(response: SimulationResponse): ParsedEvent[];
|
|
59
|
-
export {};
|
|
60
|
-
//# sourceMappingURL=simulation.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"simulation.d.mts","sourceRoot":"","sources":["../../src/utils/simulation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAA0B,2BAA2B;AAI3E,OAAO,EAAsB,KAAK,GAAG,EAAE,wBAAwB;AAG/D,OAAO,KAAK,EAEV,4BAA4B,EAC5B,kBAAkB,EAInB,kCAA8B;AAW/B,OAAO,KAAK,EAEV,cAAc,EAGd,WAAW,EACZ,qBAAiB;AAClB,OAAO,EAAE,uBAAuB,EAAE,qBAAiB;AAEnD,oBAAY,cAAc;IACxB,KAAK,UAAU;IACf,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,aAAa,iBAAiB;IAC9B,aAAa,iBAAiB;CAC/B;AAED,KAAK,GAAG,GAAG,QAAQ,EAAE,CAAC;AAEtB,MAAM,MAAM,wBAAwB,GAAG;IACrC,iBAAiB,CAAC,EAAE,4BAA4B,CAAC,mBAAmB,CAAC,CAAC;IACtE,OAAO,EAAE,GAAG,CAAC;IACb,IAAI,CAAC,EAAE,GAAG,CAAC;IACX,IAAI,EAAE,GAAG,CAAC;IACV,EAAE,CAAC,EAAE,GAAG,CAAC;IACT,KAAK,CAAC,EAAE,GAAG,CAAC;CACb,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG;IACpC,YAAY,EAAE,WAAW,EAAE,CAAC;IAC5B,cAAc,EAAE,cAAc,CAAC;CAChC,CAAC;AAEF,KAAK,WAAW,GAAG;IACjB,eAAe,EAAE,GAAG,CAAC;IACrB,aAAa,EAAE,uBAAuB,CAAC;IACvC,IAAI,EAA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