# Transactions, blocks, and state roots

`Evm.call()` runs a single message call or contract creation. Real Ethereum
blocks also enforce transaction admission, EIP-1559 fee caps, EIP-2930 access
lists, EIP-4844 blob gas, EIP-7623 calldata floor pricing, EIP-7702
authorizations, protocol system calls, EIP-4895 validator withdrawals, and
post-state Merkle Patricia Trie roots.

Guillotine packages all of that into `evm.tx_runner` (`src/tx_runner.zig`),
`evm.state_root` (`src/storage/state_root.zig`), and `evm.trie` (`src/trie/`).

## Full transaction execution (`evm.tx_runner`)

`evm.tx_runner.executeTx` works over any `Evm(config)` specialization, including
custom `DatabaseType` backends and `InspectorType` tracers:

```zig
const std = @import("std");
const evm = @import("evm");
const primitives = @import("voltaire");
const Address = primitives.Address.Address;

const OsakaEvm = evm.Evm(.{});

var db = evm.Database.init(allocator);
defer db.deinit();

var vm = try OsakaEvm.init(allocator, &db, block_info, tx_context, 0, primitives.ZERO_ADDRESS);
defer vm.deinit();

// 1. Pre-block protocol system calls (from SYSTEM_ADDRESS = 0xffff...fffe)
try evm.tx_runner.runSystemCall(OsakaEvm, &vm, beacon_roots_addr, &parent_beacon_root);
try evm.tx_runner.runSystemCall(OsakaEvm, &vm, history_storage_addr, &parent_block_hash);

// 2. Execute each transaction in the block
var res = try evm.tx_runner.executeTx(OsakaEvm, allocator, &vm, .{
    .tx_type = 2, // 0=Legacy, 1=EIP-2930, 2=EIP-1559, 3=EIP-4844, 4=EIP-7702
    .from = sender,
    .to = recipient, // null for contract creation
    .nonce = 0,      // null skips nonce check
    .gas_limit = 200_000,
    .max_fee_per_gas = 20_000_000_000,
    .max_priority_fee_per_gas = 1_000_000_000,
    .value = 0,
    .input = calldata,
});
defer res.deinit(allocator);

// 3. Post-block protocol system calls (EIP-7002 withdrawals, EIP-7251 consolidations)
try evm.tx_runner.runSystemCall(OsakaEvm, &vm, withdrawal_requests_addr, &.{});
try evm.tx_runner.runSystemCall(OsakaEvm, &vm, consolidation_requests_addr, &.{});

// 4. EIP-4895 validator withdrawals (applied directly to the database)
try evm.tx_runner.applyWithdrawals(&db, &withdrawals);

// 5. Compute canonical Ethereum post-state MPT root
const post_state_root = try db.get_state_root();
```

### Supported transaction types

| `tx_type` | Envelope | Enforced rules |
| ---: | --- | --- |
| `0` | Legacy (EIP-155) | `gas_price >= base_fee` (London+), intrinsic gas, nonce, balance, EIP-7825 gas cap (Osaka), EIP-7623 calldata floor (Prague+) |
| `1` | EIP-2930 | Same as legacy + `access_list` pre-warming (2,400/address, 1,900/key); rejected before Berlin |
| `2` | EIP-1559 | `max_fee_per_gas >= base_fee`, `max_priority_fee_per_gas <= max_fee_per_gas`, effective price `min(max_fee, base_fee + tip)`, coinbase tip credit |
| `3` | EIP-4844 | Blob validation (`to != null`, non-empty `blob_hashes`, `max_fee_per_blob_gas >= blob_base_fee`, upfront blob fee debit at 131,072 gas/blob) |
| `4` | EIP-7702 | Set-code delegation (`to != null`, non-empty `authorizations`, 25,000 gas/tuple, authority recovery & delegation storage, 12,500 refund for existing authorities) |

Every call also enforces:

* **EIP-3607**: rejects transactions whose sender has deployed non-delegated code (`error.SenderHasCode`).
* **EIP-3860**: rejects initcode larger than 49,152 bytes on Shanghai+ (`error.InitcodeTooLarge`).
* **EIP-3529**: caps gas refunds at `gas_used / 5` on London+ (`gas_used / 2` pre-London).
* **EIP-161**: prunes empty touched accounts on Spurious Dragon+.
* **EIP-7825**: rejects transactions with `gas_limit > 16,777,216` on Osaka (`error.GasLimitExceedsCap`).

### `Transaction`, `TxResult`, and `ExecuteOptions`

`Transaction` (`src/tx_runner.zig`):

| Field | Type | Default / notes |
| --- | --- | --- |
| `tx_type` | `u8` | `0` (`0`..`4`; higher values return `error.InvalidTransactionType`) |
| `from` | `Address` | Required sender address |
| `to` | `?Address` | `null` for contract creation |
| `nonce` | `?u64` | `null` skips nonce comparison; otherwise checks `sender.nonce == expected` |
| `gas_limit` | `u64` | Required gas limit |
| `gas_price` | `u256` | `0` (used for legacy/type-1 transactions when `max_fee_per_gas == null`) |
| `max_fee_per_gas` | `?u256` | `null` (set for EIP-1559/4844/7702) |
| `max_priority_fee_per_gas` | `u256` | `0` |
| `value` | `u256` | `0` |
| `input` | `[]const u8` | `&.{}` (calldata or initcode) |
| `access_list` | `[]const AccessListEntry` | `&.{}` |
| `blob_hashes` | `[]const [32]u8` | `&.{}` |
| `max_fee_per_blob_gas` | `?u256` | `null` (when set, enforces cap ≥ `block_info.blob_base_fee` and sender affordability) |
| `authorizations` | `[]const Authorization` | `&.{}` |
| `disable_balance_check` | `bool` | `false` (set `true` for `eth_call` simulations) |

