# Layer 2 chains (OP Stack, Base & Arbitrum)

Guillotine ships first-class Layer 2 execution modules under `src/layer2/`,
exposed both as `@import("evm").layer2` and as the standalone public package
module `guillotine.module("layer2")` (`src/layer2_package.zig`).

L2 support follows Guillotine's comptime zero-cost rule: `Layer2Config` defaults
to `.none`, so L1-only builds compile out all L2 code completely.

## Importing the `layer2` module

In a downstream Zig project's `build.zig`:

```zig
const guillotine = b.dependency("guillotine", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("evm", guillotine.module("evm"));
exe.root_module.addImport("layer2", guillotine.module("layer2"));
exe.root_module.addImport("voltaire", guillotine.module("voltaire"));
```

`evm.layer2` exposes the pure rules and transaction executor (`optimism`,
`base`, `arbitrum`, `layer2_config`, `executor`, `OpSpecId`). The standalone
`layer2` module additionally re-exports `evm_host` (`src/layer2/evm_host.zig`),
which wires the OP Stack executor onto real fork-specialized Guillotine `Evm`
instances.

## OP Stack and Base

Guillotine implements OP Stack and Base execution rules from **Bedrock through
Jovian** (pre-Azul), matching `op-revm` and `base/base` fee and state-transition
formulas.

### Supported OP Stack hardforks (`OpSpecId`)

| OP Stack fork | Underlying Ethereum fork | Key L2 changes |
| --- | --- | --- |
| `BEDROCK` | `MERGE` | Deposit tx (`0x7e`), L1 calldata data fee, L1/base/priority fee vaults |
| `REGOLITH` | `MERGE` | Deposit gas non-refundability, system tx rules |
| `CANYON` | `SHANGHAI` | `PUSH0`, EIP-3860 initcode cap, create2deployer |
| `ECOTONE` | `CANCUN` | EIP-4844 blob base fee formula for L1 data costs (`L1BlockInfo`) |
| `FJORD` | `CANCUN` | FastLZ compression-based L1 data fee (`optimism/fast_lz.zig`), `P256VERIFY` (`0x100`) precompile |
| `GRANITE` | `CANCUN` | BN254 pairing input-size cap precompile override |
| `HOLOCENE` | `CANCUN` | Dynamic EIP-1559 elasticity & denominator (`optimism/eip1559.zig`) |
| `ISTHMUS` | `PRAGUE` | Operator fee, EIP-7702 authorizations, EIP-7623 calldata floor, BLS12-381 overrides |
| `JOVIAN` | `PRAGUE` | DA footprint gas metering (`optimism/da_footprint.zig`), updated operator fee scalar |

Unmodeled future Base upgrades (`Azul`, `Beryl`, `Cobalt`, `Denim`) return
`error.UnmodeledBaseUpgrade` explicitly rather than silently falling back to
Jovian.

### Base chain schedules and system contracts

`layer2.base` (`src/layer2/base/`) provides built-in activation schedules and
system contract addresses for:

* **Base Mainnet** (`chain_id = 8453`): `BaseConfig.MAINNET`, `MAINNET_SCHEDULE`
* **Base Sepolia** (`chain_id = 84532`): `BaseConfig.SEPOLIA`, `SEPOLIA_SCHEDULE`

```zig
const layer2 = @import("layer2");
const base = layer2.base;

// Resolve the active OP Stack spec from a Base Mainnet block timestamp
const spec = try base.MAINNET_SCHEDULE.specAt(timestamp);

// Access Base fee vaults and L1Block predeploy addresses
const l1_block_addr = base.SystemContracts.L1_BLOCK;
const base_fee_vault = base.SystemContracts.BASE_FEE_VAULT;
const l1_fee_vault = base.SystemContracts.L1_FEE_VAULT;
```

### Running OP Stack / Base transactions on the real EVM (`layer2.evm_host`)

`src/layer2/evm_host.zig` implements the host interface expected by
`layer2.executor.execute` on top of real fork-configured Guillotine `Evm`
instances (one comptime `Evm` per `OpSpecId` with `optimism/precompiles.zig`
installed via `EvmConfig.precompile_overrides`):

