> ## Documentation Index
> Fetch the complete documentation index at: https://voltaire.tevm.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Hardfork

> Ethereum protocol upgrade identification and comparison utilities

<Card title="Try it Live" icon="play" href="https://playground.tevm.sh?example=primitives/hardfork.ts">
  Run Hardfork examples in the interactive playground
</Card>

<Tip>
  **New to hardforks?** Read the [Fundamentals](/primitives/hardfork/fundamentals) guide for an introduction to Ethereum protocol upgrades, activation mechanisms, and feature timeline.
</Tip>

Ethereum hardforks are protocol upgrades that change EVM behavior, gas costs, or add features. This module provides type-safe hardfork identification, version comparison, and feature detection.

```typescript theme={null}
import { Hardfork } from 'tevm';

const fork = Hardfork("cancun");
if (Hardfork.hasEIP4844(fork)) {
  // Blob transactions available
}
```

## Hardfork Type

Hardforks are represented as branded strings:

```typescript theme={null}
type BrandedHardfork = string & { __tag: "Hardfork" };
```

## Core Operations

**Version Comparison:**

```typescript theme={null}
Hardfork.isAtLeast(current, target)  // current >= target
Hardfork.isBefore(current, target)    // current < target
Hardfork.compare(a, b)                // -1, 0, 1
```

**Feature Detection:**

```typescript theme={null}
Hardfork.hasEIP1559(fork)   // EIP-1559 base fee (London+)
Hardfork.hasEIP3855(fork)   // PUSH0 opcode (Shanghai+)
Hardfork.hasEIP4844(fork)   // Blob transactions (Cancun+)
Hardfork.isPostMerge(fork)  // Proof of Stake (Merge+)
```

**String Parsing:**

```typescript theme={null}
Hardfork("cancun")        // Case-insensitive
Hardfork("paris")         // Alias → MERGE
Hardfork.toString(fork)              // Normalized name
```

## API Methods

### Constructors

* [`fromString(value)`](./from-string) - Parse hardfork name (case-insensitive, handles aliases)
* [`toString(fork)`](./to-string) - Convert to normalized string name

### Comparison Methods

* [`compare(a, b)`](./compare) - Three-way comparison (-1, 0, 1)
* [`isAtLeast(current, target)`](./is-at-least) - Check if current >= target
* [`isBefore(current, target)`](./is-before) - Check if current \< target
* [`isAfter(current, target)`](./is-after) - Check if current > target
* [`equals(a, b)`](./equals) - Equality check
* [`gte(a, b)`](./gte) - Greater than or equal (alias)
* [`lte(a, b)`](./lte) - Less than or equal (alias)
* [`gt(a, b)`](./gt) - Greater than (alias)
* [`lt(a, b)`](./lt) - Less than (alias)

### Feature Detection

* [`hasEIP1559(fork)`](./has-eip1559) - EIP-1559 base fee mechanism (London+)
* [`hasEIP3855(fork)`](./has-eip3855) - PUSH0 opcode (Shanghai+)
* [`hasEIP4844(fork)`](./has-eip4844) - Blob transactions (Cancun+)
* [`hasEIP1153(fork)`](./has-eip1153) - Transient storage TLOAD/TSTORE (Cancun+)
* [`isPostMerge(fork)`](./is-post-merge) - Proof of Stake consensus (Merge+)

### Collection Operations

* [`allNames()`](./all-names) - Get all hardfork names (chronological order)
* [`allIds()`](./all-ids) - Get all hardfork IDs (chronological order)
* [`range(start, end)`](./range) - Get hardforks between two versions (inclusive)
* `min(forks)` - Find earliest hardfork in array
* `max(forks)` - Find latest hardfork in array

### Constants

All hardfork constants available:

```typescript theme={null}
FRONTIER, HOMESTEAD, DAO, TANGERINE_WHISTLE, SPURIOUS_DRAGON
BYZANTIUM, CONSTANTINOPLE, PETERSBURG, ISTANBUL, MUIR_GLACIER
BERLIN, LONDON, ARROW_GLACIER, GRAY_GLACIER, MERGE
SHANGHAI, CANCUN, PRAGUE, OSAKA

Hardfork.DEFAULT  // PRAGUE
```

## Quick Examples

### Version Gating

