Profile gas usage
Every test's transactions are profiled, passing or failing: read the running
test's profile with currentProfile():
const { gas } = await anvil.diagnostics.currentProfile();
expect(gas.transactions.map((tx) => [tx.function, tx.status])).toEqual([
["approve(address,uint256)", "success"],
["deposit(uint256)", "success"],
]);
const [approve, deposit] = gas.transactions;
expect(gas.total).toBe(approve.gasUsed + deposit.gasUsed);
expect(deposit.gasUsed).toBe(Number(receipt.gasUsed));
// With --steps-tracing: where the deposit's gas went.
const expensive = deposit.opcodes!.opcodes.map((op) => op.op);
expect(expensive).toEqual(
expect.arrayContaining(["SSTORE", "SLOAD", "CALL", "LOG3"]),
);
expect(deposit.opcodes!.executionGas + deposit.opcodes!.intrinsicGas).toBe(
deposit.gasUsed,
);
Tested in examples/test/e2e/diagnostics-and-profiling.e2e.test.ts:87
opcodes lists the expensive opcodes (storage, calls, creates, logs,
hashing, external code: EXPENSIVE_OPCODES) plus any using at least 5 % of
the execution gas. It needs anvil's --steps-tracing
(evm.withStepsTracing()); without it, gas.opcodeProfiling is
"unavailable" and reports say how to turn it on.
One operation
const { result: receipt, profile } = await anvil.diagnostics.measure(
"approve and deposit",
() => approveAndDeposit(bob, parseEther("2")),
);
expect(receipt.status).toBe("success");
expect(profile.gas.transactions).toHaveLength(2);
expect(profile.gas.total).toBeLessThan(200_000); // the operation's budget
const calls = (method: string) =>
profile.rpc.methods.find((m) => m.method === method)?.count ?? 0;
expect(calls("eth_sendTransaction")).toBe(2);
expect(calls("eth_getTransactionReceipt")).toBeGreaterThanOrEqual(2); // confirm() may poll
Tested in examples/test/e2e/diagnostics-and-profiling.e2e.test.ts:109
Reverted and refused transactions
// bob deposits without approving: mined, but reverted.
const hash = await anvil.testClientFor(bob).writeContract({
address: vault,
abi: timeLockVault.abi,
functionName: "deposit",
args: [1n],
});
await anvil.confirm(hash, { throwOnRevert: false });
const { gas } = await anvil.diagnostics.currentProfile();
expect(gas.reverted).toBe(1);
expect(gas.transactions[0]).toEqual(
expect.objectContaining({
hash,
status: "reverted",
function: "deposit(uint256)",
revert: expect.objectContaining({
errorName: "InsufficientAllowance",
reason: `InsufficientAllowance(${vault}, 0, 1)`,
}) as unknown,
}),
);
expect(gas.total).toBeGreaterThan(0); // reverted transactions cost gas too
Tested in examples/test/e2e/diagnostics-and-profiling.e2e.test.ts:143
A send the node refuses (insufficient funds, bad nonce) is listed as
"rejected" with the node's error and gasUsed: 0.