# Audit Context: Dices launchpad

**Skill**: Trail of Bits `audit-context-building` 1.1.0
**Date**: 2026-11-25, commit `bcd45b2` (`main`)
**Scope**: `src/`, with `script/deployment/V001.s.sol` for deployment-time facts

This is the system model the rest of the review was built on. Following the skill, it describes what the code
does and what it assumes. It does not rate anything; findings are in [`findings.md`](findings.md).

It has three layers:

1. This file: orientation (the skill's Phase 1) and the global model (Phase 3).
2. Per-function micro-analysis (Phase 2), one file per module, each written by a separate reviewer working
   line by line:
   - [`context/01-hook-swap-path.md`](context/01-hook-swap-path.md)
   - [`context/02-launch-admin-coin.md`](context/02-launch-admin-coin.md)
   - [`context/03-internal-swap-pool-and-escrow.md`](context/03-internal-swap-pool-and-escrow.md)
   - [`context/04-calculators-and-levels.md`](context/04-calculators-and-levels.md)
3. The entry-point map in [`tob-entry-points.md`](tob-entry-points.md).

`AGENT.md` is the project's design reference, but its Fees, Ledgers, Contracts and Configuration sections
describe an earlier design. Everything below is taken from the code.

---

## Phase 1: Orientation

### Contracts

| Contract | Lines | Role as built |
| --- | --- | --- |
| `DicesHook` (`src/DicesHook.sol`) | 853 | Launches coins, owns the launch liquidity, charges the swap fee through the `afterSwap` return delta, keeps each pool's level. `BaseHook` + `Pausable` + `Ownable`. |
| `InternalSwapPool` (`src/core/InternalSwapPool.sol`) | 366 | Holds coin-denominated fees and sells them for USDC through a one-swap liquidity position opened in `beforeSwap` and closed in `afterSwap`. |
| `FeeEscrow` (`src/core/FeeEscrow.sol`) | 121 | Funded credit ledger per beneficiary and currency. Anyone deposits, anyone triggers a payout, funds go only to the beneficiary. No admin. |
| `LiveCalculator` (`src/calculators/LiveCalculator.sol`) | 413 | Per-pool tick history with hourly checkpoints; returns the level that the 24 to 25 hour average tick and the holder count support. |
| `FeeCalculator` (`src/calculators/FeeCalculator.sol`) | 106 | Stateless: fee rate (1.25% before Live, 1.00% after), split (40% platform, 30% creator, 30% buy and burn), launch price. |
| `DicesCoin` (`src/DicesCoin.sol`) | 250 | solady ERC-20, deployed as a minimal clone per launch, 1e27 supply minted once, with a running count of holders at or above 300,000 coins. |
| `TrustedRouters` (`src/core/TrustedRouters.sol`) | 53 | Owner-managed router list and a `staticcall` to `msgSender()`. |
| `CurrencySettler`, `UniswapEvents` (`src/libraries/`) | 65, 129 | Settlement helper used by the hook; event emitters in a linked library. |

### Actors

| Actor | Can do | Trusted for |
| --- | --- | --- |
| Owner of `DicesHook` | Replace both calculators, set fee and burn recipients, coin implementation, creation fee, trusted routers; pause launches; transfer or renounce ownership | Everything that is configurable. A deployer EOA unless `PROTOCOL_OWNER` is set in `V001` |
| Creator | Call `createCoin`, name the coin, name a fee beneficiary | Nothing. Anyone can be a creator |
| Trader | Swap through any router; hold, transfer and burn coins | Nothing |
| Trusted router | Swap in a pool's launch block; be asked who its caller is | Returning the right `msgSender()`; the answer is currently unused |
| Bankroll | Receive 10% of every coin at launch | Not dumping; nothing on chain restricts it |
| Fee recipients (platform, creator, buy and burn) | Be credited in the escrow | Nothing; they are destinations |
| Anyone | `syncLevel`, escrow `deposit` / `claim` / `claimBatch` | Nothing |
| Uniswap v4 PoolManager | Calls every hook callback; custodies all liquidity | Behaving as v4-core at commit `d153b048` |
| USDC | Paired currency of every pool | Standard transfer behaviour; can pause or block addresses |

### Storage that matters

| Variable | Meaning | Written |
| --- | --- | --- |
| `DicesHook.poolCoins[poolId]`, `poolKeys[coin]`, `poolCreators[poolId]` | Launch registry | Once, in `createCoin` (`src/DicesHook.sol:570-574`) |
| `DicesHook.poolLevel[poolId]` | Highest level unlocked; non-zero means Live | `_syncLevel` (`:439`), upward only |
| `DicesHook.launchBlock[poolId]` | Launch block, for the launch-block guard | `unlockCallback` (`:601`) |
| `DicesHook.feeCalculator`, `liveCalculator` | Replaceable logic | Owner |
| `InternalSwapPool.internalSwapPool[coin]` | Queued coin fees | `deposit` (`src/core/InternalSwapPool.sol:134`), `closeInternalSwapPool` (`:254`) |
| `InternalSwapPool._internalSwapPoolState` | The open position, between `beforeSwap` and `afterSwap` of one swap | `:212`, deleted `:234`. Ordinary storage, one slot pair for all pools |
| `LiveCalculator.oracles[poolId]`, `_checkpoints[poolId]` | Tick history | `qualify` → `_observe` (`src/calculators/LiveCalculator.sol:266-295`) |
| `FeeEscrow.claimable[beneficiary][currency]` | Credits | `deposit` (`src/core/FeeEscrow.sol:71`), `_claim` (`:110`) |
| `DicesCoin._holders`, `_holdersBefore`, `_holdersChangedAt` | Holder count and its value before this block's changes | `_afterTokenTransfer` (`src/DicesCoin.sol:215-223`) |

---

## Phase 3: Global model

### Workflow 1: launch (`createCoin`)

1. Collect the optional ETH creation fee into the escrow for `feeRecipient` (`src/DicesHook.sol:535-547`).
2. Clone `coinImplementation` at a salt of `(chainid, coinCount++)` and initialise it: 1e27 coins to the hook
   (`:551-554`).
3. Transfer 100M coins to `DicesCoin(coin).bankroll()` (`:558`).
4. Build the pool key (fee 0, spacing 60, this hook; ordering by address) and record coin, key and creator
   (`:561-574`).
5. `poolManager.unlock` → `unlockCallback` (`:587-618`): initialise at the calculator's launch price, record
   `launchBlock`, add two coin-only positions, settle the coin owed.
   - Sale position: 700M coins from the first usable tick on the coin's upside of the launch price to the tick
     of a $200k market cap.
   - Upper position: 200M coins from there to the usable tick limit.
   - The ranges mirror when the coin is currency1.
6. Rounding dust stays in the hook. No USDC is involved.

The PoolManager skips callbacks for calls made by the hook itself, so `beforeInitialize` and
`beforeAddLiquidity` do not run during a launch. They exist to stop everyone else.

### Workflow 2: swap

Order inside one `PoolManager.swap`:

1. `beforeSwap` (`src/DicesHook.sol:325-358`)
   - Revert if this is the launch block and the router is not trusted.
   - Write `lastSwapBlock`.
   - `createInternalSwapPool`: if the swap buys the coin, inventory is at least 1e6 raw units and the pool has
     active liquidity, open a single-sided position one tick spacing wide on the coin's upside of the spot
     price, sized from the whole inventory and clamped to the tick's remaining capacity. Store its
     parameters and the delta owed.
   - Return a zero delta. `beforeSwapReturnDelta` is not enabled.
2. The pool swaps, through the hook's liquidity and the temporary position together.
3. `afterSwap` (`:372-386`)
   - `closeInternalSwapPool`: remove the position; the net of the two deltas is coins spent and USDC received.
     Reduce inventory, settle the coins, take the USDC, split it with the swap pool's own calculator and credit
     the three recipients in the escrow.
   - `_swapFee`: fee = unspecified amount × rate ÷ 100,000, where the rate is read from the calculator with the
     pool's Live state as it stands before this swap's level sync.
   - `_collectSwapFee`: return the fee as a positive hook delta and `take` it. A coin fee goes to the swap
     pool's inventory. A USDC fee is split by the hook's calculator and credited in the escrow.
   - `_syncLevel`: `try liveCalculator.qualify(key)`; record a higher level if one is returned.
   - Emit `HookFee` (if any), `HookSwap`, `PoolStateUpdated`.

Which currency the fee is in:

| Swap | Unspecified currency | Fee paid in | Goes to |
| --- | --- | --- | --- |
| Buy, exact USDC in | Coin | Coin | Swap pool inventory, converted on a later buy |
| Buy, exact coin out | USDC | USDC | Escrow credits, at once |
| Sell, exact coin in | USDC | USDC | Escrow credits, at once |
| Sell, exact USDC out | Coin | Coin | Swap pool inventory |

### Workflow 3: levels

- Every swap, and every `syncLevel` call, makes one observation: add `previous tick × seconds since the last
  observation` to a running total, checkpoint the total at each hour boundary passed, store the current tick.
- The average is `(total now − total at the hour 24 hours before the current hour) ÷ elapsed`, rounded down.
  It is unavailable until the 25th hour after the hour of the first observation.
- The coin tick is the pool tick when the coin is currency0 and `−tick − 1` when it is currency1.
- The level is the highest whose tick the average reaches, then lowered until the coin's
  `qualifiedHolders()` meets that level's floor.
- The hook stores the result only if it is higher than what it has.

### Workflow 4: fee payout

Credits accumulate in `FeeEscrow.claimable`. Anyone calls `claim` or `claimBatch`; the full credit is sent to
the beneficiary. Nothing else leaves the escrow.

### Invariants the code relies on

Numbered for reference from the findings. "Enforced" says where; "Assumed" means nothing in the code checks it.

| # | Invariant | Status |
| --- | --- | --- |
| I1 | Only the hook can create a pool that uses the hook | Enforced: `_beforeInitialize` reverts for every caller that reaches it (`src/DicesHook.sol:256`) |
| I2 | Only the hook and the swap pool add liquidity; only the swap pool removes it; the swap pool removes only what it added in the same swap | Enforced for callers (`:291`, `:303`); the "same swap" part follows from the swap pool's code and the PoolManager keying positions by owner |
| I3 | The hook never swaps | Assumed by the oracle (`:422-425`); true of the current code |
| I4 | Every price change is followed by an observation | Holds while I3 holds and `qualify` does not revert. A revert is swallowed (`:448`) |
| I5 | `beforeSwap` and `afterSwap` of one swap are not interleaved with another swap | Holds because nothing untrusted is called between them; `_internalSwapPoolState` depends on it |
| I6 | Escrow balance of each currency ≥ sum of credits in it | Enforced by the balance-difference check on deposit (`src/core/FeeEscrow.sol:65`) |
| I7 | Swap pool coin balance = inventory ledger | Maintained by `deposit` being called right after the transfer (`src/DicesHook.sol:475-476`) and by settling exactly `spent` |
| I8 | Every escrow beneficiary passed by the hook or swap pool is non-zero | **Assumed.** `feeRecipient` is guaranteed; `poolCreators[poolId]` and the constructor's `buyAndBurnRecipient` are not |
| I9 | The calculator returns a level between 0 and 10 in well-formed return data | **Assumed** (`:436-447`) |
| I10 | `platform + creator + buyAndBurn == fee` | True of `FeeCalculator` (`src/calculators/FeeCalculator.sol:87-93`); **assumed** of any replacement |
| I11 | The hook's calculator and the swap pool's calculator agree | **Assumed.** One is replaceable, the other immutable |
| I12 | Supply is 1e27 | True at launch; `burn` lowers it afterwards, while the calculator keeps using 1e27 |
| I13 | Every level's holder floor can be met | **Not true** of levels 9 and 10 (3,800 and 5,800 holders × 300,000 coins exceeds the supply) |
| I14 | The PoolManager can pay a USDC `take` during `afterSwap`, before the router settles the swapper's input | **Assumed.** True on a chain where the PoolManager holds other pools' USDC |
| I15 | The holder count equals the number of countable addresses at or above the threshold | Maintained in `_afterTokenTransfer`; fuzz-tested |
| I16 | `qualifiedHolders()` never reports more holders than existed before the current block's first change | Enforced (`src/DicesCoin.sol:170`) |
| I17 | The pool's spot price at the start of a buy is a fair price at which to sell the queued fee coins | **Assumed.** `createInternalSwapPool` reads `slot0` and places the whole queue there (`src/core/InternalSwapPool.sol:168-212`); nothing compares it with any reference |
| I18 | A caller cannot sell coins it does not hold | **Not true inside an unlock.** v4 flash accounting lets a contract sell coins it only owes and buy them back before settling; the hook treats both swaps as ordinary |

### Trust boundaries

```mermaid
graph LR
    Trader -->|swap| Router
    Router -->|unlock, swap| PM[PoolManager]
    PM -->|callbacks| Hook[DicesHook]
    Hook -->|create / close / deposit| ISP[InternalSwapPool]
    ISP -->|modifyLiquidity, settle, take| PM
    Hook -->|take| PM
    Hook -->|deposit| Escrow[FeeEscrow]
    ISP -->|deposit| Escrow
    Hook -->|getSwapFee, getFeeDistribution| FeeCalc[FeeCalculator, replaceable]
    ISP -->|getFeeDistribution| FeeCalc0[FeeCalculator, fixed at deploy]
    Hook -->|try qualify| LiveCalc[LiveCalculator, replaceable]
    LiveCalc -->|qualifiedHolders| Coin[DicesCoin clone]
    Hook -->|staticcall msgSender| Router
    Owner -->|setters| Hook
    Creator -->|createCoin| Hook
    Anyone -->|syncLevel| Hook
    Anyone -->|deposit, claim| Escrow
```

- Untrusted input enters in three places: `createCoin` parameters, swap parameters (through the PoolManager),
  and escrow deposits.
- The two calculators are the only code the hook calls that can be changed after deployment.
- `hookData` is passed through to the swap pool and ignored there. Nothing reads identity from it.

### Complexity and fragility clusters

1. **`createInternalSwapPool` / `closeInternalSwapPool`.** Two functions that only make sense as a pair,
   joined by a storage struct, run inside someone else's unlock, with tick rounding that differs by currency
   ordering and sign. Most assumptions per line in the codebase.
2. **`_afterSwap`.** Five steps whose order matters: the position must close before the fee is computed (the
   fee deposit would otherwise change the inventory being settled), and the fee must be computed before the
   level sync (so the swap that reaches Live pays the old rate).
3. **`LiveCalculator._observe` / `_average`.** Correct only because every hour boundary between two
   observations is checkpointed and the ring holds exactly 25 slots. Signed arithmetic in `int56`.
4. **Fee routing by currency.** The same economic fee takes two different paths depending on swap mode, uses
   two different calculator instances, and reaches recipients at different times.
5. **Deployment wiring.** Four contracts hold each other's addresses as immutables or constructor state; the
   addresses are predicted before any of them exists. `_requireWiring` checks the result after the fact.