`TxResult` fields: `success`, `gas_used`, `gas_left`, `effective_gas_price`,
`refund`, `output`, `created_address`, `logs`, and `trace`. Always free it with
`result.deinit(allocator)`.

When running tight block-replay loops that only need receipts (and not owned
copies of return bytes or logs), use `executeTxWithOptions`:

```zig
var res = try evm.tx_runner.executeTxWithOptions(OsakaEvm, allocator, &vm, tx, .{
    .clone_output = false,
    .clone_logs = false,
});
defer res.deinit(allocator);
```

### Admission errors (`TxError`)

Admission failures reject the transaction **without mutating state** and return
a typed error:

```zig
pub const TxError = error{
    GasLimitExceedsCap,
    GasBelowIntrinsic,
    GasLimitExceedsBlock,
    MaxFeeBelowBaseFee,
    MaxFeePerBlobGasBelowBlobBaseFee,
    PriorityFeeExceedsMaxFee,
    InsufficientBalance,
    NonceMismatch,
    NonceOverflow,
    SenderHasCode,
    InvalidTransactionType,
    AccessListNotAllowed,
    InvalidBlobTransaction,
    InvalidAuthorizationTransaction,
    InitcodeTooLarge,
    HostFailure,
    OutOfMemory,
};
```

Helper functions exported alongside `executeTx`:

* `computeEffectiveGasPrice(tx, base_fee) TxError!u256`
* `computeGasSchedule(eips, tx) struct { intrinsic: u64, floor: u64 }`
* `runSystemCall(EvmType, vm, target, input) TxError!void` (executes from `SYSTEM_ADDRESS = 0xfffffffffffffffffffffffffffffffffffffffe` with 30M gas and zero gas price)
* `applyWithdrawals(database, withdrawals) TxError!void` (credits each non-zero `Withdrawal{ .address, .amount_wei }`)

## Moving across blocks without losing warm caches

To replay multiple blocks on one `Evm` instance while keeping `DispatchCache`,
`FrameStackPool`, and `FrameMemoryPool` warm:

```zig
vm.setBlockInfo(next_block_info);
// executeTx calls vm.resetForTx() automatically before each transaction.
```

If you call `vm.call()` directly instead of `tx_runner.executeTx`, call
`vm.resetForTx()` between transactions and `vm.resetTouched()` periodically if
`track_state_dump` is enabled.

## State root calculation (`evm.state_root`)

`Database.get_state_root()` delegates to `evm.state_root.stateRoot(allocator, db)`
(`src/storage/state_root.zig`), which computes the canonical Yellow Paper
Appendix D Merkle Patricia Trie root:

1. Groups every non-zero storage slot per account (`db.storage`), RLP-encodes
   each slot value, keys by `keccak256(slot_be32)`, and computes each account's
   storage trie root.
2. RLP-encodes each account as `[nonce, balance, storageRoot, codeHash]` keyed
   by `keccak256(address)`.
3. For EOAs with an EIP-7702 `delegated_address`, hashes the 23-byte delegation
   designator `0xef0100 || target` as `codeHash`.
4. Builds the trie bottom-up from sorted keys inside a single temporary arena
   and frees the arena before returning — zero persistent node-store overhead.

You can also hash arbitrary 32-byte-keyed tries directly:

```zig
const state_root = @import("evm").state_root;

var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();

var entries = [_]state_root.TrieEntry{
    .{ .key = state_root.keccak(&key_bytes), .value = rlp_encoded_value },
};
const root: [32]u8 = try state_root.trieRoot(arena.allocator(), &entries);
```

Exported constants: `state_root.empty_trie_root` (`keccak256(rlp(""))`) and
`state_root.empty_code_hash` (`keccak256("")`). The EEST state-test runner
checks all 66,652 post-state roots through this module.

## Standalone Merkle Patricia Trie and proofs (`evm.trie`)

When you need an incremental in-memory trie or EIP-1186-style Merkle proof
generation and verification, use `evm.trie` (`src/trie/`):

* **`MerkleTrie`** (`src/trie/merkle_trie.zig`): iterative `[32]u8`-keyed MPT
  (no recursion) supporting insert, lookup, delete, and root computation.
* **`ProofRetainer` / `ProofNodes`** (`src/trie/proof.zig`): collect RLP-encoded
  proof nodes along a key path and verify inclusion or non-inclusion proofs
  against a root hash.
* **`HashBuilder`** (`src/trie/hash_builder_complete.zig`): streaming hash
  builder for sorted keys.

## Next

* [Parallel block execution (Block-STM)](/guides/parallel-execution): run a
  whole block across multiple CPU cores with bit-exact post-state parity.
* [State and journaling](/guides/state): accounts, code, storage, snapshots, and
  ephemeral views.
* [Layer 2 chains](/guides/layer2): OP Stack, Base, and Arbitrum transaction
  envelopes and fee settlement.