```typescript theme={null}
import { Hardfork, CANCUN, LONDON } from 'tevm';

const fork = Hardfork("cancun");

// Check minimum version
if (Hardfork.isAtLeast(fork, LONDON)) {
  // EIP-1559 available
}

// Feature-based check
if (Hardfork.hasEIP4844(fork)) {
  // Use blob transactions
}
```

### Network Configuration

```typescript theme={null}
import { InvalidFormatError } from 'tevm/errors'

function getNetworkCapabilities(hardfork: string) {
  const fork = Hardfork(hardfork);
  if (!fork) {
    throw new InvalidFormatError("Invalid hardfork", {
      value: hardfork,
      expected: "Valid hardfork name (e.g., 'cancun', 'london')",
      code: "INVALID_HARDFORK"
    })
  }

  return {
    consensus: Hardfork.isPostMerge(fork) ? "PoS" : "PoW",
    eip1559: Hardfork.hasEIP1559(fork),
    push0: Hardfork.hasEIP3855(fork),
    blobs: Hardfork.hasEIP4844(fork),
    transientStorage: Hardfork.hasEIP1153(fork),
  };
}
```

### Upgrade Path

```typescript theme={null}
import { BERLIN, CANCUN, range } from 'tevm';

// Get all hardforks between two versions
const upgradePath = range(BERLIN, CANCUN);
// [BERLIN, LONDON, ARROW_GLACIER, GRAY_GLACIER, MERGE, SHANGHAI, CANCUN]

console.log(`${upgradePath.length} hardforks to upgrade through`);
```

## Additional Documentation

* **[fundamentals.mdx](./fundamentals.mdx)** - Introduction to Ethereum protocol upgrades
* **[hardforks.mdx](./hardforks.mdx)** - Complete hardfork timeline with all features
* **[usage-patterns.mdx](./usage-patterns.mdx)** - Common patterns and examples
* **[branded-hardfork.mdx](./branded-hardfork.mdx)** - Branded type pattern
* **[wasm.mdx](./wasm.mdx)** - WASM implementation status

## Tree-Shaking

Import only what you need for optimal bundle size:

```typescript theme={null}
// Import specific features
import { hasEIP4844, isAtLeast, fromString } from 'tevm/Hardfork'

// Or import constants only
import { CANCUN, LONDON, BERLIN } from 'tevm/Hardfork'

// Selective imports reduce bundle size
const fork = fromString(userInput)
if (hasEIP4844(fork)) {
  // Blob logic
}
```

Each comparison method, feature detector, and utility is independently exported. Import only the hardfork detection logic your application needs.

## Performance

All operations are O(1):

* **Comparisons**: Simple array index lookups (\~10-20ns)
* **Feature detection**: Single comparison + branch (\~15-30ns)
* **String parsing**: Hash table lookup (\~50-100ns)
* **String conversion**: Array index (\~20-40ns)

No WASM implementation - pure TypeScript is optimal for these operations. WASM overhead (1-2μs) would make operations 10-100x slower.

## Implementation

* **Type**: Branded string (`string & { __tag: "Hardfork" }`)
* **Storage**: Chronologically ordered array
* **Comparison**: Array index comparison
* **Parsing**: Hash table with lowercase keys
* **Aliases**: "paris" → MERGE, "constantinoplefix" → PETERSBURG

## Best Practices

1. **Use feature detection over version checks**
   ```typescript theme={null}
   // Good - explicit about requirements
   if (Hardfork.hasEIP4844(fork)) { /* ... */ }

   // Less clear - couples to version
   if (Hardfork.isAtLeast(fork, CANCUN)) { /* ... */ }
   ```

2. **Validate user input**
   ```typescript theme={null}
   import { InvalidFormatError } from 'tevm/errors'

   const fork = Hardfork(userInput);
   if (!fork) {
     throw new InvalidFormatError("Invalid hardfork", {
       value: userInput,
       expected: "Valid hardfork name",
       code: "INVALID_HARDFORK"
     })
   }
   ```

3. **Normalize for storage**
   ```typescript theme={null}
   const normalized = Hardfork.toString(fork);
   ```

4. **Use convenience forms for readability**
   ```typescript theme={null}
   if (fork.supportsBlobs()) { /* ... */ }
   ```

## Related Primitives

* [Hardfork (Effect)](https://voltaire-effect.tevm.sh/primitives/hardfork) - Effect.ts integration with Schema validation
* **Network** - Chain ID and network configuration
* **Transaction** - Transaction type selection based on hardfork
* **Block** - Block structure changes per hardfork
