> ## 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.

# BrandedFeeMarket

> [card] [Try it Live](https://playground.tevm.sh?example=primitives/fee-market.ts)
>
> Run FeeMarket examples in the interactive playground

# BrandedFeeMarket

Tree-shakable namespace functions for fee market calculations.

## Overview

`BrandedFeeMarket/` directory contains implementation functions organized as standalone modules. Each function operates on data passed as arguments (no instance methods).

All functions exported through `FeeMarket.js` namespace.

## Pattern

```typescript theme={null}
// Import individual function
import { BaseFee } from './BrandedFeeMarket/BaseFee.js';

// Or use via namespace
import * as FeeMarket from './FeeMarket.js';
FeeMarket.BaseFee(/* ... */);
```

Tree-shakable: bundlers only include functions you use.

## Functions

### EIP-1559 Base Fee

**BaseFee.js**

```typescript theme={null}
BaseFee(
  parentGasUsed: bigint,
  parentGasLimit: bigint,
  parentBaseFee: bigint
): BaseFee
```

Construct next block's base fee using EIP-1559 formula.

**Implementation:** Standard form per EIP-1559 spec.

**Formula:**

```javascript theme={null}
const gasTarget = gasLimit / ELASTICITY_MULTIPLIER;

if (gasUsed === 0n) return baseFee;
if (gasUsed === gasTarget) return baseFee;

if (gasUsed > gasTarget) {
  const delta = (baseFee * (gasUsed - gasTarget)) / gasTarget / 8n;
  return baseFee + max(delta, 1n);
} else {
  const delta = (baseFee * (gasTarget - gasUsed)) / gasTarget / 8n;
  return max(baseFee - max(delta, 1n), MIN_BASE_FEE);
}
```

See [eip1559.mdx#basefee](./eip1559.mdx#basefee)

### EIP-4844 Blob Fees

**BlobBaseFee.js**

```typescript theme={null}
BlobBaseFee(excessBlobGas: bigint): BlobBaseFee
```

Construct blob base fee using exponential formula.

**Implementation:** Uses `fakeExponential` helper for Taylor series approximation.

See [eip4844.mdx#blobbasefee](./eip4844.mdx#blobbasefee)

**fakeExponential.js**

```typescript theme={null}
fakeExponential(
  factor: bigint,
  numerator: bigint,
  denominator: bigint
): bigint
```

Internal exponential approximation via Taylor series.

**Formula:** `factor * e^(numerator / denominator)`

**Implementation:**

```javascript theme={null}
let output = 0n;
let numeratorAccum = factor * denominator;
let i = 1n;

while (numeratorAccum > 0n && i <= 256n) {
  output += numeratorAccum;
  numeratorAccum = (numeratorAccum * numerator) / (denominator * i);
  i += 1n;
}

return output / denominator;
```

**calculateExcessBlobGas.js**

```typescript theme={null}
calculateExcessBlobGas(
  parentExcessBlobGas: bigint,
  parentBlobGasUsed: bigint
): bigint
```

Calculate excess blob gas for next block.

**Implementation:**

```javascript theme={null}
const excess = parentExcessBlobGas + parentBlobGasUsed - TARGET_BLOB_GAS;
return excess > 0n ? excess : 0n;
```

See [eip4844.mdx#calculateexcessblobgas](./eip4844.mdx#calculateexcessblobgas)

### Transaction Fees

**calculateTxFee.js**

```typescript theme={null}
calculateTxFee(params: TxFeeParams): TxFee
```

Calculate EIP-1559 transaction fee breakdown.

**Implementation:**

```javascript theme={null}
const effectiveGasPrice =
  baseFee + maxPriorityFeePerGas < maxFeePerGas
    ? baseFee + maxPriorityFeePerGas
    : maxFeePerGas;

const priorityFee =
  effectiveGasPrice > baseFee
    ? effectiveGasPrice - baseFee
    : 0n;

return { effectiveGasPrice, priorityFee, baseFee };
```

See [calculations.mdx#calculatetxfee](./calculations.mdx#calculatetxfee)

**calculateBlobTxFee.js**

```typescript theme={null}
calculateBlobTxFee(params: BlobTxFeeParams): BlobTxFee
```

Calculate blob transaction fee (combines regular + blob fees).

**Implementation:**

```javascript theme={null}
const txFee = calculateTxFee(params);

const blobGasPrice =
  blobBaseFee < maxFeePerBlobGas ? blobBaseFee : maxFeePerBlobGas;

const totalBlobFee = blobGasPrice * BLOB_GAS_PER_BLOB * blobCount;

return { ...txFee, blobGasPrice, totalBlobFee };
```

See [calculations.mdx#calculateblobtxfee](./calculations.mdx#calculateblobtxfee)

**canIncludeTx.js**

```typescript theme={null}
canIncludeTx(params: TxFeeParams | BlobTxFeeParams): boolean
```

Check if transaction meets minimum fees.

**Implementation:**

```javascript theme={null}
if (params.maxFeePerGas < params.baseFee) return false;

if ('maxFeePerBlobGas' in params) {
  if (params.maxFeePerBlobGas < params.blobBaseFee) return false;
}

return true;
```

See [calculations.mdx#canincludetx](./calculations.mdx#canincludetx)

### State Operations

**nextState.js**

```typescript theme={null}
nextState(state: State): State
```

Calculate next block's complete state.

**Implementation:**

```javascript theme={null}
const nextBaseFee = BaseFee(
  state.gasUsed,
  state.gasLimit,
  state.baseFee
);

const nextExcessBlobGas = calculateExcessBlobGas(
  state.excessBlobGas,
  state.blobGasUsed
);

return {
  gasUsed: 0n,
  gasLimit: state.gasLimit,
  baseFee: nextBaseFee,
  excessBlobGas: nextExcessBlobGas,
  blobGasUsed: 0n
};
```

See [calculations.mdx#nextstate](./calculations.mdx#nextstate)

**projectBaseFees.js**

```typescript theme={null}
projectBaseFees(
  initialState: State,
  blocks: number,
  avgGasUsed: bigint,
  avgBlobGasUsed?: bigint
): bigint[]
```

Project future base fees over multiple blocks.

**Implementation:** Iteratively calls `nextState` with constant usage.

See [calculations.mdx#projectbasefees](./calculations.mdx#projectbasefees)

### Query Functions

**getBlobBaseFee.js**

```typescript theme={null}
getBlobBaseFee(state: State): bigint
```

Get current blob base fee from state.

**Implementation:**

```javascript theme={null}
return BlobBaseFee(state.excessBlobGas);
```

**getGasTarget.js**

```typescript theme={null}
getGasTarget(state: State): bigint
```

Get gas target (50% of limit).

**Implementation:**

```javascript theme={null}
return state.gasLimit / ELASTICITY_MULTIPLIER;
```

**isAboveGasTarget.js**

```typescript theme={null}
isAboveGasTarget(state: State): boolean
```

Check if gas usage exceeds target.

**Implementation:**

```javascript theme={null}
const target = state.gasLimit / ELASTICITY_MULTIPLIER;
return state.gasUsed > target;
```

**isAboveBlobGasTarget.js**

```typescript theme={null}
isAboveBlobGasTarget(state: State): boolean
```

Check if blob gas usage exceeds target.

**Implementation:**

```javascript theme={null}
return state.blobGasUsed > TARGET_BLOB_GAS_PER_BLOCK;
```

### Validation

**validateState.js**

```typescript theme={null}
validateState(state: State): string[]
```

Validate block state parameters.

**Checks:**

* `gasUsed >= 0`
* `gasLimit > 0`
* `gasUsed <= gasLimit`
* `baseFee >= MIN_BASE_FEE`
* `excessBlobGas >= 0`
* `blobGasUsed >= 0`
* `blobGasUsed <= MAX_BLOB_GAS_PER_BLOCK`

See [utilities.mdx#validatestate](./utilities.mdx#validatestate)

**validateTxFeeParams.js**

```typescript theme={null}
validateTxFeeParams(params: TxFeeParams | BlobTxFeeParams): string[]
```

Validate transaction fee parameters.

**Checks:**

* All values non-negative
* `maxPriorityFeePerGas <= maxFeePerGas`
* `1 <= blobCount <= 6` (if blob tx)

See [utilities.mdx#validatetxfeeparams](./utilities.mdx#validatetxfeeparams)

### Conversions

**weiToGwei.js**

```typescript theme={null}
weiToGwei(wei: bigint): string
```

Convert wei to gwei (9 decimal places).

**Implementation:**

```javascript theme={null}
const gwei = Number(wei) / 1_000_000_000;
return gwei.toFixed(9);
```

**gweiToWei.js**

```typescript theme={null}
gweiToWei(gwei: number): bigint
```

Convert gwei to wei (floors fractional).

**Implementation:**

```javascript theme={null}
return BigInt(Math.floor(gwei * 1_000_000_000));
```

See [utilities.mdx](./utilities.mdx)

## File Organization

```
BrandedFeeMarket/
├── BaseFee.js                   # EIP-1559 base fee constructor
├── BlobBaseFee.js               # EIP-4844 blob fee constructor
├── calculateExcessBlobGas.js    # Blob excess calculation
├── fakeExponential.js           # Exponential helper
├── calculateTxFee.js            # Transaction fee
├── calculateBlobTxFee.js        # Blob transaction fee
├── canIncludeTx.js              # Inclusion check
├── nextState.js                 # State transition
├── projectBaseFees.js           # Fee projection
├── getBlobBaseFee.js            # Query blob fee
├── getGasTarget.js              # Query gas target
├── isAboveGasTarget.js          # Check gas utilization
├── isAboveBlobGasTarget.js      # Check blob utilization
├── validateState.js             # State validation
├── validateTxFeeParams.js       # Param validation
├── weiToGwei.js                 # Wei to gwei conversion
├── gweiToWei.js                 # Gwei to wei conversion
├── index.ts                     # Type exports
└── FeeMarket.test.ts            # Comprehensive tests
```

## Testing

**FeeMarket.test.ts** - Comprehensive test suite covering:

* EIP-1559 base fee calculations (all scenarios)
* EIP-4844 blob fee calculations
* Transaction fee calculations
* State transitions
* Validation functions
* Edge cases and boundaries

Run tests:

```bash theme={null}
pnpm --filter @tevm/voltaire test:run src/primitives/FeeMarket/FeeMarket.test.ts
```

## Usage

### Tree-Shaking

Bundlers include only what you use:

```typescript theme={null}
// Only BaseFee and weiToGwei included in bundle
import { BaseFee, weiToGwei } from './FeeMarket.js';

const nextFee = BaseFee(30_000_000n, 30_000_000n, 1_000_000_000n);
console.log(weiToGwei(nextFee));
```

### Direct Imports

Import specific functions for minimal bundle size:

```typescript theme={null}
import { BaseFee } from './BrandedFeeMarket/BaseFee.js';
import { weiToGwei } from './BrandedFeeMarket/weiToGwei.js';

// Only these 2 functions in bundle
```

### Namespace Import

Import all via namespace (convenient but larger bundle):

```typescript theme={null}
import * as FeeMarket from './FeeMarket.js';

// All functions available, but bundler still tree-shakes unused
FeeMarket.BaseFee(/* ... */);
FeeMarket.weiToGwei(/* ... */);
```

## Implementation Notes

### Bigint Arithmetic

All calculations use bigint for precision:

```javascript theme={null}
// Integer division truncates (floors)
const target = gasLimit / 2n;

// Avoid overflow in multiplications
const delta = (baseFee * gasUsed) / gasLimit;
// Correct order: multiply first, divide last
```

### Constant-Time Operations

Fee calculations are not constant-time (no security requirement):

```javascript theme={null}
// Branch on gas usage is fine
if (gasUsed > gasTarget) {
  // increase logic
} else {
  // decrease logic
}
```

### Pure Functions

All functions pure (no side effects):

```javascript theme={null}
// Input immutable
export function nextState(state) {
  // Returns new object, doesn't modify state
  return { ...newValues };
}
```

### No WASM

Pure TypeScript optimal for these lightweight calculations. See [wasm.mdx](./wasm.mdx).

## References

* [eip1559.mdx](./eip1559.mdx)
* [eip4844.mdx](./eip4844.mdx)
* [calculations.mdx](./calculations.mdx)
* [utilities.mdx](./utilities.mdx)
* [types.mdx](./types.mdx)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.