@metamask/transaction-controller 65.0.0 → 65.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 +17 -1
- package/dist/TransactionController.cjs +32 -1
- package/dist/TransactionController.cjs.map +1 -1
- package/dist/TransactionController.d.cts.map +1 -1
- package/dist/TransactionController.d.mts.map +1 -1
- package/dist/TransactionController.mjs +32 -1
- package/dist/TransactionController.mjs.map +1 -1
- package/dist/api/simulation-api.cjs.map +1 -1
- package/dist/api/simulation-api.d.cts +2 -0
- package/dist/api/simulation-api.d.cts.map +1 -1
- package/dist/api/simulation-api.d.mts +2 -0
- package/dist/api/simulation-api.d.mts.map +1 -1
- package/dist/api/simulation-api.mjs.map +1 -1
- package/dist/helpers/PendingTransactionTracker.cjs +13 -2
- package/dist/helpers/PendingTransactionTracker.cjs.map +1 -1
- package/dist/helpers/PendingTransactionTracker.d.cts.map +1 -1
- package/dist/helpers/PendingTransactionTracker.d.mts.map +1 -1
- package/dist/helpers/PendingTransactionTracker.mjs +13 -2
- package/dist/helpers/PendingTransactionTracker.mjs.map +1 -1
- package/dist/index.cjs +3 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -0
- package/dist/index.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +22 -0
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +22 -0
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/balance-changes.cjs +21 -1
- package/dist/utils/balance-changes.cjs.map +1 -1
- package/dist/utils/balance-changes.d.cts +2 -1
- package/dist/utils/balance-changes.d.cts.map +1 -1
- package/dist/utils/balance-changes.d.mts +2 -1
- package/dist/utils/balance-changes.d.mts.map +1 -1
- package/dist/utils/balance-changes.mjs +21 -1
- package/dist/utils/balance-changes.mjs.map +1 -1
- package/dist/utils/eip7702.cjs +38 -9
- package/dist/utils/eip7702.cjs.map +1 -1
- package/dist/utils/eip7702.d.cts +12 -0
- package/dist/utils/eip7702.d.cts.map +1 -1
- package/dist/utils/eip7702.d.mts +12 -0
- package/dist/utils/eip7702.d.mts.map +1 -1
- package/dist/utils/eip7702.mjs +36 -8
- package/dist/utils/eip7702.mjs.map +1 -1
- package/dist/utils/gas.cjs +12 -5
- package/dist/utils/gas.cjs.map +1 -1
- package/dist/utils/gas.d.cts +2 -1
- package/dist/utils/gas.d.cts.map +1 -1
- package/dist/utils/gas.d.mts +2 -1
- package/dist/utils/gas.d.mts.map +1 -1
- package/dist/utils/gas.mjs +12 -5
- package/dist/utils/gas.mjs.map +1 -1
- package/dist/utils/revert-reason.cjs +192 -0
- package/dist/utils/revert-reason.cjs.map +1 -0
- package/dist/utils/revert-reason.d.cts +57 -0
- package/dist/utils/revert-reason.d.cts.map +1 -0
- package/dist/utils/revert-reason.d.mts +57 -0
- package/dist/utils/revert-reason.d.mts.map +1 -0
- package/dist/utils/revert-reason.mjs +186 -0
- package/dist/utils/revert-reason.mjs.map +1 -0
- package/package.json +4 -4
package/dist/utils/gas.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { TransactionEnvelopeType } from "../types.mjs";
|
|
|
7
7
|
import { DELEGATION_PREFIX, doesAccountSupportEIP7702, generateEIP7702BatchTransaction } from "./eip7702.mjs";
|
|
8
8
|
import { getGasEstimateBuffer, getGasEstimateFallback } from "./feature-flags.mjs";
|
|
9
9
|
import { getChainId, rpcRequest } from "./provider.mjs";
|
|
10
|
+
import { decodeRevert } from "./revert-reason.mjs";
|
|
10
11
|
export const log = createModuleLogger(projectLogger, 'gas');
|
|
11
12
|
export const FIXED_GAS = '0x5208';
|
|
12
13
|
export const DEFAULT_GAS_MULTIPLIER = 1.5;
|
|
@@ -21,10 +22,13 @@ export const DUMMY_AUTHORIZATION_SIGNATURE = '0x11111111111111111111111111111111
|
|
|
21
22
|
export async function updateGas(request) {
|
|
22
23
|
const { txMeta } = request;
|
|
23
24
|
const initialParams = { ...txMeta.txParams };
|
|
24
|
-
const [gas, simulationFails, gasLimitNoBuffer] = await getGas(request);
|
|
25
|
+
const [gas, simulationFails, gasLimitNoBuffer, gasRevert] = await getGas(request);
|
|
25
26
|
txMeta.txParams.gas = gas;
|
|
26
27
|
txMeta.simulationFails = simulationFails;
|
|
27
28
|
txMeta.gasLimitNoBuffer = gasLimitNoBuffer;
|
|
29
|
+
if (gasRevert) {
|
|
30
|
+
txMeta.revert = { ...txMeta.revert, gas: gasRevert };
|
|
31
|
+
}
|
|
28
32
|
if (!initialParams.gas) {
|
|
29
33
|
txMeta.originalGasEstimate = txMeta.txParams.gas;
|
|
30
34
|
}
|
|
@@ -66,6 +70,7 @@ export async function estimateGas({ ignoreDelegationSignatures, isSimulationEnab
|
|
|
66
70
|
delete request.maxPriorityFeePerGas;
|
|
67
71
|
let estimatedGas = fallback;
|
|
68
72
|
let simulationFails;
|
|
73
|
+
let gasRevert;
|
|
69
74
|
const isUpgradeWithData = txParams.type === TransactionEnvelopeType.setCode &&
|
|
70
75
|
Boolean(authorizationList?.length) &&
|
|
71
76
|
Boolean(data) &&
|
|
@@ -95,11 +100,13 @@ export async function estimateGas({ ignoreDelegationSignatures, isSimulationEnab
|
|
|
95
100
|
blockGasLimit,
|
|
96
101
|
},
|
|
97
102
|
};
|
|
98
|
-
|
|
103
|
+
gasRevert = decodeRevert(error, 'gas');
|
|
104
|
+
log('Estimation failed', { ...simulationFails, fallback, gasRevert });
|
|
99
105
|
}
|
|
100
106
|
return {
|
|
101
107
|
blockGasLimit,
|
|
102
108
|
estimatedGas,
|
|
109
|
+
gasRevert,
|
|
103
110
|
isUpgradeWithData,
|
|
104
111
|
simulationFails,
|
|
105
112
|
};
|
|
@@ -254,7 +261,7 @@ async function getGas(request) {
|
|
|
254
261
|
log('Using fixed value', FIXED_GAS);
|
|
255
262
|
return [FIXED_GAS, undefined, FIXED_GAS];
|
|
256
263
|
}
|
|
257
|
-
const { blockGasLimit, estimatedGas, isUpgradeWithData, simulationFails } = await estimateGas({
|
|
264
|
+
const { blockGasLimit, estimatedGas, gasRevert, isUpgradeWithData, simulationFails, } = await estimateGas({
|
|
258
265
|
isSimulationEnabled,
|
|
259
266
|
getSimulationConfig,
|
|
260
267
|
messenger,
|
|
@@ -269,7 +276,7 @@ async function getGas(request) {
|
|
|
269
276
|
log('Gas buffer disabled');
|
|
270
277
|
}
|
|
271
278
|
if (simulationFails || disableGasBuffer) {
|
|
272
|
-
return [estimatedGas, simulationFails, estimatedGas];
|
|
279
|
+
return [estimatedGas, simulationFails, estimatedGas, gasRevert];
|
|
273
280
|
}
|
|
274
281
|
const bufferMultiplier = getGasEstimateBuffer({
|
|
275
282
|
chainId,
|
|
@@ -280,7 +287,7 @@ async function getGas(request) {
|
|
|
280
287
|
log('Buffer', bufferMultiplier);
|
|
281
288
|
const bufferedGas = addGasBuffer(estimatedGas, blockGasLimit, bufferMultiplier);
|
|
282
289
|
log('Buffered gas', bufferedGas);
|
|
283
|
-
return [bufferedGas, simulationFails, estimatedGas];
|
|
290
|
+
return [bufferedGas, simulationFails, estimatedGas, gasRevert];
|
|
284
291
|
}
|
|
285
292
|
/**
|
|
286
293
|
* Determine if the gas for the provided request should be fixed.
|
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,EACN,mCAAmC;AAGpC,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,QAAQ,EAAE,wBAAwB;AACtE,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EAAE,oBAAoB,EAAE,kCAA8B;AAC7D,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAE1C,OAAO,EA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N,\n toHex,\n} from '@metamask/controller-utils';\nimport type { NetworkClientId } from '@metamask/network-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport { add0x, createModuleLogger, remove0x } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { simulateTransactions } from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport { TransactionEnvelopeType } from '../types';\nimport type {\n AuthorizationList,\n BatchTransactionParams,\n GetSimulationConfig,\n IsAtomicBatchSupportedRequest,\n IsAtomicBatchSupportedResult,\n TransactionBatchSingleRequest,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport {\n DELEGATION_PREFIX,\n doesAccountSupportEIP7702,\n generateEIP7702BatchTransaction,\n} from './eip7702';\nimport { getGasEstimateBuffer, getGasEstimateFallback } from './feature-flags';\nimport { getChainId, rpcRequest } from './provider';\n\nexport type UpdateGasRequest = {\n isCustomNetwork: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport type EstimateGasBatchResult = {\n gasLimits: number[];\n requiresAuthorizationList?: true;\n totalGasLimit: number;\n};\n\nexport const log = createModuleLogger(projectLogger, 'gas');\n\nexport const FIXED_GAS = '0x5208';\nexport const DEFAULT_GAS_MULTIPLIER = 1.5;\nexport const MAX_GAS_BLOCK_PERCENT = 90;\nexport const INTRINSIC_GAS = 21000;\n\nexport const DUMMY_AUTHORIZATION_SIGNATURE =\n '0x1111111111111111111111111111111111111111111111111111111111111111';\n\n/**\n * Populate the gas properties of the provided transaction meta.\n *\n * @param request - The request object including the necessary parameters.\n */\nexport async function updateGas(request: UpdateGasRequest): Promise<void> {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const [gas, simulationFails, gasLimitNoBuffer] = await getGas(request);\n\n txMeta.txParams.gas = gas;\n txMeta.simulationFails = simulationFails;\n txMeta.gasLimitNoBuffer = gasLimitNoBuffer;\n\n if (!initialParams.gas) {\n txMeta.originalGasEstimate = txMeta.txParams.gas;\n }\n\n txMeta.defaultGasEstimates ??= {};\n txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;\n}\n\n/**\n * Estimate the gas for the provided transaction parameters.\n * If the gas estimate fails, the fallback value is returned.\n *\n * @param options - The options object.\n * @param options.ignoreDelegationSignatures - Ignore signature errors if submitting delegations to the DelegationManager.\n * @param options.isSimulationEnabled - Whether the simulation is enabled.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.messenger - The messenger instance for communication.\n * @param options.networkClientId - The network client ID.\n * @param options.txParams - The transaction parameters.\n * @returns The estimated gas and related info.\n */\nexport async function estimateGas({\n ignoreDelegationSignatures,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n networkClientId,\n txParams,\n}: {\n ignoreDelegationSignatures?: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n networkClientId: NetworkClientId;\n txParams: TransactionParams;\n}): Promise<{\n blockGasLimit: string;\n estimatedGas: string;\n isUpgradeWithData: boolean;\n simulationFails: TransactionMeta['simulationFails'];\n}> {\n const request = { ...txParams };\n const { authorizationList, data, value } = request;\n const chainId = getChainId({ messenger, networkClientId });\n\n if (ignoreDelegationSignatures && !isSimulationEnabled) {\n throw new Error(\n 'Gas estimation with ignored delegation signatures is not supported as simulation disabled',\n );\n }\n\n const { gasLimit: blockGasLimit, number: blockNumber } = await getLatestBlock(\n messenger,\n networkClientId,\n );\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 isUpgradeWithData =\n txParams.type === TransactionEnvelopeType.setCode &&\n Boolean(authorizationList?.length) &&\n Boolean(data) &&\n data !== '0x';\n\n try {\n if (isSimulationEnabled && isUpgradeWithData) {\n estimatedGas = await estimateGasUpgradeWithDataToSelf(\n request,\n messenger,\n networkClientId,\n chainId,\n getSimulationConfig,\n );\n } else if (ignoreDelegationSignatures && isSimulationEnabled) {\n estimatedGas = await simulateGas({\n chainId,\n getSimulationConfig,\n transaction: request,\n });\n } else {\n estimatedGas = await estimateGasNode(messenger, networkClientId, 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 isUpgradeWithData,\n simulationFails,\n };\n}\n\nexport async function estimateGasBatch({\n from,\n getSimulationConfig,\n isAtomicBatchSupported,\n messenger,\n networkClientId,\n transactions,\n}: {\n from: Hex;\n getSimulationConfig: GetSimulationConfig;\n isAtomicBatchSupported: (\n request: IsAtomicBatchSupportedRequest,\n ) => Promise<IsAtomicBatchSupportedResult>;\n messenger: TransactionControllerMessenger;\n networkClientId: NetworkClientId;\n transactions: BatchTransactionParams[];\n}): Promise<EstimateGasBatchResult> {\n const chainId = getChainId({ messenger, networkClientId });\n\n const is7702Result = await isAtomicBatchSupported({\n address: from,\n chainIds: [chainId],\n });\n\n const accountSupports7702 = doesAccountSupportEIP7702(messenger, from);\n\n const chainResult = accountSupports7702\n ? is7702Result.find((result) => result.chainId === chainId)\n : undefined;\n\n const isUpgradeRequired = Boolean(chainResult && !chainResult.isSupported);\n\n if (isUpgradeRequired && !chainResult?.upgradeContractAddress) {\n throw new Error('Upgrade contract address not found');\n }\n\n if (chainResult) {\n const authorizationList = isUpgradeRequired\n ? [{ address: chainResult.upgradeContractAddress as Hex }]\n : undefined;\n\n const type = isUpgradeRequired\n ? TransactionEnvelopeType.setCode\n : undefined;\n\n const params: TransactionParams = {\n ...generateEIP7702BatchTransaction(from, transactions),\n authorizationList,\n from,\n type,\n };\n\n const { estimatedGas: gasLimitHex } = await estimateGas({\n isSimulationEnabled: true,\n getSimulationConfig,\n messenger,\n networkClientId,\n txParams: params,\n });\n\n const totalGasLimit = new BigNumber(gasLimitHex).toNumber();\n\n log('Estimated EIP-7702 gas limit', totalGasLimit);\n\n return {\n gasLimits: [totalGasLimit],\n ...(isUpgradeRequired ? { requiresAuthorizationList: true } : {}),\n totalGasLimit,\n };\n }\n\n const allTransactionsHaveGas = transactions.every(\n (transaction) => transaction.gas !== undefined,\n );\n\n if (allTransactionsHaveGas) {\n const gasLimits = transactions.map((transaction) =>\n new BigNumber(transaction.gas as Hex).toNumber(),\n );\n\n const total = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);\n\n log('Using batch parameter gas limits', { gasLimits, total });\n\n return { totalGasLimit: total, gasLimits };\n }\n\n const { gasLimits: gasLimitsHex } = await simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions: transactions.map((transaction) => ({\n params: transaction,\n })),\n });\n\n const gasLimits = transactions.map((transaction, index) =>\n transaction.gas\n ? new BigNumber(transaction.gas).toNumber()\n : new BigNumber(gasLimitsHex[index]).toNumber(),\n );\n\n const totalGasLimit = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);\n\n log('Simulated batch gas limits', { totalGasLimit, gasLimits });\n\n return { totalGasLimit, gasLimits };\n}\n\n/**\n * Add a buffer to the provided estimated gas.\n * The buffer is calculated based on the block gas limit and a multiplier.\n *\n * @param estimatedGas - The estimated gas.\n * @param blockGasLimit - The block gas limit.\n * @param multiplier - The multiplier to apply to the estimated gas.\n * @returns The gas with the buffer applied.\n */\nexport function addGasBuffer(\n estimatedGas: string,\n blockGasLimit: string,\n multiplier: number,\n): string {\n const estimatedGasBN = hexToBN(estimatedGas);\n\n const maxGasBN = fractionBN(\n hexToBN(blockGasLimit),\n MAX_GAS_BLOCK_PERCENT,\n 100,\n );\n\n const paddedGasBN = fractionBN(estimatedGasBN, multiplier * 100, 100);\n\n if (estimatedGasBN.gt(maxGasBN)) {\n const estimatedGasHex = add0x(estimatedGas);\n log('Using estimated value', estimatedGasHex);\n return estimatedGasHex;\n }\n\n if (paddedGasBN.lt(maxGasBN)) {\n const paddedHex = add0x(BNToHex(paddedGasBN));\n log('Using padded estimate', paddedHex, multiplier);\n return paddedHex;\n }\n\n const maxHex = add0x(BNToHex(maxGasBN));\n log('Using 90% of block gas limit', maxHex);\n return maxHex;\n}\n\n/**\n * Simulate the required gas for a batch of transactions using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transactions.\n * @param options.from - The address of the sender.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transactions - The array of transactions within a batch request.\n * @returns An object containing the transactions with their gas limits and the total gas limit.\n */\nexport async function simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions,\n}: {\n chainId: Hex;\n from: Hex;\n getSimulationConfig: GetSimulationConfig;\n transactions: TransactionBatchSingleRequest[];\n}): Promise<{ totalGasLimit: Hex; gasLimits: Hex[] }> {\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: transactions.map((transaction) => ({\n ...transaction.params,\n from,\n })),\n });\n\n if (response?.transactions?.length !== transactions.length) {\n throw new Error('Simulation response does not match transaction count');\n }\n\n return response.transactions.reduce<{\n totalGasLimit: Hex;\n gasLimits: Hex[];\n }>(\n (acc, transaction) => {\n const gasLimit = transaction?.gasLimit;\n\n if (!gasLimit) {\n throw new Error(\n 'No simulated gas returned for one of the transactions',\n );\n }\n\n acc.gasLimits.push(gasLimit);\n\n acc.totalGasLimit = BNToHex(\n hexToBN(acc.totalGasLimit).add(hexToBN(gasLimit)),\n );\n\n return acc;\n },\n {\n totalGasLimit: '0x0',\n gasLimits: [],\n },\n );\n } catch (error: unknown) {\n log('Error while simulating gas batch', error);\n throw new Error(\n 'Cannot estimate transaction batch total gas as simulation failed',\n );\n }\n}\n\n/**\n * Determine the gas for the provided request.\n *\n * @param request - The request object including the necessary parameters.\n * @returns The final gas value and the estimate used.\n */\nasync function getGas(\n request: UpdateGasRequest,\n): Promise<[string, TransactionMeta['simulationFails']?, string?]> {\n const {\n isCustomNetwork,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txMeta,\n } = request;\n const { networkClientId } = txMeta;\n const chainId = getChainId({ messenger, networkClientId });\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 { blockGasLimit, estimatedGas, isUpgradeWithData, simulationFails } =\n await estimateGas({\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n networkClientId,\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 isUpgradeWithData,\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.messenger - The messenger instance for communication.\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 messenger,\n txMeta,\n isCustomNetwork,\n}: UpdateGasRequest): Promise<boolean> {\n const {\n networkClientId,\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(messenger, networkClientId, to);\n\n return !code || code === '0x';\n}\n\n/**\n * Get the contract code for the provided address.\n *\n * @param messenger - The messenger instance for communication.\n * @param networkClientId - The network client ID.\n * @param address - The address to get the code for.\n * @returns The contract code.\n */\nasync function getCode(\n messenger: TransactionControllerMessenger,\n networkClientId: NetworkClientId,\n address: string,\n): Promise<string | undefined> {\n return (await rpcRequest({\n messenger,\n networkClientId,\n method: 'eth_getCode',\n params: [address, 'latest'],\n })) as string | undefined;\n}\n\n/**\n * Get the latest block from the network.\n *\n * @param messenger - The messenger instance for communication.\n * @param networkClientId - The network client ID.\n * @returns The latest block number.\n */\nasync function getLatestBlock(\n messenger: TransactionControllerMessenger,\n networkClientId: NetworkClientId,\n): Promise<{ gasLimit: string; number: string }> {\n return (await rpcRequest({\n messenger,\n networkClientId,\n method: 'eth_getBlockByNumber',\n params: ['latest', false],\n })) as { gasLimit: string; number: string };\n}\n\n/**\n * Estimate the gas for a type 4 transaction.\n *\n * @param txParams - The transaction parameters.\n * @param messenger - The messenger instance for communication.\n * @param networkClientId - The network client ID.\n * @param chainId - The chain ID of the transaction.\n * @param getSimulationConfig - The function to get the simulation configuration.\n * @returns The estimated gas.\n */\nasync function estimateGasUpgradeWithDataToSelf(\n txParams: TransactionParams,\n messenger: TransactionControllerMessenger,\n networkClientId: NetworkClientId,\n chainId: Hex,\n getSimulationConfig: GetSimulationConfig,\n): Promise<Hex> {\n const upgradeGas = (await rpcRequest({\n messenger,\n networkClientId,\n method: 'eth_estimateGas',\n params: [\n {\n ...txParams,\n to: txParams.from,\n data: '0x',\n },\n ],\n })) as Hex;\n\n log('Upgrade only gas', upgradeGas);\n\n const delegationAddress = txParams.authorizationList?.[0].address as Hex;\n\n let executeGas: Hex | undefined;\n\n try {\n executeGas = await simulateGas({\n chainId,\n delegationAddress,\n getSimulationConfig,\n transaction: txParams,\n });\n } catch (error: unknown) {\n log('Error while simulating data portion of upgrade', error);\n }\n\n if (executeGas === undefined) {\n try {\n executeGas = await estimateGasNode(\n messenger,\n networkClientId,\n { ...txParams, authorizationList: undefined, type: undefined },\n delegationAddress,\n );\n } catch (error: unknown) {\n log('Error while estimating data portion of upgrade', error);\n throw error;\n }\n\n log('Success estimating data portion of upgrade', executeGas);\n }\n\n log('Execute gas', executeGas);\n\n const total = BNToHex(\n hexToBN(upgradeGas).add(hexToBN(executeGas)).subn(INTRINSIC_GAS),\n );\n\n log('Total type 4 gas', total);\n\n return total;\n}\n\n/**\n * Simulate the required gas using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transaction.\n * @param options.delegationAddress - The delegation address of the sender to mock.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transaction - The transaction parameters.\n * @returns The simulated gas.\n */\nasync function simulateGas({\n chainId,\n delegationAddress,\n getSimulationConfig,\n transaction,\n}: {\n chainId: Hex;\n delegationAddress?: Hex;\n getSimulationConfig: GetSimulationConfig;\n transaction: TransactionParams;\n}): Promise<Hex> {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n to: transaction.to as Hex,\n from: transaction.from as Hex,\n data: transaction.data as Hex,\n value: transaction.value as Hex,\n },\n ],\n overrides: {\n [transaction.from]: {\n code:\n delegationAddress &&\n ((DELEGATION_PREFIX + remove0x(delegationAddress)) as Hex),\n },\n },\n });\n\n const gasLimit = response?.transactions?.[0].gasLimit;\n\n if (!gasLimit) {\n throw new Error('No simulated gas returned');\n }\n\n return gasLimit;\n}\n\n/**\n * Populate the authorization list with dummy values.\n *\n * @param authorizationList - The authorization list to prepare.\n * @param chainId - The chain ID to use.\n * @returns The authorization list with dummy values.\n */\nfunction normalizeAuthorizationList(\n authorizationList: AuthorizationList | undefined,\n chainId: Hex,\n): AuthorizationList | undefined {\n return authorizationList?.map((authorization) => ({\n ...authorization,\n chainId: authorization.chainId ?? chainId,\n nonce: authorization.nonce ?? '0x1',\n r: authorization.r ?? DUMMY_AUTHORIZATION_SIGNATURE,\n s: authorization.s ?? DUMMY_AUTHORIZATION_SIGNATURE,\n yParity: authorization.yParity ?? '0x1',\n }));\n}\n\n/**\n * Estimate the gas for a transaction using the `eth_estimateGas` method.\n *\n * @param messenger - The messenger instance for communication.\n * @param networkClientId - The network client ID.\n * @param txParams - The transaction parameters.\n * @param delegationAddress - The delegation address of the sender to mock.\n * @returns The estimated gas as a hex string.\n */\nasync function estimateGasNode(\n messenger: TransactionControllerMessenger,\n networkClientId: NetworkClientId,\n txParams: TransactionParams,\n delegationAddress?: Hex,\n): Promise<Hex> {\n const { from } = txParams;\n const params = [txParams] as Json[];\n\n if (delegationAddress) {\n params.push('latest');\n\n params.push({\n [from]: {\n code: DELEGATION_PREFIX + remove0x(delegationAddress),\n },\n });\n }\n\n return (await rpcRequest({\n messenger,\n networkClientId,\n method: 'eth_estimateGas',\n params,\n })) as Hex;\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,EACN,mCAAmC;AAGpC,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,QAAQ,EAAE,wBAAwB;AACtE,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EAAE,oBAAoB,EAAE,kCAA8B;AAC7D,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAE1C,OAAO,EAAE,uBAAuB,EAAE,qBAAiB;AAYnD,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EACzB,+BAA+B,EAChC,sBAAkB;AACnB,OAAO,EAAE,oBAA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CAAC;aACtD;SACF,CAAC,CAAC;IACL,CAAC;IAED,OAAO,CAAC,MAAM,UAAU,CAAC;QACvB,SAAS;QACT,eAAe;QACf,MAAM,EAAE,iBAAiB;QACzB,MAAM;KACP,CAAC,CAAQ,CAAC;AACb,CAAC","sourcesContent":["import {\n BNToHex,\n fractionBN,\n hexToBN,\n toHex,\n} from '@metamask/controller-utils';\nimport type { NetworkClientId } from '@metamask/network-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport { add0x, createModuleLogger, remove0x } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { simulateTransactions } from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport { TransactionEnvelopeType } from '../types';\nimport type {\n AuthorizationList,\n BatchTransactionParams,\n GetSimulationConfig,\n IsAtomicBatchSupportedRequest,\n IsAtomicBatchSupportedResult,\n Revert,\n TransactionBatchSingleRequest,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport {\n DELEGATION_PREFIX,\n doesAccountSupportEIP7702,\n generateEIP7702BatchTransaction,\n} from './eip7702';\nimport { getGasEstimateBuffer, getGasEstimateFallback } from './feature-flags';\nimport { getChainId, rpcRequest } from './provider';\nimport { decodeRevert } from './revert-reason';\n\nexport type UpdateGasRequest = {\n isCustomNetwork: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport type EstimateGasBatchResult = {\n gasLimits: number[];\n requiresAuthorizationList?: true;\n totalGasLimit: number;\n};\n\nexport const log = createModuleLogger(projectLogger, 'gas');\n\nexport const FIXED_GAS = '0x5208';\nexport const DEFAULT_GAS_MULTIPLIER = 1.5;\nexport const MAX_GAS_BLOCK_PERCENT = 90;\nexport const INTRINSIC_GAS = 21000;\n\nexport const DUMMY_AUTHORIZATION_SIGNATURE =\n '0x1111111111111111111111111111111111111111111111111111111111111111';\n\n/**\n * Populate the gas properties of the provided transaction meta.\n *\n * @param request - The request object including the necessary parameters.\n */\nexport async function updateGas(request: UpdateGasRequest): Promise<void> {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const [gas, simulationFails, gasLimitNoBuffer, gasRevert] =\n await getGas(request);\n\n txMeta.txParams.gas = gas;\n txMeta.simulationFails = simulationFails;\n txMeta.gasLimitNoBuffer = gasLimitNoBuffer;\n\n if (gasRevert) {\n txMeta.revert = { ...txMeta.revert, gas: gasRevert };\n }\n\n if (!initialParams.gas) {\n txMeta.originalGasEstimate = txMeta.txParams.gas;\n }\n\n txMeta.defaultGasEstimates ??= {};\n txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;\n}\n\n/**\n * Estimate the gas for the provided transaction parameters.\n * If the gas estimate fails, the fallback value is returned.\n *\n * @param options - The options object.\n * @param options.ignoreDelegationSignatures - Ignore signature errors if submitting delegations to the DelegationManager.\n * @param options.isSimulationEnabled - Whether the simulation is enabled.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.messenger - The messenger instance for communication.\n * @param options.networkClientId - The network client ID.\n * @param options.txParams - The transaction parameters.\n * @returns The estimated gas and related info.\n */\nexport async function estimateGas({\n ignoreDelegationSignatures,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n networkClientId,\n txParams,\n}: {\n ignoreDelegationSignatures?: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n networkClientId: NetworkClientId;\n txParams: TransactionParams;\n}): Promise<{\n blockGasLimit: string;\n estimatedGas: string;\n gasRevert?: Revert;\n isUpgradeWithData: boolean;\n simulationFails: TransactionMeta['simulationFails'];\n}> {\n const request = { ...txParams };\n const { authorizationList, data, value } = request;\n const chainId = getChainId({ messenger, networkClientId });\n\n if (ignoreDelegationSignatures && !isSimulationEnabled) {\n throw new Error(\n 'Gas estimation with ignored delegation signatures is not supported as simulation disabled',\n );\n }\n\n const { gasLimit: blockGasLimit, number: blockNumber } = await getLatestBlock(\n messenger,\n networkClientId,\n );\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 let gasRevert: Revert | undefined;\n\n const isUpgradeWithData =\n txParams.type === TransactionEnvelopeType.setCode &&\n Boolean(authorizationList?.length) &&\n Boolean(data) &&\n data !== '0x';\n\n try {\n if (isSimulationEnabled && isUpgradeWithData) {\n estimatedGas = await estimateGasUpgradeWithDataToSelf(\n request,\n messenger,\n networkClientId,\n chainId,\n getSimulationConfig,\n );\n } else if (ignoreDelegationSignatures && isSimulationEnabled) {\n estimatedGas = await simulateGas({\n chainId,\n getSimulationConfig,\n transaction: request,\n });\n } else {\n estimatedGas = await estimateGasNode(messenger, networkClientId, 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 gasRevert = decodeRevert(error, 'gas');\n\n log('Estimation failed', { ...simulationFails, fallback, gasRevert });\n }\n\n return {\n blockGasLimit,\n estimatedGas,\n gasRevert,\n isUpgradeWithData,\n simulationFails,\n };\n}\n\nexport async function estimateGasBatch({\n from,\n getSimulationConfig,\n isAtomicBatchSupported,\n messenger,\n networkClientId,\n transactions,\n}: {\n from: Hex;\n getSimulationConfig: GetSimulationConfig;\n isAtomicBatchSupported: (\n request: IsAtomicBatchSupportedRequest,\n ) => Promise<IsAtomicBatchSupportedResult>;\n messenger: TransactionControllerMessenger;\n networkClientId: NetworkClientId;\n transactions: BatchTransactionParams[];\n}): Promise<EstimateGasBatchResult> {\n const chainId = getChainId({ messenger, networkClientId });\n\n const is7702Result = await isAtomicBatchSupported({\n address: from,\n chainIds: [chainId],\n });\n\n const accountSupports7702 = doesAccountSupportEIP7702(messenger, from);\n\n const chainResult = accountSupports7702\n ? is7702Result.find((result) => result.chainId === chainId)\n : undefined;\n\n const isUpgradeRequired = Boolean(chainResult && !chainResult.isSupported);\n\n if (isUpgradeRequired && !chainResult?.upgradeContractAddress) {\n throw new Error('Upgrade contract address not found');\n }\n\n if (chainResult) {\n const authorizationList = isUpgradeRequired\n ? [{ address: chainResult.upgradeContractAddress as Hex }]\n : undefined;\n\n const type = isUpgradeRequired\n ? TransactionEnvelopeType.setCode\n : undefined;\n\n const params: TransactionParams = {\n ...generateEIP7702BatchTransaction(from, transactions),\n authorizationList,\n from,\n type,\n };\n\n const { estimatedGas: gasLimitHex } = await estimateGas({\n isSimulationEnabled: true,\n getSimulationConfig,\n messenger,\n networkClientId,\n txParams: params,\n });\n\n const totalGasLimit = new BigNumber(gasLimitHex).toNumber();\n\n log('Estimated EIP-7702 gas limit', totalGasLimit);\n\n return {\n gasLimits: [totalGasLimit],\n ...(isUpgradeRequired ? { requiresAuthorizationList: true } : {}),\n totalGasLimit,\n };\n }\n\n const allTransactionsHaveGas = transactions.every(\n (transaction) => transaction.gas !== undefined,\n );\n\n if (allTransactionsHaveGas) {\n const gasLimits = transactions.map((transaction) =>\n new BigNumber(transaction.gas as Hex).toNumber(),\n );\n\n const total = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);\n\n log('Using batch parameter gas limits', { gasLimits, total });\n\n return { totalGasLimit: total, gasLimits };\n }\n\n const { gasLimits: gasLimitsHex } = await simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions: transactions.map((transaction) => ({\n params: transaction,\n })),\n });\n\n const gasLimits = transactions.map((transaction, index) =>\n transaction.gas\n ? new BigNumber(transaction.gas).toNumber()\n : new BigNumber(gasLimitsHex[index]).toNumber(),\n );\n\n const totalGasLimit = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);\n\n log('Simulated batch gas limits', { totalGasLimit, gasLimits });\n\n return { totalGasLimit, gasLimits };\n}\n\n/**\n * Add a buffer to the provided estimated gas.\n * The buffer is calculated based on the block gas limit and a multiplier.\n *\n * @param estimatedGas - The estimated gas.\n * @param blockGasLimit - The block gas limit.\n * @param multiplier - The multiplier to apply to the estimated gas.\n * @returns The gas with the buffer applied.\n */\nexport function addGasBuffer(\n estimatedGas: string,\n blockGasLimit: string,\n multiplier: number,\n): string {\n const estimatedGasBN = hexToBN(estimatedGas);\n\n const maxGasBN = fractionBN(\n hexToBN(blockGasLimit),\n MAX_GAS_BLOCK_PERCENT,\n 100,\n );\n\n const paddedGasBN = fractionBN(estimatedGasBN, multiplier * 100, 100);\n\n if (estimatedGasBN.gt(maxGasBN)) {\n const estimatedGasHex = add0x(estimatedGas);\n log('Using estimated value', estimatedGasHex);\n return estimatedGasHex;\n }\n\n if (paddedGasBN.lt(maxGasBN)) {\n const paddedHex = add0x(BNToHex(paddedGasBN));\n log('Using padded estimate', paddedHex, multiplier);\n return paddedHex;\n }\n\n const maxHex = add0x(BNToHex(maxGasBN));\n log('Using 90% of block gas limit', maxHex);\n return maxHex;\n}\n\n/**\n * Simulate the required gas for a batch of transactions using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transactions.\n * @param options.from - The address of the sender.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transactions - The array of transactions within a batch request.\n * @returns An object containing the transactions with their gas limits and the total gas limit.\n */\nexport async function simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions,\n}: {\n chainId: Hex;\n from: Hex;\n getSimulationConfig: GetSimulationConfig;\n transactions: TransactionBatchSingleRequest[];\n}): Promise<{ totalGasLimit: Hex; gasLimits: Hex[] }> {\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: transactions.map((transaction) => ({\n ...transaction.params,\n from,\n })),\n });\n\n if (response?.transactions?.length !== transactions.length) {\n throw new Error('Simulation response does not match transaction count');\n }\n\n return response.transactions.reduce<{\n totalGasLimit: Hex;\n gasLimits: Hex[];\n }>(\n (acc, transaction) => {\n const gasLimit = transaction?.gasLimit;\n\n if (!gasLimit) {\n throw new Error(\n 'No simulated gas returned for one of the transactions',\n );\n }\n\n acc.gasLimits.push(gasLimit);\n\n acc.totalGasLimit = BNToHex(\n hexToBN(acc.totalGasLimit).add(hexToBN(gasLimit)),\n );\n\n return acc;\n },\n {\n totalGasLimit: '0x0',\n gasLimits: [],\n },\n );\n } catch (error: unknown) {\n log('Error while simulating gas batch', error);\n throw new Error(\n 'Cannot estimate transaction batch total gas as simulation failed',\n );\n }\n}\n\n/**\n * Determine the gas for the provided request.\n *\n * @param request - The request object including the necessary parameters.\n * @returns The final gas value and the estimate used.\n */\nasync function getGas(\n request: UpdateGasRequest,\n): Promise<[string, TransactionMeta['simulationFails']?, string?, Revert?]> {\n const {\n isCustomNetwork,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txMeta,\n } = request;\n const { networkClientId } = txMeta;\n const chainId = getChainId({ messenger, networkClientId });\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 gasRevert,\n isUpgradeWithData,\n simulationFails,\n } = await estimateGas({\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n networkClientId,\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, gasRevert];\n }\n\n const bufferMultiplier = getGasEstimateBuffer({\n chainId,\n isCustomRPC: isCustomNetwork,\n isUpgradeWithData,\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, gasRevert];\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.messenger - The messenger instance for communication.\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 messenger,\n txMeta,\n isCustomNetwork,\n}: UpdateGasRequest): Promise<boolean> {\n const {\n networkClientId,\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(messenger, networkClientId, to);\n\n return !code || code === '0x';\n}\n\n/**\n * Get the contract code for the provided address.\n *\n * @param messenger - The messenger instance for communication.\n * @param networkClientId - The network client ID.\n * @param address - The address to get the code for.\n * @returns The contract code.\n */\nasync function getCode(\n messenger: TransactionControllerMessenger,\n networkClientId: NetworkClientId,\n address: string,\n): Promise<string | undefined> {\n return (await rpcRequest({\n messenger,\n networkClientId,\n method: 'eth_getCode',\n params: [address, 'latest'],\n })) as string | undefined;\n}\n\n/**\n * Get the latest block from the network.\n *\n * @param messenger - The messenger instance for communication.\n * @param networkClientId - The network client ID.\n * @returns The latest block number.\n */\nasync function getLatestBlock(\n messenger: TransactionControllerMessenger,\n networkClientId: NetworkClientId,\n): Promise<{ gasLimit: string; number: string }> {\n return (await rpcRequest({\n messenger,\n networkClientId,\n method: 'eth_getBlockByNumber',\n params: ['latest', false],\n })) as { gasLimit: string; number: string };\n}\n\n/**\n * Estimate the gas for a type 4 transaction.\n *\n * @param txParams - The transaction parameters.\n * @param messenger - The messenger instance for communication.\n * @param networkClientId - The network client ID.\n * @param chainId - The chain ID of the transaction.\n * @param getSimulationConfig - The function to get the simulation configuration.\n * @returns The estimated gas.\n */\nasync function estimateGasUpgradeWithDataToSelf(\n txParams: TransactionParams,\n messenger: TransactionControllerMessenger,\n networkClientId: NetworkClientId,\n chainId: Hex,\n getSimulationConfig: GetSimulationConfig,\n): Promise<Hex> {\n const upgradeGas = (await rpcRequest({\n messenger,\n networkClientId,\n method: 'eth_estimateGas',\n params: [\n {\n ...txParams,\n to: txParams.from,\n data: '0x',\n },\n ],\n })) as Hex;\n\n log('Upgrade only gas', upgradeGas);\n\n const delegationAddress = txParams.authorizationList?.[0].address as Hex;\n\n let executeGas: Hex | undefined;\n\n try {\n executeGas = await simulateGas({\n chainId,\n delegationAddress,\n getSimulationConfig,\n transaction: txParams,\n });\n } catch (error: unknown) {\n log('Error while simulating data portion of upgrade', error);\n }\n\n if (executeGas === undefined) {\n try {\n executeGas = await estimateGasNode(\n messenger,\n networkClientId,\n { ...txParams, authorizationList: undefined, type: undefined },\n delegationAddress,\n );\n } catch (error: unknown) {\n log('Error while estimating data portion of upgrade', error);\n throw error;\n }\n\n log('Success estimating data portion of upgrade', executeGas);\n }\n\n log('Execute gas', executeGas);\n\n const total = BNToHex(\n hexToBN(upgradeGas).add(hexToBN(executeGas)).subn(INTRINSIC_GAS),\n );\n\n log('Total type 4 gas', total);\n\n return total;\n}\n\n/**\n * Simulate the required gas using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transaction.\n * @param options.delegationAddress - The delegation address of the sender to mock.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transaction - The transaction parameters.\n * @returns The simulated gas.\n */\nasync function simulateGas({\n chainId,\n delegationAddress,\n getSimulationConfig,\n transaction,\n}: {\n chainId: Hex;\n delegationAddress?: Hex;\n getSimulationConfig: GetSimulationConfig;\n transaction: TransactionParams;\n}): Promise<Hex> {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n to: transaction.to as Hex,\n from: transaction.from as Hex,\n data: transaction.data as Hex,\n value: transaction.value as Hex,\n },\n ],\n overrides: {\n [transaction.from]: {\n code:\n delegationAddress &&\n ((DELEGATION_PREFIX + remove0x(delegationAddress)) as Hex),\n },\n },\n });\n\n const gasLimit = response?.transactions?.[0].gasLimit;\n\n if (!gasLimit) {\n throw new Error('No simulated gas returned');\n }\n\n return gasLimit;\n}\n\n/**\n * Populate the authorization list with dummy values.\n *\n * @param authorizationList - The authorization list to prepare.\n * @param chainId - The chain ID to use.\n * @returns The authorization list with dummy values.\n */\nfunction normalizeAuthorizationList(\n authorizationList: AuthorizationList | undefined,\n chainId: Hex,\n): AuthorizationList | undefined {\n return authorizationList?.map((authorization) => ({\n ...authorization,\n chainId: authorization.chainId ?? chainId,\n nonce: authorization.nonce ?? '0x1',\n r: authorization.r ?? DUMMY_AUTHORIZATION_SIGNATURE,\n s: authorization.s ?? DUMMY_AUTHORIZATION_SIGNATURE,\n yParity: authorization.yParity ?? '0x1',\n }));\n}\n\n/**\n * Estimate the gas for a transaction using the `eth_estimateGas` method.\n *\n * @param messenger - The messenger instance for communication.\n * @param networkClientId - The network client ID.\n * @param txParams - The transaction parameters.\n * @param delegationAddress - The delegation address of the sender to mock.\n * @returns The estimated gas as a hex string.\n */\nasync function estimateGasNode(\n messenger: TransactionControllerMessenger,\n networkClientId: NetworkClientId,\n txParams: TransactionParams,\n delegationAddress?: Hex,\n): Promise<Hex> {\n const { from } = txParams;\n const params = [txParams] as Json[];\n\n if (delegationAddress) {\n params.push('latest');\n\n params.push({\n [from]: {\n code: DELEGATION_PREFIX + remove0x(delegationAddress),\n },\n });\n }\n\n return (await rpcRequest({\n messenger,\n networkClientId,\n method: 'eth_estimateGas',\n params,\n })) as Hex;\n}\n"]}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.extractRevert = exports.decodeRevert = exports.OnChainFailureError = void 0;
|
|
4
|
+
const abi_1 = require("@ethersproject/abi");
|
|
5
|
+
const logger_1 = require("../logger.cjs");
|
|
6
|
+
const provider_1 = require("./provider.cjs");
|
|
7
|
+
const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'revert-reason');
|
|
8
|
+
const ERROR_SELECTOR = '0x08c379a0';
|
|
9
|
+
const PANIC_SELECTOR = '0x4e487b71';
|
|
10
|
+
/**
|
|
11
|
+
* Solidity panic code descriptions.
|
|
12
|
+
*
|
|
13
|
+
* @see https://docs.soliditylang.org/en/latest/control-structures.html#panic-via-assert-and-error-via-require
|
|
14
|
+
*/
|
|
15
|
+
const PANIC_CODE_MESSAGES = {
|
|
16
|
+
'0x00': 'Generic compiler panic',
|
|
17
|
+
'0x01': 'Assertion failed',
|
|
18
|
+
'0x11': 'Arithmetic overflow or underflow',
|
|
19
|
+
'0x12': 'Division or modulo by zero',
|
|
20
|
+
'0x21': 'Invalid enum value',
|
|
21
|
+
'0x22': 'Incorrectly encoded storage byte array',
|
|
22
|
+
'0x31': 'Pop on empty array',
|
|
23
|
+
'0x32': 'Array index out of bounds',
|
|
24
|
+
'0x41': 'Memory allocation overflow',
|
|
25
|
+
'0x51': 'Call to zero-initialized function',
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Error thrown by `PendingTransactionTracker` when a transaction failed
|
|
29
|
+
* on-chain, carrying any decoded revert.
|
|
30
|
+
*/
|
|
31
|
+
class OnChainFailureError extends Error {
|
|
32
|
+
constructor(revert) {
|
|
33
|
+
const suffix = revert?.message ? `: ${revert.message}` : '';
|
|
34
|
+
super(`Transaction failed on-chain${suffix}`);
|
|
35
|
+
this.name = 'OnChainFailureError';
|
|
36
|
+
this.revert = revert;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
exports.OnChainFailureError = OnChainFailureError;
|
|
40
|
+
/**
|
|
41
|
+
* Decode an EVM revert into a `Revert` containing both the decoded
|
|
42
|
+
* human-readable message and the original raw `data`. Accepts either a
|
|
43
|
+
* raw revert data hex string, or a thrown JSON-RPC error of the shape
|
|
44
|
+
* `{ data: Hex | { data: Hex } }`. Handles `Error(string)`,
|
|
45
|
+
* `Panic(uint256)`, and falls back to a raw `Custom error: 0x<selector>`
|
|
46
|
+
* reference for unknown custom errors.
|
|
47
|
+
*
|
|
48
|
+
* @param input - Raw revert data hex, or a thrown JSON-RPC error.
|
|
49
|
+
* @param source - Optional label included in debug logs to identify the
|
|
50
|
+
* caller (e.g. `gas`, `simulation`).
|
|
51
|
+
* @returns A `Revert` if any data was found, otherwise `undefined`.
|
|
52
|
+
*/
|
|
53
|
+
function decodeRevert(input, source) {
|
|
54
|
+
const data = toRevertDataHex(input);
|
|
55
|
+
if (!data) {
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
const message = decodeMessage(data);
|
|
59
|
+
const revert = {
|
|
60
|
+
...(message ? { message } : {}),
|
|
61
|
+
data,
|
|
62
|
+
};
|
|
63
|
+
logRevert(source, revert);
|
|
64
|
+
return revert;
|
|
65
|
+
}
|
|
66
|
+
exports.decodeRevert = decodeRevert;
|
|
67
|
+
/**
|
|
68
|
+
* Replay a transaction that failed on-chain via `eth_estimateGas` to
|
|
69
|
+
* recover the revert reason. `eth_estimateGas` is used instead of
|
|
70
|
+
* `eth_call` to avoid `RetryOnEmptyMiddleware`, which retries reverted
|
|
71
|
+
* `eth_call` responses 10 times and discards the original error data.
|
|
72
|
+
*
|
|
73
|
+
* Always resolves; never throws.
|
|
74
|
+
*
|
|
75
|
+
* @param input - Extraction inputs.
|
|
76
|
+
* @param input.messenger - Transaction controller messenger.
|
|
77
|
+
* @param input.networkClientId - Network client ID to replay against.
|
|
78
|
+
* @param input.txParams - Transaction parameters for the failed tx.
|
|
79
|
+
* @returns A `Revert`, or `undefined` if none could be observed.
|
|
80
|
+
*/
|
|
81
|
+
async function extractRevert({ messenger, networkClientId, txParams, }) {
|
|
82
|
+
if (!txParams?.to && !txParams?.data) {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
const callParams = {};
|
|
86
|
+
if (txParams.from) {
|
|
87
|
+
callParams.from = txParams.from;
|
|
88
|
+
}
|
|
89
|
+
if (txParams.to) {
|
|
90
|
+
callParams.to = txParams.to;
|
|
91
|
+
}
|
|
92
|
+
if (txParams.data) {
|
|
93
|
+
callParams.data = txParams.data;
|
|
94
|
+
}
|
|
95
|
+
if (txParams.value) {
|
|
96
|
+
callParams.value = txParams.value;
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
await (0, provider_1.rpcRequest)({
|
|
100
|
+
messenger,
|
|
101
|
+
networkClientId,
|
|
102
|
+
// `eth_estimateGas` is used instead of `eth_call` to bypass
|
|
103
|
+
// `RetryOnEmptyMiddleware`, which retries reverted `eth_call`
|
|
104
|
+
// responses and discards the original revert data.
|
|
105
|
+
method: 'eth_estimateGas',
|
|
106
|
+
params: [callParams],
|
|
107
|
+
});
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
return decodeRevert(error, 'receipt');
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
exports.extractRevert = extractRevert;
|
|
115
|
+
/**
|
|
116
|
+
* Coerce a `RevertInput` to a non-empty revert data hex string.
|
|
117
|
+
*
|
|
118
|
+
* @param input - Raw hex or thrown JSON-RPC error.
|
|
119
|
+
* @returns The revert data hex, or `undefined`.
|
|
120
|
+
*/
|
|
121
|
+
function toRevertDataHex(input) {
|
|
122
|
+
if (isHex(input)) {
|
|
123
|
+
return input;
|
|
124
|
+
}
|
|
125
|
+
if (typeof input !== 'object' || input === null) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const { data } = input;
|
|
129
|
+
if (isHex(data)) {
|
|
130
|
+
return data;
|
|
131
|
+
}
|
|
132
|
+
if (typeof data === 'object' && data !== null && isHex(data.data)) {
|
|
133
|
+
return data.data;
|
|
134
|
+
}
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Type guard for non-empty `0x`-prefixed hex strings.
|
|
139
|
+
*
|
|
140
|
+
* @param value - Value to test.
|
|
141
|
+
* @returns Whether the value is a non-empty hex string.
|
|
142
|
+
*/
|
|
143
|
+
function isHex(value) {
|
|
144
|
+
return typeof value === 'string' && value.startsWith('0x') && value !== '0x';
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Decode raw revert data into a human-readable string.
|
|
148
|
+
*
|
|
149
|
+
* @param data - Raw revert data hex.
|
|
150
|
+
* @returns Decoded message, or `undefined` if undecodable.
|
|
151
|
+
*/
|
|
152
|
+
function decodeMessage(data) {
|
|
153
|
+
if (!data || data === '0x') {
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
if (data.length < 10) {
|
|
157
|
+
return `execution reverted (${data})`;
|
|
158
|
+
}
|
|
159
|
+
const selector = data.slice(0, 10).toLowerCase();
|
|
160
|
+
const payload = `0x${data.slice(10)}`;
|
|
161
|
+
if (selector === ERROR_SELECTOR) {
|
|
162
|
+
try {
|
|
163
|
+
const [reason] = abi_1.defaultAbiCoder.decode(['string'], payload);
|
|
164
|
+
return typeof reason === 'string' ? reason : undefined;
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (selector === PANIC_SELECTOR) {
|
|
171
|
+
try {
|
|
172
|
+
const [code] = abi_1.defaultAbiCoder.decode(['uint256'], payload);
|
|
173
|
+
const codeHex = code.toHexString().toLowerCase();
|
|
174
|
+
const description = PANIC_CODE_MESSAGES[codeHex] ?? 'Unknown panic';
|
|
175
|
+
return `Panic: ${description}`;
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return `Custom error: ${selector}`;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Emit a single structured debug line for a decoded revert.
|
|
185
|
+
*
|
|
186
|
+
* @param source - Source label, when known.
|
|
187
|
+
* @param revert - Resolved Revert.
|
|
188
|
+
*/
|
|
189
|
+
function logRevert(source, revert) {
|
|
190
|
+
log('Decoded revert', source ?? 'unknown', revert);
|
|
191
|
+
}
|
|
192
|
+
//# sourceMappingURL=revert-reason.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"revert-reason.cjs","sourceRoot":"","sources":["../../src/utils/revert-reason.ts"],"names":[],"mappings":";;;AAAA,4CAAqD;AAIrD,0CAA8D;AAG9D,6CAAwC;AAExC,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,eAAe,CAAC,CAAC;AAE/D,MAAM,cAAc,GAAG,YAAY,CAAC;AACpC,MAAM,cAAc,GAAG,YAAY,CAAC;AAEpC;;;;GAIG;AACH,MAAM,mBAAmB,GAA2B;IAClD,MAAM,EAAE,wBAAwB;IAChC,MAAM,EAAE,kBAAkB;IAC1B,MAAM,EAAE,kCAAkC;IAC1C,MAAM,EAAE,4BAA4B;IACpC,MAAM,EAAE,oBAAoB;IAC5B,MAAM,EAAE,wCAAwC;IAChD,MAAM,EAAE,oBAAoB;IAC5B,MAAM,EAAE,2BAA2B;IACnC,MAAM,EAAE,4BAA4B;IACpC,MAAM,EAAE,mCAAmC;CAC5C,CAAC;AAaF;;;GAGG;AACH,MAAa,mBAAoB,SAAQ,KAAK;IAG5C,YAAY,MAAe;QACzB,MAAM,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5D,KAAK,CAAC,8BAA8B,MAAM,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;QAClC,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Content":["import { defaultAbiCoder } from '@ethersproject/abi';\nimport type { NetworkClientId } from '@metamask/network-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { Revert, TransactionParams } from '../types';\nimport { rpcRequest } from './provider';\n\nconst log = createModuleLogger(projectLogger, 'revert-reason');\n\nconst ERROR_SELECTOR = '0x08c379a0';\nconst PANIC_SELECTOR = '0x4e487b71';\n\n/**\n * Solidity panic code descriptions.\n *\n * @see https://docs.soliditylang.org/en/latest/control-structures.html#panic-via-assert-and-error-via-require\n */\nconst PANIC_CODE_MESSAGES: Record<string, string> = {\n '0x00': 'Generic compiler panic',\n '0x01': 'Assertion failed',\n '0x11': 'Arithmetic overflow or underflow',\n '0x12': 'Division or modulo by zero',\n '0x21': 'Invalid enum value',\n '0x22': 'Incorrectly encoded storage byte array',\n '0x31': 'Pop on empty array',\n '0x32': 'Array index out of bounds',\n '0x41': 'Memory allocation overflow',\n '0x51': 'Call to zero-initialized function',\n};\n\n/**\n * Input accepted by `decodeRevert`. Either raw revert data hex, or a\n * thrown JSON-RPC error carrying the data on `data` (standard) or\n * nested `data.data` (some older node forks).\n */\ntype RevertInput =\n | Hex\n | undefined\n | { data?: Hex | { data?: Hex } | null }\n | null;\n\n/**\n * Error thrown by `PendingTransactionTracker` when a transaction failed\n * on-chain, carrying any decoded revert.\n */\nexport class OnChainFailureError extends Error {\n readonly revert?: Revert;\n\n constructor(revert?: Revert) {\n const suffix = revert?.message ? `: ${revert.message}` : '';\n super(`Transaction failed on-chain${suffix}`);\n this.name = 'OnChainFailureError';\n this.revert = revert;\n }\n}\n\n/**\n * Decode an EVM revert into a `Revert` containing both the decoded\n * human-readable message and the original raw `data`. Accepts either a\n * raw revert data hex string, or a thrown JSON-RPC error of the shape\n * `{ data: Hex | { data: Hex } }`. Handles `Error(string)`,\n * `Panic(uint256)`, and falls back to a raw `Custom error: 0x<selector>`\n * reference for unknown custom errors.\n *\n * @param input - Raw revert data hex, or a thrown JSON-RPC error.\n * @param source - Optional label included in debug logs to identify the\n * caller (e.g. `gas`, `simulation`).\n * @returns A `Revert` if any data was found, otherwise `undefined`.\n */\nexport function decodeRevert(\n input: RevertInput,\n source?: string,\n): Revert | undefined {\n const data = toRevertDataHex(input);\n if (!data) {\n return undefined;\n }\n\n const message = decodeMessage(data);\n const revert: Revert = {\n ...(message ? { message } : {}),\n data,\n };\n\n logRevert(source, revert);\n return revert;\n}\n\n/**\n * Replay a transaction that failed on-chain via `eth_estimateGas` to\n * recover the revert reason. `eth_estimateGas` is used instead of\n * `eth_call` to avoid `RetryOnEmptyMiddleware`, which retries reverted\n * `eth_call` responses 10 times and discards the original error data.\n *\n * Always resolves; never throws.\n *\n * @param input - Extraction inputs.\n * @param input.messenger - Transaction controller messenger.\n * @param input.networkClientId - Network client ID to replay against.\n * @param input.txParams - Transaction parameters for the failed tx.\n * @returns A `Revert`, or `undefined` if none could be observed.\n */\nexport async function extractRevert({\n messenger,\n networkClientId,\n txParams,\n}: {\n messenger: TransactionControllerMessenger;\n networkClientId: NetworkClientId;\n txParams: TransactionParams;\n}): Promise<Revert | undefined> {\n if (!txParams?.to && !txParams?.data) {\n return undefined;\n }\n\n const callParams: Record<string, string> = {};\n if (txParams.from) {\n callParams.from = txParams.from;\n }\n if (txParams.to) {\n callParams.to = txParams.to;\n }\n if (txParams.data) {\n callParams.data = txParams.data;\n }\n if (txParams.value) {\n callParams.value = txParams.value;\n }\n\n try {\n await rpcRequest({\n messenger,\n networkClientId,\n // `eth_estimateGas` is used instead of `eth_call` to bypass\n // `RetryOnEmptyMiddleware`, which retries reverted `eth_call`\n // responses and discards the original revert data.\n method: 'eth_estimateGas',\n params: [callParams],\n });\n return undefined;\n } catch (error: unknown) {\n return decodeRevert(error as RevertInput, 'receipt');\n }\n}\n\n/**\n * Coerce a `RevertInput` to a non-empty revert data hex string.\n *\n * @param input - Raw hex or thrown JSON-RPC error.\n * @returns The revert data hex, or `undefined`.\n */\nfunction toRevertDataHex(input: RevertInput): Hex | undefined {\n if (isHex(input)) {\n return input;\n }\n\n if (typeof input !== 'object' || input === null) {\n return undefined;\n }\n\n const { data } = input;\n if (isHex(data)) {\n return data;\n }\n\n if (typeof data === 'object' && data !== null && isHex(data.data)) {\n return data.data;\n }\n\n return undefined;\n}\n\n/**\n * Type guard for non-empty `0x`-prefixed hex strings.\n *\n * @param value - Value to test.\n * @returns Whether the value is a non-empty hex string.\n */\nfunction isHex(value: unknown): value is Hex {\n return typeof value === 'string' && value.startsWith('0x') && value !== '0x';\n}\n\n/**\n * Decode raw revert data into a human-readable string.\n *\n * @param data - Raw revert data hex.\n * @returns Decoded message, or `undefined` if undecodable.\n */\nfunction decodeMessage(data: Hex | undefined): string | undefined {\n if (!data || data === '0x') {\n return undefined;\n }\n\n if (data.length < 10) {\n return `execution reverted (${data})`;\n }\n\n const selector = data.slice(0, 10).toLowerCase();\n const payload = `0x${data.slice(10)}`;\n\n if (selector === ERROR_SELECTOR) {\n try {\n const [reason] = defaultAbiCoder.decode(['string'], payload);\n return typeof reason === 'string' ? reason : undefined;\n } catch {\n return undefined;\n }\n }\n\n if (selector === PANIC_SELECTOR) {\n try {\n const [code] = defaultAbiCoder.decode(['uint256'], payload) as [\n { toHexString: () => string },\n ];\n const codeHex = code.toHexString().toLowerCase() as Hex;\n const description = PANIC_CODE_MESSAGES[codeHex] ?? 'Unknown panic';\n return `Panic: ${description}`;\n } catch {\n return undefined;\n }\n }\n\n return `Custom error: ${selector}`;\n}\n\n/**\n * Emit a single structured debug line for a decoded revert.\n *\n * @param source - Source label, when known.\n * @param revert - Resolved Revert.\n */\nfunction logRevert(source: string | undefined, revert: Revert): void {\n log('Decoded revert', source ?? 'unknown', revert);\n}\n"]}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { NetworkClientId } from "@metamask/network-controller";
|
|
2
|
+
import type { Hex } from "@metamask/utils";
|
|
3
|
+
import type { TransactionControllerMessenger } from "../TransactionController.cjs";
|
|
4
|
+
import type { Revert, TransactionParams } from "../types.cjs";
|
|
5
|
+
/**
|
|
6
|
+
* Input accepted by `decodeRevert`. Either raw revert data hex, or a
|
|
7
|
+
* thrown JSON-RPC error carrying the data on `data` (standard) or
|
|
8
|
+
* nested `data.data` (some older node forks).
|
|
9
|
+
*/
|
|
10
|
+
type RevertInput = Hex | undefined | {
|
|
11
|
+
data?: Hex | {
|
|
12
|
+
data?: Hex;
|
|
13
|
+
} | null;
|
|
14
|
+
} | null;
|
|
15
|
+
/**
|
|
16
|
+
* Error thrown by `PendingTransactionTracker` when a transaction failed
|
|
17
|
+
* on-chain, carrying any decoded revert.
|
|
18
|
+
*/
|
|
19
|
+
export declare class OnChainFailureError extends Error {
|
|
20
|
+
readonly revert?: Revert;
|
|
21
|
+
constructor(revert?: Revert);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Decode an EVM revert into a `Revert` containing both the decoded
|
|
25
|
+
* human-readable message and the original raw `data`. Accepts either a
|
|
26
|
+
* raw revert data hex string, or a thrown JSON-RPC error of the shape
|
|
27
|
+
* `{ data: Hex | { data: Hex } }`. Handles `Error(string)`,
|
|
28
|
+
* `Panic(uint256)`, and falls back to a raw `Custom error: 0x<selector>`
|
|
29
|
+
* reference for unknown custom errors.
|
|
30
|
+
*
|
|
31
|
+
* @param input - Raw revert data hex, or a thrown JSON-RPC error.
|
|
32
|
+
* @param source - Optional label included in debug logs to identify the
|
|
33
|
+
* caller (e.g. `gas`, `simulation`).
|
|
34
|
+
* @returns A `Revert` if any data was found, otherwise `undefined`.
|
|
35
|
+
*/
|
|
36
|
+
export declare function decodeRevert(input: RevertInput, source?: string): Revert | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* Replay a transaction that failed on-chain via `eth_estimateGas` to
|
|
39
|
+
* recover the revert reason. `eth_estimateGas` is used instead of
|
|
40
|
+
* `eth_call` to avoid `RetryOnEmptyMiddleware`, which retries reverted
|
|
41
|
+
* `eth_call` responses 10 times and discards the original error data.
|
|
42
|
+
*
|
|
43
|
+
* Always resolves; never throws.
|
|
44
|
+
*
|
|
45
|
+
* @param input - Extraction inputs.
|
|
46
|
+
* @param input.messenger - Transaction controller messenger.
|
|
47
|
+
* @param input.networkClientId - Network client ID to replay against.
|
|
48
|
+
* @param input.txParams - Transaction parameters for the failed tx.
|
|
49
|
+
* @returns A `Revert`, or `undefined` if none could be observed.
|
|
50
|
+
*/
|
|
51
|
+
export declare function extractRevert({ messenger, networkClientId, txParams, }: {
|
|
52
|
+
messenger: TransactionControllerMessenger;
|
|
53
|
+
networkClientId: NetworkClientId;
|
|
54
|
+
txParams: TransactionParams;
|
|
55
|
+
}): Promise<Revert | undefined>;
|
|
56
|
+
export {};
|
|
57
|
+
//# sourceMappingURL=revert-reason.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"revert-reason.d.cts","sourceRoot":"","sources":["../../src/utils/revert-reason.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,qCAAqC;AACpE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAC/E,OAAO,KAAK,EAAE,MAAM,EAAE,iBAAiB,EAAE,qBAAiB;AA0B1D;;;;GAIG;AACH,KAAK,WAAW,GACZ,GAAG,GACH,SAAS,GACT;IAAE,IAAI,CAAC,EAAE,GAAG,GAAG;QAAE,IAAI,CAAC,EAAE,GAAG,CAAA;KAAE,GAAG,IAAI,CAAA;CAAE,GACtC,IAAI,CAAC;AAET;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;gBAEb,MAAM,CAAC,EAAE,MAAM;CAM5B;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAC1B,KAAK,EAAE,WAAW,EAClB,MAAM,CAAC,EAAE,MAAM,GACd,MAAM,GAAG,SAAS,CAcpB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,aAAa,CAAC,EAClC,SAAS,EACT,eAAe,EACf,QAAQ,GACT,EAAE;IACD,SAAS,EAAE,8BAA8B,CAAC;IAC1C,eAAe,EAAE,eAAe,CAAC;IACjC,QAAQ,EAAE,iBAAiB,CAAC;CAC7B,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAiC9B"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { NetworkClientId } from "@metamask/network-controller";
|
|
2
|
+
import type { Hex } from "@metamask/utils";
|
|
3
|
+
import type { TransactionControllerMessenger } from "../TransactionController.mjs";
|
|
4
|
+
import type { Revert, TransactionParams } from "../types.mjs";
|
|
5
|
+
/**
|
|
6
|
+
* Input accepted by `decodeRevert`. Either raw revert data hex, or a
|
|
7
|
+
* thrown JSON-RPC error carrying the data on `data` (standard) or
|
|
8
|
+
* nested `data.data` (some older node forks).
|
|
9
|
+
*/
|
|
10
|
+
type RevertInput = Hex | undefined | {
|
|
11
|
+
data?: Hex | {
|
|
12
|
+
data?: Hex;
|
|
13
|
+
} | null;
|
|
14
|
+
} | null;
|
|
15
|
+
/**
|
|
16
|
+
* Error thrown by `PendingTransactionTracker` when a transaction failed
|
|
17
|
+
* on-chain, carrying any decoded revert.
|
|
18
|
+
*/
|
|
19
|
+
export declare class OnChainFailureError extends Error {
|
|
20
|
+
readonly revert?: Revert;
|
|
21
|
+
constructor(revert?: Revert);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Decode an EVM revert into a `Revert` containing both the decoded
|
|
25
|
+
* human-readable message and the original raw `data`. Accepts either a
|
|
26
|
+
* raw revert data hex string, or a thrown JSON-RPC error of the shape
|
|
27
|
+
* `{ data: Hex | { data: Hex } }`. Handles `Error(string)`,
|
|
28
|
+
* `Panic(uint256)`, and falls back to a raw `Custom error: 0x<selector>`
|
|
29
|
+
* reference for unknown custom errors.
|
|
30
|
+
*
|
|
31
|
+
* @param input - Raw revert data hex, or a thrown JSON-RPC error.
|
|
32
|
+
* @param source - Optional label included in debug logs to identify the
|
|
33
|
+
* caller (e.g. `gas`, `simulation`).
|
|
34
|
+
* @returns A `Revert` if any data was found, otherwise `undefined`.
|
|
35
|
+
*/
|
|
36
|
+
export declare function decodeRevert(input: RevertInput, source?: string): Revert | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* Replay a transaction that failed on-chain via `eth_estimateGas` to
|
|
39
|
+
* recover the revert reason. `eth_estimateGas` is used instead of
|
|
40
|
+
* `eth_call` to avoid `RetryOnEmptyMiddleware`, which retries reverted
|
|
41
|
+
* `eth_call` responses 10 times and discards the original error data.
|
|
42
|
+
*
|
|
43
|
+
* Always resolves; never throws.
|
|
44
|
+
*
|
|
45
|
+
* @param input - Extraction inputs.
|
|
46
|
+
* @param input.messenger - Transaction controller messenger.
|
|
47
|
+
* @param input.networkClientId - Network client ID to replay against.
|
|
48
|
+
* @param input.txParams - Transaction parameters for the failed tx.
|
|
49
|
+
* @returns A `Revert`, or `undefined` if none could be observed.
|
|
50
|
+
*/
|
|
51
|
+
export declare function extractRevert({ messenger, networkClientId, txParams, }: {
|
|
52
|
+
messenger: TransactionControllerMessenger;
|
|
53
|
+
networkClientId: NetworkClientId;
|
|
54
|
+
txParams: TransactionParams;
|
|
55
|
+
}): Promise<Revert | undefined>;
|
|
56
|
+
export {};
|
|
57
|
+
//# sourceMappingURL=revert-reason.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"revert-reason.d.mts","sourceRoot":"","sources":["../../src/utils/revert-reason.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,qCAAqC;AACpE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAC/E,OAAO,KAAK,EAAE,MAAM,EAAE,iBAAiB,EAAE,qBAAiB;AA0B1D;;;;GAIG;AACH,KAAK,WAAW,GACZ,GAAG,GACH,SAAS,GACT;IAAE,IAAI,CAAC,EAAE,GAAG,GAAG;QAAE,IAAI,CAAC,EAAE,GAAG,CAAA;KAAE,GAAG,IAAI,CAAA;CAAE,GACtC,IAAI,CAAC;AAET;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;gBAEb,MAAM,CAAC,EAAE,MAAM;CAM5B;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAC1B,KAAK,EAAE,WAAW,EAClB,MAAM,CAAC,EAAE,MAAM,GACd,MAAM,GAAG,SAAS,CAcpB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,aAAa,CAAC,EAClC,SAAS,EACT,eAAe,EACf,QAAQ,GACT,EAAE;IACD,SAAS,EAAE,8BAA8B,CAAC;IAC1C,eAAe,EAAE,eAAe,CAAC;IACjC,QAAQ,EAAE,iBAAiB,CAAC;CAC7B,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAiC9B"}
|