gas metering
Gas metering is how the EVM charges for work. Every opcode has a price in 'gas', a unit of computational effort, and as a transaction executes the EVM deducts that price from a budget the sender set in advance. Think of it like a taxi meter: the longer and harder the computation runs, the more it ticks up, and when the money runs out the ride stops. This solves a deep problem — without a cost on computation, a malicious contract could loop forever and freeze the network.
Before any opcode runs, the transaction pays intrinsic gas: a flat 21,000 for a base transaction, plus a charge for every byte of calldata (4 gas per zero byte, 16 per non-zero byte under EIP-2028). Then execution proceeds opcode by opcode. Costs span a wide range: trivial arithmetic costs 3 gas, a JUMPDEST costs 1, while an SSTORE that turns a zero slot non-zero costs 20,000. Memory is charged with a quadratic expansion term, and since EIP-2929 the first ('cold') access to a storage slot or account in a transaction costs far more than later ('warm') accesses (a cold SLOAD is 2,100 gas, a warm one 100).
The sender specifies a gas limit — the maximum gas they will allow. If execution finishes under that limit, unused gas is refunded; if it hits the limit, the EVM throws an out-of-gas exception, reverts all state changes from that transaction, but still keeps the gas already spent as payment for the work the network performed. This asymmetry is deliberate: it makes spamming expensive even when it fails.
Certain operations grant gas refunds to encourage cleaning up state, most notably clearing a storage slot back to zero. To prevent abuse (e.g. 'gas tokens' that hoarded refunds), EIP-3529 capped total refunds at one-fifth of the transaction's gas used and removed the SELFDESTRUCT refund. Gas metering is thus simultaneously a security mechanism, a DoS defense, and the basis of the fee market.
Metering counts gas_used; the fee market multiplies it by a per-gas price.
Gas (the amount of work) is separate from gas price (ETH paid per unit). A transaction's fee is gas used times the per-gas price, so metering fixes the work while the fee market sets the price.