* **Deposit transactions (`0x7e`)**: mints `mint` value, runs on the EVM without
  L1/L2 gas fees, handles failed deposits per Bedrock/Regolith rules.
* **User transactions**: deducts L1 data fee + operator fee + upfront L2 gas,
  enforces EIP-2930 access lists, EIP-7702 authorizations on Isthmus/Jovian,
  EIP-7623 calldata floor, and settles L1, base, operator, and coinbase fee
  vaults.
* **Database checkpoints**: uses `Database` snapshots for O(1) rollback on
  failed transactions.

```zig
const evm = @import("evm");
const layer2 = @import("layer2");

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

// Configure L1BlockInfo (from L1Block predeploy storage or block header)
// and run through layer2.executor.execute(&host, ...) via layer2.evm_host.
```

## Arbitrum (Experimental)

`src/layer2/arbitrum/` provides an **experimental** Arbitrum execution module
and EVM host covering:

* **Configured networks (`ArbitrumChain`):** Arbitrum One (`42161`), Arbitrum
  Sepolia (`421614`), and Arbitrum Nova (`42170`).
* **ArbOS versions (`ArbOsVersion`):** ArbOS 11, 20 (Atlas), 31/32 (Bianca,
  enabling `P256VERIFY`), and 40 (Callisto).
* **L1 → L2 address aliasing:** `applyL1ToL2Alias` and `undoL1ToL2Alias`.
* **ArbOS state (`ArbOsState`):** journaled snapshot/rollback state for pricing,
  block numbers/hashes, address table, retryable tickets, scheduled redeems,
  L2→L1 sends, and statistics.
* **ArbOS precompiles (`0x64`–`0x6f`):** `ArbSys` (`0x64`), `ArbInfo` (`0x65`),
  `ArbAddressTable` (`0x66`), `ArbosTest` (`0x69`), `ArbGasInfo` (`0x6c`),
  `ArbAggregator` (`0x6d`), `ArbRetryableTx` (`0x6e`), and `ArbStatistics`
  (`0x6f`), bridged via `RuntimePrecompileOverride`.
* **Six Arbitrum transaction types (`ArbTxType`):** `0x64` (unsigned), `0x65`
  (contract), `0x66` (deposit), `0x68` (retry), `0x69` (submit retryable), and
  `0x6a` (internal).
* **2D gas model (`gas_model.zig`):** poster units, poster gas, fee settlement,
  and exponential backlog base-fee updates.

:::warning[Experimental limitations — read before relying on Arbitrum]
The Arbitrum module is experimental and Nitro fixture validation is still
outstanding. Known limits (tracked in `src/layer2/README.md`):

* **Nested state-changing precompile calls fail:** `RuntimePrecompileOverride`
  receives `(context, allocator, input, gas_limit)` without the active frame, so
  state-changing precompile methods (`sendTxToL1`, `withdrawEth`, `register`,
  `redeem`, `keepalive`, `cancel`) work only when called directly by a
  transaction, not from inside a contract. View methods work at every depth.
* **L1 poster fees are estimates:** Guillotine applies an LZ77 size heuristic to
  the transaction envelope rather than Nitro's Brotli compression and message
  padding; estimation error has not been measured against Nitro.
* **Precompile gas costs** use this module's own constants rather than Nitro's
  storage-access gas burn.
* **Not modeled:** batch-posting reports and L1 pricer updates, the infra fee
  account, retryable reaping on timeout, Stylus, and internal transactions other
  than `startBlock`.
:::

## Testing Layer 2

```bash
zig build test-layer2
```

This runs both the pure L2 unit suite (`src/layer2/test_root.zig`: OP Stack,
Base, and Arbitrum modules) and the real-EVM host integration tests
(`src/layer2/evm_host.zig` and `src/layer2/arbitrum/host_test.zig`).

See [`src/layer2/README.md`](https://github.com/evmts/guillotine/blob/main/src/layer2/README.md)
for the complete file map and invariants.
