---
id: TIP-1171
title: Unbounded Deposit Queues for Zones
description: Removes the Zone deposit cap by processing the deposit queue in authenticated, weight-bounded buckets, priced by a congestion premium on deposits.
authors: @0xrusowsky
status: Draft
related: TIP-1096, TIP-1012, TIP-1060, TIP-1150
protocolVersion: T15
---

# TIP-1171: Unbounded Deposit Queues for Zones

## Abstract

This TIP replaces the 230-entry cap on a Zone's unprocessed deposit queue with an unbounded queue split into fixed-size buckets. The Portal stores a hash checkpoint after each bucket. Each full Zone block verifies at most one bucket's worth of entries against a checkpoint or the queue head, so no block hashes the whole backlog. It executes as many entries as fit a per-block weight budget and only hashes the rest, leaving them for later blocks. The protocol, not the sequencer, selects each block's range.

Queue depth no longer limits admission. Since anyone can then delay later entries by lengthening the queue, a congestion premium on deposits applies backpressure. Its price rises with Zone work not yet settled on L1: zero in the first tier, then linearly to a cap equal to the forced-exit fee. It cannot rise within an L1 block, is capped by the user, and is paid to the Portal admin. Waiting time stays unbounded.

## Motivation

[TIP-1096](./tip-1096.md) requires every full Zone block to process every pending entry. The Portal therefore caps unprocessed entries at 230, the most one full block can execute within its gas budget. Deposits and withdrawal bounce-backs share this cap. That causes two problems:

- **Outages reject deposits.** While the sequencer is down, the queue fills and further deposits revert.
- **Exits compete for queue space.** A failed withdrawal bounces back into the queue. `processWithdrawals` therefore runs a batch only if every withdrawal in it could bounce back, so a full queue stops withdrawal delivery. TIP-1012 forced exits would share the cap too. Its draft counts each forced exit as `FORCED_EXIT_ADMISSION_WEIGHT` entries against the 210 left after the reserve. At most `floor(210 / FORCED_EXIT_ADMISSION_WEIGHT)` could then wait at once, so anyone could fill those places and make honest ones revert. This TIP therefore activates before TIP-1012.

Processing the queue in buckets removes the need for a cap. Filling the queue then delays later entries, and the congestion premium prices that delay. A Zone that processes only part of the queue must still prove that part belongs to it. Without intermediate commitments, that proof hashes the whole remaining backlog in every block. Total work then grows with the square of the backlog. A checkpoint at the end of each fixed-size bucket bounds the hashing to one bucket's worth of entries per block.

## Assumptions

