Skip to content

feat: fallback to node with overrides for type-4 gas estimation #6016

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/transaction-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add optional `ignoreDelegationSignatures` boolean to `estimateGas` method.
- Add `gasFeeEstimates` property to `TransactionBatchMeta`, populated using `DefaultGasFeeFlow` ([#5886](https://github.com/MetaMask/core/pull/5886))

### Changed

- Estimate gas for type-4 transactions with `data` using `eth_estimateGas` and state overrides if simulation fails [#6016](https://github.com/MetaMask/core/pull/6016))

### Fixed

- Handle unknown chain IDs on incoming transactions ([#5985](https://github.com/MetaMask/core/pull/5985))
Expand Down
55 changes: 53 additions & 2 deletions packages/transaction-controller/src/utils/gas.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,16 @@ describe('gas', () => {
* @param options.getBlockByNumberResponse - The response for getBlockByNumber.
* @param options.estimateGasResponse - The response for estimateGas.
* @param options.estimateGasError - The error for estimateGas.
* @param options.estimateGasOverridesResponse - The response for estimateGas with overrides.
* @param options.estimateGasOverridesError - The error for estimateGas with overrides.
*/
function mockQuery({
getCodeResponse,
getBlockByNumberResponse,
estimateGasResponse,
estimateGasError,
estimateGasOverridesResponse,
estimateGasOverridesError,
}: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getCodeResponse?: any;
Expand All @@ -130,6 +134,10 @@ describe('gas', () => {
estimateGasResponse?: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
estimateGasError?: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
estimateGasOverridesResponse?: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
estimateGasOverridesError?: any;
}) {
if (getCodeResponse !== undefined) {
queryMock.mockResolvedValueOnce(getCodeResponse);
Expand All @@ -144,6 +152,12 @@ describe('gas', () => {
} else {
queryMock.mockResolvedValueOnce(estimateGasResponse);
}

if (estimateGasOverridesError) {
queryMock.mockRejectedValueOnce(estimateGasOverridesError);
} else {
queryMock.mockResolvedValueOnce(estimateGasOverridesResponse);
}
}

/**
Expand Down Expand Up @@ -825,10 +839,47 @@ describe('gas', () => {
});
});

it('uses fallback if simulation fails', async () => {
it('uses node with overrides if simulation fails', async () => {
mockQuery({
getBlockByNumberResponse: { gasLimit: toHex(BLOCK_GAS_LIMIT_MOCK) },
estimateGasResponse: toHex(GAS_2_MOCK),
estimateGasOverridesResponse: toHex(SIMULATE_GAS_MOCK),
});

simulateTransactionsMock.mockResolvedValueOnce({
transactions: [
{
gasUsed: undefined,
},
],
} as SimulationResponse);

const result = await estimateGas({
chainId: CHAIN_ID_MOCK,
ethQuery: ETH_QUERY_MOCK,
isSimulationEnabled: true,
messenger: MESSENGER_MOCK,
txParams: {
...TRANSACTION_META_MOCK.txParams,
authorizationList: AUTHORIZATION_LIST_MOCK,
to: TRANSACTION_META_MOCK.txParams.from,
type: TransactionEnvelopeType.setCode,
},
});

expect(result).toStrictEqual({
estimatedGas: toHex(GAS_2_MOCK + SIMULATE_GAS_MOCK - INTRINSIC_GAS),
blockGasLimit: toHex(BLOCK_GAS_LIMIT_MOCK),
isUpgradeWithDataToSelf: true,
simulationFails: undefined,
});
});

it('uses gas limit fallback if simulation and node overrides fail', async () => {
mockQuery({
getBlockByNumberResponse: { gasLimit: toHex(BLOCK_GAS_LIMIT_MOCK) },
estimateGasResponse: toHex(GAS_2_MOCK),
estimateGasOverridesError: new Error('Estimate failed'),
});

simulateTransactionsMock.mockResolvedValueOnce({
Expand Down Expand Up @@ -862,7 +913,7 @@ describe('gas', () => {
blockNumber: undefined,
},
errorKey: undefined,
reason: 'No simulated gas returned',
reason: 'Estimate failed',
},
});
});
Expand Down
68 changes: 60 additions & 8 deletions packages/transaction-controller/src/utils/gas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
toHex,
} from '@metamask/controller-utils';
import type EthQuery from '@metamask/eth-query';
import type { Hex } from '@metamask/utils';
import type { Hex, Json } from '@metamask/utils';
import { add0x, createModuleLogger, remove0x } from '@metamask/utils';
import { BN } from 'bn.js';

Expand Down Expand Up @@ -151,7 +151,7 @@ export async function estimateGas({
transaction: request,
});
} else {
estimatedGas = await query(ethQuery, 'estimateGas', [request]);
estimatedGas = await estimateGasNode(ethQuery, request);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
Expand Down Expand Up @@ -424,16 +424,39 @@ async function estimateGasUpgradeWithDataToSelf(

const delegationAddress = txParams.authorizationList?.[0].address as Hex;

const executeGas = await simulateGas({
chainId: chainId as Hex,
delegationAddress,
transaction: txParams,
});
let executeGas: Hex | undefined;

try {
executeGas = await simulateGas({
chainId: chainId as Hex,
delegationAddress,
transaction: txParams,
});
} catch (error: unknown) {
log('Error while simulating data portion of upgrade', error);
}

if (executeGas === undefined) {
try {
executeGas = await estimateGasNode(
ethQuery,
{ ...txParams, authorizationList: undefined, type: undefined },
delegationAddress,
);
} catch (error: unknown) {
log('Error while estimating data portion of upgrade', error);
throw error;
}

log('Success estimating data portion of upgrade', executeGas);
}

log('Execute gas', executeGas);

const total = BNToHex(
hexToBN(upgradeGas).add(hexToBN(executeGas)).subn(INTRINSIC_GAS),
hexToBN(upgradeGas)
.add(hexToBN(executeGas as Hex))
.subn(INTRINSIC_GAS),
);

log('Total type 4 gas', total);
Expand Down Expand Up @@ -506,3 +529,32 @@ function normalizeAuthorizationList(
yParity: authorization.yParity ?? '0x1',
}));
}

/**
* Estimate the gas for a transaction using the `eth_estimateGas` method.
*
* @param ethQuery - The EthQuery instance to interact with the network.
* @param txParams - The transaction parameters.
* @param delegationAddress - The delegation address of the sender to mock.
* @returns The estimated gas as a hex string.
*/
function estimateGasNode(
ethQuery: EthQuery,
txParams: TransactionParams,
delegationAddress?: Hex,
) {
const { from } = txParams;
const params = [txParams] as Json[];

if (delegationAddress) {
params.push('latest');

params.push({
[from as string]: {
code: DELEGATION_PREFIX + remove0x(delegationAddress),
},
});
}

return query(ethQuery, 'estimateGas', params);
}
Loading