| Assumption | Consequence if violated |
| --- | --- |
| A live sequencer produces full blocks and settles batches. | The backlog grows and entries wait indefinitely. Admission continues, priced by the premium. |
| The costliest mix of one block's weight budget, hashing a full bucket, and 8 token enablements fits the Zone block budget. | The block's opening transaction aborts and the Zone stalls until the sequencer supplies valid input. No entry is skipped. |
| Under normal load, settlement leaves less than `CONGESTION_TIER_WEIGHT` weight units unsettled. | Users pay the premium without a real backlog. |
| The sequencer keeps unprocessed entry payloads and historical decryption keys. | The backlog cannot be processed. |
| TIP-1012 activates in a later fork and adds forced exits as [Forced exits](#forced-exits) describes. | Forced exits regain an admission cap, or escape the per-block weight budget and the premium tier. |
| The Portal admin does not build backlog with its own deposits. | The admin pays its own premiums to itself, so it can delay later entries, including forced exits, for the cost of L1 gas. |
| The Portal runtime replaced at activation capped unprocessed entries at no more than one bucket. | The bootstrap guarantee in [Activation on existing Portals](#activation-on-existing-portals) does not hold. |

---

# Specification

## Overview

The **Portal** is the Zone's L1 contract that escrows deposits and queues them. This TIP changes the current Portal. TIP-1012 adds **forced exits** in a later fork: L1 requests that withdraw a Zone account's balance through the deposit queue. This TIP leaves their weight to TIP-1012 ([Forced exits](#forced-exits)). The **Inbox** is the Zone system contract that executes queued entries. A **full block** is a Zone block that imports one Tempo header and processes queued work; [TIP-1096](./tip-1096.md) header-only blocks import headers only.

An **entry** is anything appended to a Zone's deposit queue: a deposit, a forced exit, or an entry the Portal creates while delivering withdrawals. Entries are numbered from 1. Each entry has a **weight** set by its `DepositType`. Every type in this TIP weighs 1, and the TIP that adds a type sets its weight. `MAX_ENTRY_WEIGHT` is the largest weight of any type, 1 under this TIP.

Three positions in the queue drive the design:

| Symbol | Meaning | Stored as |
| --- | --- | --- |
| `N` | Entries appended on L1 | Portal `depositCount` |
| `P` | Entries executed by the Zone | Inbox `processedDepositNumber` |
| `S` | Entries confirmed on L1 by settlement | Portal `lastProcessedDepositNumber` |

`S` never exceeds `P`, because settlement only confirms what the Zone executed.

The design has two limits:

- `K = 230` entries: the queue splits into **buckets** of `K` entries. The last entry of each bucket stores a **checkpoint**, the queue hash at that entry. A full block verifies at most `K` entries.
- `W = 230` weight units: a full block executes at most `W` weight. `W` is a Zone-side limit; the Portal never reads it.

With `K = W`, a queue of weight-1 entries fills exactly one full block per checkpoint, and no entry is hashed twice. [Adjusting limits and weights](#adjusting-limits-and-weights) describes how a later fork changes them.

An entry's life has four steps:

1. **Append.** Anyone appends a deposit or forced exit on L1 and pays the existing fees. Deposits also pay a congestion premium, which rises with unsettled weight up to `CONGESTION_MAX_FEE` and goes to the Portal admin. Forced exits and entries created while delivering withdrawals pay no premium.
2. **Process.** Each full Zone block selects the next **range** of at most `K` entries. It executes the longest **prefix** within `W` and only hashes the rest, checking the result against a checkpoint or the queue head.
3. **Settle.** `submitBatch` advances `S` to the prefix the batch proves.
4. **Prune.** The Portal deletes checkpoints that neither processing nor settlement will read again.

The protocol, not the sequencer, selects each block's range and prefix. The sequencer only supplies entry payloads and decryption data. The Inbox rejects a block that executes a different prefix, and the batch proof re-executes the Inbox.

**Example: recovery after an outage.** The sequencer stops while 1,000 deposits arrive, followed by a bounce-back at position 1,001. When the sequencer returns, each full block executes one bucket of `K` entries. The bounce-back runs in the fifth block. Throughout, users can still deposit at a rising premium.

## Mechanics

### Append

Anyone can append through `deposit` or `depositEncrypted`, and through `requestForcedExit` once TIP-1012 activates. The Portal also appends **withdrawal-generated entries** while delivering withdrawals. These are withdrawal bounce-backs and at most one deposit returned by each callback withdrawal.

The Portal removes the `MAX_UNPROCESSED_DEPOSITS` cap, the 20-entry withdrawal reserve, the queue-capacity check in `processWithdrawals`, and `DepositBlockCapacityExceeded`. It adds no other limit on queue depth, outage duration, or appends per L1 block. L1 counts weight only to price the premium, never to limit admission.

Checkpoints are counted from `N0`, the value of `depositCount` when the new runtime first appended ([Activation on existing Portals](#activation-on-existing-portals)). Checkpoint `j` holds the queue hash after entry `N0 + j*K`.

Every successful append, including withdrawal bounce-backs and callback-returned deposits, MUST atomically:

1. Bootstrap checkpoints if `depositBuckets` is empty ([Activation on existing Portals](#activation-on-existing-portals)), spending [storage credits](#storage-credits) directly.
2. Snapshot the block's tier if this block has none yet ([Price per block](#congestion-premium)), then apply the existing validity checks and fees. A deposit, unless it is a callback-returned deposit, also pays the [congestion premium](#congestion-premium) at the block's stored tier.
3. Extend the queue hash through the canonical `DepositQueueLib` encoding and increment `depositCount` with checked overflow.
4. Add the entry's weight to `depositWeight`.
5. Run [Prune](#prune).
6. If `depositCount - N0` is a multiple of `K`, append the queue hash and `depositWeight` to `depositBuckets` as the next checkpoint, spending [storage credits](#storage-credits) directly.
7. Emit the existing lifecycle event with the deposit number.

Checkpoints never change until pruned. The current queue hash covers the open tail, so a partial bucket needs no sealing transaction, padding, or timeout.

`_withdrawalReentrancyStatus` keeps its transition from `CALLBACK_DEPOSIT_AVAILABLE` to `CALLBACK_DEPOSIT_CONSUMED`. That transition now exempts the callback's deposit from the premium instead of granting reserved capacity.

#### Activation on existing Portals

A hardfork installs the new Portal runtime without touching Portal storage, so existing Portals receive no initializer call. L1 also cannot recompute old queue hashes. Checkpoints counted from entry 1 could therefore require a hash that was never stored. For example, with `P < K < N` at activation, the next block would require the hash at entry `K`.

Checkpoints therefore start at the first append under the new runtime, the **bootstrap**. Until then, `depositBuckets` is empty and no checkpoint exists. That append sets `depositBucketBase` (`N0`) to the current `depositCount`. It stores the current queue hash as checkpoint 0, with cumulative weight zero, before applying its own entry. New Portals follow the same path with `N0 = 0` and a zero hash, so the native factory needs no change. This reuses the lazy-bootstrap pattern of `tokenEnablementCursorInitialized`.

The replaced runtime guaranteed `N - S <= K`. Because `S <= P`, the Zone can reach the queue head within `K` entries before bootstrap, and `N0 - P <= K` holds at bootstrap. The first append after activation pays the bootstrap writes.

#### Congestion premium

The premium is backpressure: its price rises with the Zone work still unconfirmed on L1.

**Tier.** The tier `b` counts how many multiples of `CONGESTION_TIER_WEIGHT` weight units are unsettled. The premium rises linearly with `b` and stops at `CONGESTION_MAX_FEE`:

```text
b = floor((depositWeight - settledDepositWeight) / CONGESTION_TIER_WEIGHT)
congestionFee(b) = CONGESTION_MAX_FEE * min(b, CONGESTION_MAX_TIER) / CONGESTION_MAX_TIER
```

The multiplication happens before the division. `depositWeight` is the cumulative weight appended since bootstrap. `settledDepositWeight` is a lower bound on the weight settled since bootstrap, set at [Settle](#settle). The bound is exact when `S` is at a checkpoint or at the queue head. Otherwise it overstates unsettled weight by at most `MAX_ENTRY_WEIGHT - 1` per entry settled since the last checkpoint, and only while entries remain unsettled. While every entry weighs 1, it is always exact. `depositWeight` does not count entries appended before bootstrap, so until they settle the tier can be one step low. After that, the premium never undercharges, and a fully settled queue pays none. Forced exits pay no premium but count their full weight, so a backlog of forced exits raises the tier as fast as the Zone work it creates.

The first tier is free: below `CONGESTION_TIER_WEIGHT` unsettled weight units, the depth the replaced runtime admitted, `b = 0`. Each further tier adds `1/32` of the cap, which applies from tier 32 on. At 100 deposits per minute, stalled settlement reaches the cap in about 75 minutes.

`CONGESTION_MAX_FEE` is 100,000 token units, the `FORCED_EXIT_FEE` TIP-1012 sets, so a deposit's premium never exceeds a forced exit's fee. `CONGESTION_TIER_WEIGHT` does not follow `W`, so a fork that changes throughput does not move the price.

L1 sees Zone progress only through settlement, so `b` includes settlement delay.

**Price per block.** Each L1 block is priced from the state at its start. The first operation in a block that changes `depositWeight` or `settledDepositWeight` (any append, including exempt ones, or a settlement) first computes `b` from the state before it and stores it in `depositPriceTier`, with `depositPriceBlock = block.number`. A settlement that leaves `b` below the stored tier lowers the stored tier to `b`. Every deposit in that block pays the stored tier. Appends only raise `b` and only settlement lowers it, so the stored tier never exceeds the tier from the current state. A quote from the latest state is therefore exact for inclusion in the next block. Ordering other appends or withdrawal processing ahead of a pending deposit cannot raise its tier, and a settlement ahead of it can only lower it. Between blocks, the price rises when entries are appended and falls when settlement advances. `calculateDepositFee()` returns the price from the current state. That price is exact for the next block and never below the charge for a deposit later in the current block.

**Charges.**

| Entry | Charge |
| --- | --- |
| Deposit | Operational fee (`FIXED_DEPOSIT_GAS * zoneGasRate`) plus `congestionFee(b)` |
| Forced exit | `FORCED_EXIT_FEE`, set by [TIP-1012](#forced-exits) |
| Withdrawal bounce-back or callback-returned deposit | No premium |

Forced exits are exempt so the exit path costs the same at every tier. Withdrawal-generated entries are exempt because each one follows a Zone withdrawal that already paid Zone fees. A premium above a callback amount would also make the callback's deposit revert. The withdrawal would then bounce back without paying any premium.

**User cap.** New `deposit` and `depositEncrypted` overloads take `maxFee`, the most the caller accepts to pay in total. If the charge exceeds it, the call reverts with `FeeTooHigh(fee, maxFee)` and changes nothing. The caller retries with a higher `maxFee` or waits for the price to fall. The existing signatures act as if `maxFee` were the operational fee. They work unchanged under normal load and revert with `FeeTooHigh` during congestion. `DepositTooSmall` covers the premium as well as the existing fee and bounce-back reserve. `DepositMade.fee` reports the total fee.

**Recipient.** The Portal adds the premium to the operational fee and transfers both to `admin` in the existing fee transfer. As today, a failed transfer reverts the deposit. [Threat Model](#threat-model) covers what congestion revenue lets the admin do.

### Process

A full Zone block opens with `advanceTempo`. That call imports one Tempo header. Let `R` be that header's state root. The Inbox reads `depositCount` (`N_R`), `currentDepositQueueHash`, `depositBucketBase`, and the `depositBuckets` length from the Portal storage at `R`, so each read is proven against `R`. A live getter cannot replace that proof.

The Inbox requires `P <= N_R`. If `P == N_R`, the block executes no entries. Otherwise the Inbox selects the target `T`, the last entry of the range. `C[j]` denotes the hash stored in `depositBuckets[j]`.

```text
if N_R - P <= K:
    T = N_R
    expectedHash = currentDepositQueueHash at R
else:
    require depositBuckets.length at R > 0
    j = 0                          if P < N0
      = floor((P - N0) / K) + 1    otherwise
    T = N0 + j * K
    expectedHash = C[j] at R
```

The Inbox then selects the endpoint `X`, the largest `x` in `P+1 ... T` whose entries `P+1 ... x` weigh at most `W` in total.

`advanceTempo` receives exactly entries `P+1 ... T`. It MUST execute `P+1 ... X` in queue order and only hash `X+1 ... T`, and the hash chain through `T` must equal `expectedHash`. Hashed-only entries are strictly decoded but neither decrypted nor executed. They consume no `DecryptionData`, and a later block supplies them again.

The Inbox rejects the block for a missing checkpoint, a malformed witness or entry, a reordered sequence, or a different `T` or `X`. A rejected block changes nothing, and the sequencer must rebuild it with correct input.

The range always fits within `K` entries. In the first branch, `T` is the queue head and no checkpoint is read. In the second branch, `T` is the next stored checkpoint after `P`. At bootstrap `N0 - P <= K`, and later checkpoints are `K` entries apart. Before bootstrap at `R`, the first branch always applies.

Every block makes progress. No entry weighs more than `W`, so `X > P`. Each block either executes at least `W - MAX_ENTRY_WEIGHT + 1` weight or reaches `T`. While every queued entry weighs 1, `X = T`.

An entry `d` therefore executes within `ceil(w / (W - MAX_ENTRY_WEIGHT + 1)) + c` full blocks whose imported header includes it. Here `w` is the weight from `P` through `d`, and `c` is the number of checkpoints in that range.

The Inbox initializes token enablements before entries, as today. Deposit and bounce-back execution and failure rules are unchanged. The Inbox sets `P = X` and updates `processedDepositQueueHash` to the hash through `X` atomically. `TempoAdvanced.depositsProcessed` reports the executed count.

Implementations check `P <= N_R` before subtracting. They compare `N_R - P` with `K` to avoid overflow in `P + K`. They evaluate `j` and `T` only in the second branch.

#### Examples

With the initial `K = W = 230`, `N0 = 0`, and only weight-1 entries, `X = T`. Each row is an independent block:

| `P` | `N_R` | `T` | Entries executed | Checked against |
| --- | --- | --- | --- | --- |
| 100 | 200 | 200 | 101–200 (100) | Queue head at 200 |
| 200 | 430 | 430 | 201–430 (230) | Queue head at 430 |
| 200 | 431 | 230 | 201–230 (30) | `C[1]`, the hash at 230 |
| 230 | 460 | 460 | 231–460 (230) | Queue head at 460 |

At `P = 200`, raising `N_R` from 430 to 431 puts the head out of reach, so `T` drops to the checkpoint at 230. Later blocks process full buckets.

Starting at `P = 0` with `N = 500`, successive blocks process 1–230, 231–460, and 461–500. If entry 501 arrives later, execution resumes from the hash at 500.

On an existing Portal bootstrapped at `N0 = 430` with `P = 200`, entry 431 gives `N_R = 431`. The block selects `j = 0`, executes 201–430, and checks against `C[0]`.

#### Sizing

The Inbox test `max_portal_deposit_and_token_block_fits_system_gas_budget` measures 203,667,510 gas for `W` worst-case deposits and 8 maximum-metadata token enablements. The target is 225,000,000 gas.

That test sends every deposit to one recipient under a reject-all policy, so almost all of its L1 reads are warm. Without the 20-entry reserve, a block can also execute more than 20 bounce-backs. The following MUST be measured within the target before this TIP activates:

- a block of bounce-backs;
- deposits to distinct recipients with full receive policies under a compound token policy;
- the extra Portal reads.

#### Recovery

[TIP-1096](./tip-1096.md)'s header-only blocks are unchanged: they import Tempo headers without processing entries, token enablements, user transactions, or withdrawals. Each full block imports exactly one new header, so processing another bucket requires another full block. Recovery time therefore depends on how often the sequencer produces full blocks.

Header advancement MUST preserve unprocessed entry payloads. A queued backlog MUST NOT force decryption, execution, hashing, or entry-specific witnesses for the whole backlog before a bounded full block can proceed.

### Settle

The sequencer calls `submitBatch` with a batch that ends in a full block. The batch's processed position may lag the queue head. `DepositQueueTransition`, its binding in the settlement attestation, and `submitBatch`'s checks already allow that and are unchanged:

```text
prevDepositNumber == S
prevDepositNumber <= nextDepositNumber <= depositCount
```

After the proof is accepted, `submitBatch`:

1. Snapshots the block's tier if this block has none yet ([Price per block](#congestion-premium)).
2. Sets `S` to `nextDepositNumber`.
3. Sets `settledDepositWeight` to the largest of three lower bounds on the weight through `S`. It starts at zero and stays unchanged while `depositBuckets` is empty.
4. Lowers `depositPriceTier` to the tier from the new state if that is lower ([Price per block](#congestion-premium)).
5. Runs [Prune](#prune).

```text
(prev, prevS) = settledDepositWeight and S before this settlement
(c, Wc)       = position and cumulative weight of the latest checkpoint at or below S, if any
(u, Wu)       = position and cumulative weight of the next checkpoint above S,
                or (N, depositWeight) if there is none
settledDepositWeight = max(prev + max(0, S - max(prevS, N0)),
                           Wc + (S - c),
                           Wu - MAX_ENTRY_WEIGHT * (u - S))
```

Every entry weighs at least 1 and at most `MAX_ENTRY_WEIGHT`, so all three terms are lower bounds. The first keeps the bound from decreasing, so settlement never raises the tier. The second is exact when `S` is at a checkpoint, the third when `S` is at the head. The second term is skipped while `S < N0`, and the third when it would be negative. At bootstrap, checkpoint 0 has cumulative weight zero, so a settlement at or below `N0` leaves the bound unchanged. After a [`K` re-base](#adjusting-limits-and-weights), checkpoint 0 carries the weight appended before it, so the third term bounds a settlement below the new base.

[Prune](#prune) never deletes the latest checkpoint at or below `S` or any checkpoint above it, so step 3 always finds the checkpoints it reads, in this settlement and every later one. Neither `processWithdrawals` nor an unproven sequencer claim can advance `S`.

### Prune

Checkpoint `j` can be deleted once the next checkpoint is also settled: `N0 + (j+1)*K <= S`. Processing reads only checkpoints above `P`, and `P >= S`. Settlement reads only the latest checkpoint at or below `S`, which this rule keeps, and the next one above it. A deletable checkpoint is therefore never needed again.

The Portal prunes after settlement advances `S`, and on each successful append and `processWithdrawals` call. Each run deletes up to `DEPOSIT_BUCKETS_PRUNED_PER_CALL` consecutive eligible checkpoints from `nextDepositBucketToPrune` (`G`) onward. A run never changes or reuses indices, and never changes the array length, the open tail, or the Inbox's processed hash. No call does work proportional to the backlog, and one `processWithdrawals` call shares a single allowance. There is no public pruning function.

Pausing stops appends and `processWithdrawals`, and since T14 the sequencer also stops settling. Pruning resumes with the first eligible call after the pause ends. While pruning keeps pace, at most `(N - S) / K + 2` checkpoints are live.

#### Storage credits

Under [TIP-1060](./tip-1060.md), each deletion earns the Portal a storage credit, shared with withdrawal-queue slot deletions. A credit covers 245,000 gas of a later storage creation, while clean creations still pay a 5,000-gas residual. Each checkpoint takes two slots, created by the append that completes its bucket, and pruning it earns two credits.

In TIP-1060's default `Refund` mode, a creation pays its full cost upfront and is refunded at the end of the transaction. A checkpoint write would then need about 490,000 gas of headroom even when credits are available. Checkpoint and bootstrap writes therefore spend credits directly:

1. The append runs [Prune](#prune) before the write, so credits it earns are available.
2. Immediately before the write, the Portal calls `setBudget(n)` on the TIP-1060 precompile. `n` is the number of slots the write can create: 2 for a checkpoint, 4 at bootstrap.
3. Immediately after the write, the Portal calls `setMode(Refund)`. No external call happens in between.

With credits available, each new slot costs the 5,000-gas residual. Without them, the write pays the full creation cost, and the append succeeds only if its gas limit covers it. Credits can run short at bootstrap, when live checkpoints exceed their previous maximum, or when withdrawal-queue creations have spent them. Restoring `Refund` keeps later creations in the transaction refundable.

TIP-1060 keeps `Refund` as the default because gas in `Direct` mode depends on the credit balance at inclusion. This TIP accepts that for checkpoint writes. Callers need fixed headroom in either mode, because other appends can move a deposit onto a bucket boundary before inclusion. Callback deposits also pay the withdrawal fee on their whole `gasLimit`. In `Direct` mode, a callback that budgets the with-credit cost bounces back only when credits run short, not at every bucket boundary.

### Forced exits

TIP-1012 activates in a later fork and adds forced exits as `DepositType.ForcedExit` entries in this queue. Its draft weights them at L1 admission: a forced exit counts `FORCED_EXIT_ADMISSION_WEIGHT` units and every other entry 1 against the `MAX_UNPROCESSED_DEPOSITS` cap, freed only at settlement. Admission pays `FORCED_EXIT_FEE` to the admin.

This TIP enforces weights per block during Zone execution instead ([Process](#process)). Once TIP-1012 activates on top of this TIP, each forced exit:

1. weighs what TIP-1012 sets, following [Adjusting limits and weights](#adjusting-limits-and-weights), and adds it to `depositWeight` at append;
2. pays `FORCED_EXIT_FEE` and no premium ([Congestion premium](#congestion-premium));
3. faces no admission cap, request limit, or reserve.

TIP-1012 sizes its forced exits per full block and restates the backlog cost in [Threat Model](#threat-model) for its weight and fee. It adds its storage without moving this TIP's slots. Its fee, encryption, authorization, and Zone execution are otherwise unchanged. [Compatibility](#compatibility) lists the parts of its draft this TIP replaces.

### Adjusting limits and weights

`K`, `W`, and entry weights are fork constants. A fork that raises the cost of executing an entry MUST lower `W` or raise weights in the same change. The costliest mix then stays within the block budget.

- **New entry types** get their weight, at most `W`, from the TIP that adds them. If it exceeds `MAX_ENTRY_WEIGHT`, that TIP raises `MAX_ENTRY_WEIGHT` to match. That TIP MUST measure its costliest mix within the [Sizing](#sizing) target before it activates, including a block that executes `W` weight and hashes the rest of a `K`-entry range.
- **`W` and weights** change at the fork boundary. A full block still verifies at most `K` entries, where `K` is the spacing of the Portal's current checkpoints, and executes at most `W` weight. A block never executes past its target, so while entries weigh 1, a `K` below `W` leaves weight unused. Raising `MAX_ENTRY_WEIGHT` keeps [Settle](#settle)'s bounds valid, because earlier entries weigh no more than the new maximum.
- **`K`** changes per Portal. A Portal re-bases its checkpoints at its first append where its spacing differs from the runtime's `K` and `N - S <= K`. Re-basing follows [bootstrap](#activation-on-existing-portals): it sets the base to `depositCount` and appends the current queue hash as the new checkpoint 0. Unlike bootstrap, the new checkpoint 0 stores the current `depositWeight` as its cumulative weight, and neither weight counter resets. Because `S <= P`, the Zone then reaches the new base within `K` entries and never reads an older checkpoint; pruning removes them. Until it re-bases, the Portal keeps its old spacing.
- The first fork that changes `K` appends each Portal's spacing and the index of its current checkpoint 0. Until then, every Portal uses the initial `K` from index 0.
- `CONGESTION_MAX_FEE` equals TIP-1012's `FORCED_EXIT_FEE`, so a fork that changes one changes both.

## Interfaces

### Constants and storage

The current Portal layout ends in slot 28 with `transfersEnabled`. The Portal appends:

```solidity
struct DepositBucket {
    bytes32 hash;             // C[j]
    uint64 cumulativeWeight;  // depositWeight through N0 + j*K
}

// Queue checkpoints
uint64 public constant DEPOSITS_PER_BUCKET = 230;     // K: entries between checkpoints
uint64 public constant DEPOSIT_BUCKETS_PRUNED_PER_CALL = 2; // checkpoints one prune run may delete

// Entry weights (every entry type in this TIP weighs 1)
uint64 public constant MAX_ENTRY_WEIGHT = 1;

// Congestion premium
uint64 public constant CONGESTION_TIER_WEIGHT = 230;
uint64 public constant CONGESTION_MAX_TIER = 32;
uint128 public constant CONGESTION_MAX_FEE = 100_000; // token units

// Storage, appended after the existing layout
DepositBucket[] public depositBuckets;  // slot 29
uint64 public depositWeight;            // slot 30
uint64 public settledDepositWeight;     // slot 30
uint64 public depositPriceBlock;        // slot 30
uint64 public depositPriceTier;         // slot 30
uint64 public depositBucketBase;        // slot 31
uint64 public nextDepositBucketToPrune; // slot 31
```

The Inbox defines `MAX_DEPOSIT_WEIGHT_PER_BLOCK = 230` (`W`), the most weight a full block executes. It uses the Portal's `DEPOSITS_PER_BUCKET`. The Portal and Inbox weigh each entry by its `DepositType`.

[Storage credits](#storage-credits) uses `setBudget` and `setMode` of the TIP-1060 Storage Credits precompile, `StdPrecompiles.STORAGE_CREDITS` in `tempo-std`.

The array opens a new slot, so the four counters share slot 30 and the rest of slot 28 stays free. Every append and every settlement writes slot 30, so the per-block price snapshot adds no extra slot write. `depositBuckets` is empty before bootstrap. Afterward its length is `1 + floor((N - N0) / K)`, including pruned entries. `nextDepositBucketToPrune` starts at zero, its default value. Existing slots keep their offsets, including the retired per-block counters in slots 24–25 and `_withdrawalReentrancyStatus` in slot 14.

### Portal functions, events, and errors

```solidity
/// @notice Deposit with a cap on the total fee.
/// @param maxFee Most the caller accepts to pay: operational fee plus congestion premium.
/// @dev Reverts with `FeeTooHigh` if the fee for this block exceeds `maxFee`.
function depositEncrypted(
    address token,
    uint128 amount,
    uint256 keyIndex,
    DepositPayload calldata encrypted,
    address tempoRefundRecipient,
    uint128 maxFee
) external returns (bytes32 newCurrentDepositQueueHash);

/// @notice Alias for the `depositEncrypted` overload with `maxFee`.
function deposit(
    address token,
    uint128 amount,
    uint256 keyIndex,
    DepositPayload calldata encrypted,
    address tempoRefundRecipient,
    uint128 maxFee
) external returns (bytes32 newCurrentDepositQueueHash);

/// @notice Total deposit fee from the current state: operational fee plus premium.
/// @dev Exact for the next block; never below the fee charged later in the current block.
function calculateDepositFee() external view returns (uint128 fee);

/// @notice Checkpoint `index`; zeros once pruned. Reverts if `index` is out of range.
function depositBuckets(uint256 index) external view returns (bytes32 hash, uint64 cumulativeWeight);

error FeeTooHigh(uint128 fee, uint128 maxFee);
```

The new runtime removes `MAX_UNPROCESSED_DEPOSITS()` and `DepositBlockCapacityExceeded`. Bindings keep both to decode older runtimes.

# Compatibility

Activation requires a hardfork that ships three things together:

- a new Portal runtime installed through `zone_runtime_fork` in `crates/evm/src/block.rs`, with storage untouched;
- Inbox rules, gated on the same fork, that accept Portal state written by either runtime; an empty checkpoint array means the queue head is in reach;
- new Nitro enclave measurements, because proving selects the enclave by L1 fork.

Off-chain software ships before activation and must keep working with the replaced runtime until the fork is live. The `spam_deposits` and withdrawal-planner changes below therefore take effect only once the L1 runs the fork.

| Integration | What changes |
| --- | --- |
| Depositors and wallets | Existing `deposit` and `depositEncrypted` calls work unchanged under normal load. During congestion they revert with `FeeTooHigh` instead of `DepositBlockCapacityExceeded`. Behavior does not degrade for them: the replaced runtime rejected deposits once 210 unsettled entries were queued, and tier 1 starts at 230. Wallets quote `calculateDepositFee()` and call the `maxFee` overload to keep depositing during congestion. |
| `SwapAndDepositRouter.sol` | Accepts two callback layouts and tells them apart by the ABI head size of the callback data. The legacy layout calls the legacy `deposit` and works on both runtimes under normal load. A deposit into another Zone's Portal is not a premium-exempt callback deposit. During congestion the legacy call reverts with `FeeTooHigh` and the withdrawal bounces back, as it does today with `DepositBlockCapacityExceeded`. A layout with a trailing `maxFee` calls the `maxFee` overload and can pay the premium, but needs the new runtime. Any other head size reverts with `InvalidCallbackLayout`. Existing callers keep working, and the router can deploy before the fork. `SwapAndDepositRouterCallback` takes an optional `max_fee` that selects the layout. |
| xtask `demo_swap_and_deposit` and `spam_deposits` | The demo keeps the legacy `deposit` call, which works on both runtimes under normal load. `spam_deposits` builds congestion, so it passes `maxFee` and needs the new runtime. |
| Portal admins | The deposit fee transfer now includes the premium. |
| Gas limits for appends | With storage credits available, an append that completes a bucket needs about 10,000 extra gas for its checkpoint. Pruning in the same call adds about 10,000 per deleted checkpoint. Without credits, the checkpoint needs about 490,000 extra, and the bootstrap append up to about 1,200,000. `eth_estimateGas` alone is not enough: before inclusion, other appends can move a deposit onto a bucket boundary, and other transactions can spend the Portal's credits. Wallets add the no-credit headroom, which costs nothing because unused gas is not charged. Callers that cannot tolerate an out-of-gas failure budget the case without credits. Callback `gasLimit` values and `SwapAndDepositRouter` routes may instead budget the with-credit cost and accept a bounce-back when credits run short. |
| Sequencer: `L1BlockDeposits::prepare_many` | Replace the `MAX_UNPROCESSED_DEPOSITS` assertion with range selection. Supply `P+1 ... T` and decrypt only `P+1 ... X`. |
| Sequencer: `PendingDeposits` and `DeferredPortalWork` | Track header and entry progress separately. Persist or backfill unprocessed payloads from L1 events across imports and restarts; the cap no longer bounds them. |
| Sequencer withdrawal planner | Once the fork is live, skip `withdrawal_deposit_headroom` and the `WITHDRAWAL_BOUNCEBACK_RESERVE` batching. Before that, keep both: the replaced runtime still reverts a batch that could exceed the cap. |
| Inbox precompile `advance_tempo` | Replace the required equality with `currentDepositQueueHash` at `R` with [Process](#process). Read Portal state through the typed `ZonePortalStorage` mirror (`L1State::read_portal`, `read_portal_vec_len`). |
| SPF `validate_system_inputs` | Keep `deposits.len() <= K`. The SPF re-executes the Inbox, so it needs no separate check. |
| Shared constants | Replace `MAX_UNPROCESSED_DEPOSITS` in `tempo-contracts` and `zone-primitives` with `DEPOSITS_PER_BUCKET` and `MAX_DEPOSIT_WEIGHT_PER_BLOCK`. |
| `IZone.sol`, `ZonePortalStorage`, `storage-layouts/ZonePortal.json` | Append the storage fields and getters. Update slot comments and layout regression tests together. |
| `zones/specs/spec.md` | Update Deposit Queue, Withdrawal Processing, and SPF step 6. |
| TIP-1012 draft: capacity | Rebase onto this TIP's Portal. Drop admission weighting (`_outstandingDepositWeight`), `remainingDepositCapacity()`, the settlement walk in `_confirmDeposits`, the forced-exit request limit, and the reserve. Replace `FORCED_EXIT_ADMISSION_WEIGHT` with a per-block execution weight and raise `MAX_ENTRY_WEIGHT` to it ([Adjusting limits and weights](#adjusting-limits-and-weights)). |
| TIP-1012 draft: storage and withdrawals | Add its storage without moving this TIP's slots. Drop `forcedExitRequests`, `_lastProcessedForcedExitId`, and the `forcedExitRequests` getter; `ForcedExitRequested` and the returned `depositNumber` cover lookups. Drop the weighted `processWithdrawals` check and the sequencer's batch sizing from `remainingDepositCapacity()`. |
| TIP-1012 draft: fees | Unchanged; forced exits pay no premium. `FORCED_EXIT_FEE` stays equal to `CONGESTION_MAX_FEE`. |
| TIP-1012 draft: invariants | Invariant 3 (timeliness) becomes the progress bound in [Process](#process), `ceil(w / (W - MAX_ENTRY_WEIGHT + 1)) + c`. Invariant 7 becomes: each full block executes at most `W` weight, and queue depth never blocks admission. |
| TIP-1012 draft: capacity sizing | Replace the admission-time forced-exit budget with the forced exits that fit `W` at its weight, measured as [Sizing](#sizing) requires. |
| TIP-1150 | It assumes `MAX_UNPROCESSED_DEPOSITS` and the reserve; align it with this TIP. |

Withdrawal-processing and batch-submission signatures are unchanged.

# Observability

| Event | Question it answers |
| --- | --- |
| `DepositMade` (existing) | What did the deposit pay in total (`fee`), and where is it in the queue (`depositNumber`)? |
| `ZoneInbox.TempoAdvanced` (existing) | How many entries did the block execute (`depositsProcessed`), and where is `P`? |
| `ZonePortal.BatchSubmitted` (existing) | Where is `S`? |

An entry with deposit number `d` has executed once `P >= d`, and is confirmed on L1 once `S >= d`. Wallets estimate the wait from the weight queued between `P` and `d`.

Operators monitor:

- backlog weight (`depositWeight - settledDepositWeight`) and the current tier;
- settlement lag;
- pruning lag (`nextDepositBucketToPrune` against eligible checkpoints).

# Threat Model

The most consequential attack is building a backlog ahead of a victim to delay it, especially a TIP-1012 forced exit. The queue is first in, first out, so entries appended after the victim delay it by at most one block (see Head out of reach below). The attacker must build the backlog before the victim submits. Delaying an entry by `D` full blocks needs `D * W` weight ahead of it.

Under this TIP, only deposits and withdrawal-generated entries add weight. Each deposit weighs 1 and pays `congestionFee(b)` plus the operational fee, so a full block of new backlog costs `W * congestionFee(b)` in premiums, 23 tokens at the cap. At one full block per 550 ms L1 block, sustaining a backlog at the cap costs about 42 tokens per second. Entries that weigh more and pay no premium, such as TIP-1012 forced exits, lower this cost; TIP-1012 restates it ([Forced exits](#forced-exits)). The tier cannot rise within an L1 block, so entries appended in one block pay at most that block's starting tier. Raising the tier quickly therefore costs less when L1 gas admits many appends per block.

| Actor | Controls | Check that stops them | Consequence if it fails |
| --- | --- | --- | --- |
| Depositor or spammer | Appends deposits and pays their fees | Congestion premium; queue order | Delays later entries, at a cost per full block of backlog that rises with the tier. The backlog raises every later deposit's premium up to `CONGESTION_MAX_FEE`, and legacy deposit calls revert with `FeeTooHigh` until it settles. Cannot reject a deposit whose `maxFee` covers its charge, skip or reorder entries, or delay entries appended before its own by more than one block. |
| Sequencer | Payloads, decryption data, block and settlement timing | Inbox range and prefix rules; batch proof | Cannot skip, reorder, or stop early. Can slow all processing by producing fewer full blocks, and raise the price up to the cap by delaying settlement. |
| Portal admin | Receives operational fees, forced-exit fees, and premiums; pause | Existing access checks | Its own deposits pay their fees to itself, so it can build backlog for the cost of L1 gas and delay later entries, including forced exits. An admin that also runs the sequencer earns premiums while settlement lags, up to the cap. Pausing stops appends and pruning. It cannot change queue order. |
| Block proposer | Inclusion and ordering | [Price per block](#congestion-premium) | Cannot raise a pending deposit's tier by ordering other entries ahead of it. |

Residual risks:

- **Checkpoint rounding.** During a backlog, each block stops at the next checkpoint, even if it has weight budget left. A bucket that weighs more than `W` therefore takes two blocks instead of one. While every entry weighs 1, no bucket does.
- **Head out of reach.** An append that moves the queue head more than `K` entries past `P` makes the next block stop at the next checkpoint instead of the head. An entry that block would have reached waits one more block. It costs one deposit, possibly at tier 0. The delay happens at most once per entry: the following block starts at that checkpoint, and the entry lies within its next `K` entries. The `c` term in the progress bound covers it.
- **Storage-credit shortfalls.** A checkpoint write without available credits pays the full creation cost. A callback deposit that budgeted only the cost with credits then runs out of gas, and its withdrawal bounces back. Checkpoints and withdrawal-queue slots draw on the same credits.
- **Unpriced withdrawal-generated entries.** A Zone withdrawal to a failing recipient bounces back without a premium. Only withdrawal throughput and the withdrawal fee limit this path.
- **No bounded waiting time.** Entries wait behind earlier entries, and the sequencer controls full-block cadence.
- **No cancellation.** Accepted funds can stay queued indefinitely.

# Invariants

Starting from a Portal and Zone that satisfy the replaced runtime's invariants, these hold in every reachable state:

1. Entries execute in queue order, each at most once.
2. Each full block executes exactly the prefix [Process](#process) selects from the Portal state at `R`, so it verifies at most `K` entries and executes at most `W` weight.
3. In each full block with `P < N_R`, the executed weight is at least `W - MAX_ENTRY_WEIGHT + 1`, or the block reaches its target `T`.
4. No append is rejected because of queue depth, except a deposit whose charge exceeds its `maxFee`.
5. `S <= P <= N`.
6. Pruning deletes a checkpoint only once the next checkpoint is at or below `S`, so every checkpoint a full block needs is stored at `R`, and every checkpoint a settlement reads is stored when it runs.
7. No deposit pays a tier above the tier at the start of its L1 block, or above the lowest tier reached earlier in that block.
8. No deposit charges more than its `maxFee`, no premium exceeds `CONGESTION_MAX_FEE`, and forced exits and withdrawal-generated entries pay none.
9. The Portal's TIP-1060 storage-creation mode is `Refund` whenever the Portal makes an external call or returns.

Tests must cover:

- bootstrap on an existing Portal at every outstanding count up to `K`, including targets that need `C[0]`, and on a new Portal;
- settlement before bootstrap, and the tier while entries appended before bootstrap are unsettled;
- range selection at and around checkpoints, including a queue head past a checkpoint, and a later append that moves the head out of reach and delays an earlier entry by exactly one block;
- weighted prefixes with forced exits, hashed-only entries resumed by later blocks, and malformed hashed-only entries;
- the gas target at every mix in [Sizing](#sizing);
- settlement with a lagging position, consecutive settlements within one bucket and across a checkpoint, the `settledDepositWeight` update with and without forced exits between the checkpoint and `S`, including a fully settled queue after forced exits in the open bucket, a short settlement after an exact one, and settlements across a `K` re-base, and bounded pruning that keeps the latest settled checkpoint;
- the premium at tiers 0, 1, 31, 32, and above, and forced exits raising the tier without paying a premium;
- per-block tiers, including exempt appends and settlement earlier in the block that cross a tier boundary, a same-block `calculateDepositFee()` quote passed as `maxFee` after a settlement, with appends between the quote and the deposit, `FeeTooHigh` at and above `maxFee`, existing entry points under congestion, and exempt entries;
- the premium included in the admin fee transfer, and a deposit that reverts when that transfer fails;
- checkpoint and bootstrap writes with and without credits, credits earned by pruning in the same append, the creation mode restored to `Refund` after every append, and a callback deposit that completes a bucket within the gas it needs with credits;
- router callbacks in both layouts, and a head size that matches neither;
- storage layout regression across the fork.

Cases with forced exits run once TIP-1012 activates.
