# Secure Workflow Report: Dices launchpad

**Skill**: Trail of Bits `secure-workflow-guide` (building-secure-contracts 1.1.1)
**Date**: 2026-11-25, commit `bcd45b2` (`main`)
**Scope**: `src/`, with `script/deployment/V001.s.sol` for deployment checks
**Tools**: Slither 0.11.5, Forge 1.9.0. Echidna, Medusa, Manticore and Halmos are not installed.

Finding IDs (`DICES-nn`) refer to [`findings.md`](findings.md).

## Workflow checklist

| Step | Status | Result |
| --- | --- | --- |
| 1. Known security issues (Slither) | Done | 95 results triaged: 0 exploitable, 4 lead to findings recorded elsewhere, the rest are false positives or style |
| 2. Special features | Done | No upgradeability. ERC-20 conformance passes. Token integration reviewed in its own report |
| 3. Visual inspection | Done | Three printers saved and reviewed |
| 4. Security properties | Documented | 24 properties written down; 16 are tested today, 8 are untested or only partly tested. No fuzzer beyond Foundry is set up |
| 5. Manual review | Done | Front-running and oracle sections produce findings, one of them Medium (DICES-05); privacy and cryptography do not |

## Baseline

- `forge build --sizes` succeeds. `DicesHook` runtime size is 23,077 bytes, 1,499 under the EIP-170 limit.
- `forge test`: 127 tests in 14 suites pass.
- `forge lint` warnings at build: 8 `missing-zero-check`, 9 `reentrancy-events`, 3 `unused-return`,
  2 `arbitrary-send-eth`, 1 `unsafe-typecast`. They overlap the Slither results below.

---

## Step 1: Known security issues

Command: `slither . --exclude-dependencies`. Raw output: [`slither/slither-detectors.txt`](slither/slither-detectors.txt).
(The 3.6 MB JSON form of the same results was not kept.)

Slither analysed 73 contracts with 101 detectors and reported 95 results. It could not generate IR for three
functions, so no detector ran on their bodies: `DicesHook._swapFee` (`src/DicesHook.sol:458`),
`DicesHook._addInitialTokenLiquidity` (`:701`) and `InternalSwapPool.closeInternalSwapPool`
(`src/core/InternalSwapPool.sol:226`). The error is `'NoneType' object has no attribute 'parameters'`, a Slither
limitation with this compiler version. All three were reviewed by hand; `closeInternalSwapPool` is the most
security-sensitive function in the swap pool.

### Triage

| Detector | Impact | n | Verdict | Reason |
| --- | --- | --- | --- | --- |
| `arbitrary-send-erc20` | High | 1 | False positive | `CurrencySettler.settle` (`src/libraries/CurrencySettler.sol:41`) has a `transferFrom(payer, …)` branch, but the library is internal and its only caller passes `address(this)` (`src/DicesHook.sol:614`). The branch is unreachable in production. |
| `reentrancy-eth` | High | 1 | False positive | `_afterSwap` writes `poolLevel` after external calls (`src/DicesHook.sol:373-382`). Every callee is fixed code or owner-set: the swap pool, the escrow (`nonReentrant`), USDC, the PoolManager and the calculator. The "sends ETH" path is the native branch of `_creditFee`, which a USDC fee never takes. `poolLevel` only ratchets upward, so a stale read cannot lower it. |
| `weak-prng` | High | 2 | False positive | `%` is a ring index and a floor-division remainder (`src/calculators/LiveCalculator.sol:322`, `:331`), not randomness. |
| `divide-before-multiply` | Medium | 3 | False positive | Deliberate tick alignment to the spacing (`src/DicesHook.sol:673`, `src/core/InternalSwapPool.sol:173`, `:181`). The signed rounding is corrected on the next lines and checked by `testFuzz` cases in `test/CalculatorUpdates.t.sol` and `test/InternalSwapPool.t.sol`. |
| `incorrect-equality` | Medium | 3 | False positive | `_holdersChangedAt == block.number` (`src/DicesCoin.sol:170`) and `startedAt == 0` (`LiveCalculator.sol:273`, `:314`) are exact-match sentinels, not balance comparisons. |
| `unused-return` | Medium | 12 | Benign | Tuple fields that are deliberately dropped: unused `slot0` fields, `feesAccrued` from `modifyLiquidity` (the caller delta already includes it), `settle`'s paid amount (the unlock checks deltas), the tick from `initialize` (re-read from `slot0`), and `unlock`'s empty return. |
| `missing-zero-check` | Low | 7 | 1 valid, 1 false positive, 5 deployment-only | Valid: `_buyAndBurnRecipient` in the hook constructor (`src/DicesHook.sol:218`); a zero value makes every USDC-fee swap revert until the owner sets one (see DICES-01). False positive: `_owner`, which OpenZeppelin `Ownable` rejects. The `DicesCoin` and `LiveCalculator` constructor arguments are set once by `V001` and checked by `_requireWiring` (`script/deployment/V001.s.sol:510-532`). |
| `reentrancy-benign` | Low | 5 | Benign | State written after calls to the PoolManager or to fixed project contracts during launch and level sync. |
| `reentrancy-events` | Low | 3 | Benign | Events emitted after those same calls. |
| `shadowing-local` | Low | 1 | Benign | Constructor parameter `_owner` shadows the private `Ownable._owner`. |
| `timestamp` | Low | 3 | Accepted | The level window is measured in hours (`LiveCalculator.sol:277`, `:310`); a few seconds of timestamp drift does not matter. |
| `dead-code` | Info | 1 | False positive | `InternalSwapPool._creditFee` is reported unused only because its caller is one of the three functions Slither could not parse. |
| `low-level-calls` | Info | 1 | Accepted | The `staticcall` in `TrustedRouters._getSender` (`src/core/TrustedRouters.sol:44`) is deliberate so a misbehaving router cannot revert a swap. |
| `naming-convention` | Info | 47 | Style | Leading-underscore parameters and upper-case constant getters. |
| `pragma` | Info | 1 | Accepted | Seven pragma ranges across dependencies; project code is pinned to 0.8.38 by `foundry.toml`. |
| `unimplemented-functions` | Info | 2 | False positive | The interface functions are implemented by public state variables (`oracles`, `poolCoins`, and so on). |
| `immutable-states` | Optimization | 2 | Valid | `DicesHook.internalSwapPool` and `feeEscrow` (`src/DicesHook.sol:125`, `:145`) are written only in the constructor. Making them `immutable` saves two storage reads per swap and states the lock guarantee in the bytecode. Listed in DICES-16. |

Slither found none of the issues in `findings.md` rated Low or above, apart from the constructor zero-check
that is part of DICES-01. They are logic and configuration issues
outside what pattern detectors see.

**Goal check**: every result has a documented triage. A clean run needs a `slither.config.json` that excludes
`naming-convention` and suppresses the triaged items in place; the repository has none.

---

## Step 2: Special features

### Upgradeability: not applicable, verified

Search of `src/` for `delegatecall`, `upgradeTo`, `proxy`, `selfdestruct`, `assembly`, low-level `call` and
`LibClone` returns three relevant hits:

- `LibClone.cloneDeterministic` (`src/DicesHook.sol:551`): each coin is an EIP-1167 minimal clone of
  `coinImplementation`. A clone's implementation address is fixed in its bytecode. `setCoinImplementation`
  (`:806`) changes the implementation for later launches only.
- `UniswapEvents` is an externally linked library called by `DELEGATECALL` from the hook. Its address is patched
  into the hook's bytecode at deployment (`script/deployment/V001.s.sol:485-505`) and cannot change.
- `TrustedRouters._getSender` uses `staticcall`.

No proxy, no storage-layout coupling, no upgrade function. `slither-check-upgradeability` has nothing to check.

What does change after deployment is behaviour reached through owner-set addresses: the two calculators and the
trusted-router list. That is configuration rather than upgradeability, and it is where the owner's power sits
(DICES-03).

### ERC conformance: pass

`slither-check-erc . DicesCoin --erc erc20`: all required functions and events are present with correct types
and indexing ([`slither/check-erc20-DicesCoin.txt`](slither/check-erc20-DicesCoin.txt)). Two items are flagged
and both are expected for a solady token:

- "Must emit Transfer / Approval" is unchecked because solady emits from inline assembly, which the checker
  cannot follow. `test/DicesCoin.t.sol` asserts the events.
- No protection against the `approve` race. This is standard ERC-20 behaviour; `permit` and Permit2 are available.

### Token integration

Covered by [`tob-token-integration.md`](tob-token-integration.md).

### `slither-prop`

Not run. It generates Echidna properties and there is no Echidna here. The equivalent ERC-20 properties are
listed in Step 4.

---

## Step 3: Visual security inspection

Saved outputs: [`slither/inheritance-graph.dot`](slither/inheritance-graph.dot),
[`slither/printer-function-summary.txt`](slither/printer-function-summary.txt),
[`slither/printer-vars-and-auth.txt`](slither/printer-vars-and-auth.txt),
[`slither/printer-contract-summary.txt`](slither/printer-contract-summary.txt),
[`slither/printer-human-summary.txt`](slither/printer-human-summary.txt). The printer files include dependency
contracts and terminal colour codes.

### Inheritance

```mermaid
graph TD
    DicesHook --> BaseHook --> ImmutableState
    DicesHook --> Pausable --> Context
    DicesHook --> TrustedRouters --> Ownable --> Context
    DicesCoin --> SoladyERC20[solady ERC20]
    FeeEscrow --> ReentrancyGuard
    InternalSwapPool
    LiveCalculator
    FeeCalculator
```

- The hierarchy is shallow: three levels at most, one diamond on `Context` with no state.
- No function or state variable is shadowed in a way that changes behaviour. `pause` and `unpause` override the
  interface declarations only.
- `DicesHook` reaches `Ownable` through `TrustedRouters`, so ownership behaviour is OpenZeppelin's one-step
  `Ownable`, including `renounceOwnership` (DICES-04).

### Function summary

- Slither's human summary reports 1,024 source lines in `src/` and flags no project contract as complex except
  `DicesCoin`, which inherits solady's assembly.
- The longest logic paths are `InternalSwapPool.createInternalSwapPool` (`src/core/InternalSwapPool.sol:146-214`)
  and `closeInternalSwapPool` (`:226-279`), followed by `LiveCalculator._observe` and `_average`.
- External-call fan-out is highest in `DicesHook._afterSwap`: one swap can make three escrow deposits from the
  hook, three more from the swap pool, two `modifyLiquidity` calls, a `settle`, two `take`s and a calculator
  call. See the gas table in [`uniswap-v4-security-foundations.md`](uniswap-v4-security-foundations.md).

### Variables and authorisation

Who can write each piece of state, from the printer and the source:

| State | Written by | Guard |
| --- | --- | --- |
| `DicesHook.feeCalculator`, `liveCalculator`, `feeRecipient`, `buyAndBurnRecipient`, `coinImplementation`, `createFee`, `trustedRouters`, `_paused`, `_owner` | Owner setters | `onlyOwner` |
| `DicesHook.internalSwapPool`, `feeEscrow`, `usdc`, `poolManager` | Constructor | None needed; no setter exists |
| `DicesHook.poolKeys`, `poolCoins`, `poolCreators`, `coinCount` | `createCoin` | Anyone, unless paused |
| `DicesHook.launchBlock` | `unlockCallback` | PoolManager only |
| `DicesHook.lastSwapBlock` | `_beforeSwap` | PoolManager only |
| `DicesHook.poolLevel` | `_syncLevel`, from `_afterSwap` and `syncLevel` | Anyone can trigger; the value comes from `liveCalculator` |
| `InternalSwapPool.internalSwapPool` (inventory), `_internalSwapPoolState` | `deposit`, `createInternalSwapPool`, `closeInternalSwapPool` | `onlyHook` |
| `LiveCalculator.oracles`, `_checkpoints` | `qualify` | `onlyHook` |
| `FeeEscrow.claimable` | `deposit`, `claim`, `claimBatch` | Anyone; credits are funded on deposit and paid only to the beneficiary |
| `DicesCoin._holders`, `_holdersBefore`, `_holdersChangedAt` | Every transfer, mint and burn | Anyone, through their own transfers |
| `DicesCoin._name`, `_symbol`, `_initialized`, supply | `initialize` | Once, no caller check |

Printer limitations to keep in mind when reading the raw file: it shows no guard for the `onlyOwner` setters
(OpenZeppelin's `_checkOwner` is not recognised as an authorisation pattern), and the row for
`closeInternalSwapPool` is incomplete because its IR was not generated.

Observations:

- `poolLevel` is the one piece of pool state whose value is decided by a replaceable contract and then kept
  forever. The hook does not bound it: any `uint8` the calculator returns is stored (DICES-07).
- `poolCreators` is written from caller input without validation and is later used as a payment destination
  (DICES-01).
- `lastSwapBlock` is written on every swap and read by no contract or script in the repository (DICES-16).

---

## Step 4: Security properties

The properties below are what the code has to guarantee. "Tested" means a test in this repository asserts it;
the reference is to the test. Properties marked "Not tested" are the gap.

### State machine

| # | Property | Status |
| --- | --- | --- |
| S1 | `poolLevel` never decreases | Tested: `test/DicesHookLive.t.sol:107`, `:316` |
| S2 | No level unlocks before a pool has a full window of history | Tested: `test/DicesHookLive.t.sol:30`, `test/Calculators.t.sol` |
| S3 | `poolLevel <= LEVELS` | **Not tested and not enforced** in the hook (DICES-07) |
| S4 | Every level is reachable under the fixed supply and holder threshold | **Not tested; false for levels 9 and 10** (DICES-02) |
| S5 | The hook's launch positions are never reduced | Tested: `invariant_launchPositionsCannotBeRemoved` (`test/DicesHookInvariant.t.sol:105`) |
| S6 | `_internalSwapPoolState` is empty outside a swap | Tested indirectly through `test/InternalSwapPool.t.sol`; not asserted as an invariant |
| S7 | A pool that the hook launched always accepts a sell | **Not tested; false when `creator` is zero** (DICES-01) |

### Access control

| # | Property | Status |
| --- | --- | --- |
| A1 | Only the owner changes configuration | Tested: `test/DicesHook.t.sol` |
| A2 | Only the PoolManager reaches hook callbacks and `unlockCallback` | Tested: `test/DicesHook.t.sol` |
| A3 | Only the hook reaches the swap pool and `qualify` | Tested: `test/InternalSwapPool.t.sol`, `test/Calculators.t.sol` |
| A4 | No third party can initialise a pool on the hook or add liquidity to one | Tested: `test/DicesHook.t.sol` |
| A5 | A change of calculator cannot raise the fee of an existing pool above a stated cap | **No such cap exists** (DICES-03) |

### Accounting

| # | Property | Status |
| --- | --- | --- |
| C1 | Escrow token balance equals the sum of credits | Tested: `invariant_creditsRemainFullyFunded` (`:83`) |
| C2 | Swap pool coin balance equals its inventory ledger; the hook holds only launch dust and no USDC | Tested: `invariant_inventoryEqualsHeldTokens` (`:87`) |
| C3 | Every unlock ends with zero deltas for the hook, the swap pool and the router | Tested: `invariant_everyUnlockFinishesSettledAndSupplyIsConserved` (`:110`) |
| C4 | Coin supply is conserved by trading | Tested: same invariant |
| C5 | Fee equals `rate x unspecified amount`, rounded down, in all four swap modes and both orderings | Tested: `test/DicesHookTrading.t.sol` fuzz |
| C6 | `platform + creator + buyAndBurn == fee` for any calculator | Tested for the shipped calculator only (`test/Calculators.t.sol`); **not enforced** for a replacement |
| C7 | A sell followed by a buy in one unlock never leaves the caller with more USDC than it started with | **Not tested; does not hold** after a large exact-input buy (DICES-05) |

### Arithmetic

| # | Property | Status |
| --- | --- | --- |
| M1 | The holder count equals the number of countable addresses at or above the threshold | Tested: fuzz in `test/DicesCoin.t.sol` |
| M2 | `qualifiedHolders()` never includes an address that crossed the threshold in the current block | Tested: `test/DicesCoin.t.sol`, `test/DicesHookLive.t.sol:206` |
| M3 | The average tick equals the time-weighted mean of observed ticks over the window, rounded down | Tested: `test/Calculators.t.sol` |
| M4 | Every swap that succeeds records an observation | **Not tested in the repository**; checked for this review by a gas-limit scan (rejected candidate R-01 in `findings.md`) |
| M5 | Both orderings (coin as currency0 or currency1) behave identically | Unit and fuzz tests take a `bool coin0`; **the invariant suite runs one ordering only** (`test/DicesHookInvariant.t.sol:67`) |

### Fuzzing and verification setup

- Foundry invariants exist: one suite, five invariants, 64 runs at depth 32 (`foundry.toml`). The handler buys
  small exact-input amounts, sells and claims, in one currency ordering, with a stub level calculator and no
  time movement.
- No Echidna or Medusa configuration exists and neither tool is installed. No formal verification.
- The properties marked "Not tested" above are the ones worth adding first. S3, S7, A5 and C6 are one-line
  assertions once the corresponding fixes exist. C7 and M5 need the handler extended: larger buys, exact-output
  swaps, `vm.warp`, the real `LiveCalculator` and both orderings.
- I did not add tests or install tools; this review changes nothing outside `audits/`.

---

## Step 5: Manual review areas

### Privacy

Nothing on chain is meant to be secret. The brief's "sealed" game with a commitment (`gameCommitment` in
`AGENT.md`) is not in the code: `CoinParams` is `{name, symbol, creator}` (`src/interfaces/IDicesHook.sol:24-37`).
No commit-reveal exists to review.

### Front-running and ordering

- **Slippage** is the router's job. The hook neither reads nor enforces a minimum output, and nothing in `src/`
  references a deadline or price limit. This is the normal v4 arrangement, but it means a fee change by the
  owner between quote and execution is caught only by the trader's own slippage setting (DICES-03).
- **Launch block.** The guard at `src/DicesHook.sol:334` blocks untrusted routers in the launch block and
  exempts trusted ones. `V001` trusts the Universal Router (`script/deployment/V001.s.sol:238`), so as deployed
  anyone can buy in the launch block (DICES-06).
- **Creation order.** Coin addresses come from `coinCount` (`src/DicesHook.sol:551`), so a creator's predicted
  address shifts if another `createCoin` lands first. `createCoin` returns the address; integrations must use
  the return value.
- **Fee conversion.** Queued coin fees are sold in a one-tick-spacing position placed at the spot price at the
  start of the next buy (`src/core/InternalSwapPool.sol:168-212`). Any caller can move that price first inside
  one unlock, without holding coins, and keep the difference in USDC when the queue is large enough
  (DICES-05). This is the one finding in this section with a money profit for an unprivileged caller.
- **Level sync.** `syncLevel` is permissionless and idempotent; being first gains nothing.

### Cryptography

None in `src/`. The only hashes are the clone salt (`keccak256(abi.encode(block.chainid, coinCount++))`,
`src/DicesHook.sol:551`) and a constant position salt. No signatures are verified by project code; `permit` is
solady's. No randomness is used. The casino side, where randomness will matter, is out of scope.

### DeFi interactions

- **Oracle.** Levels are decided by a 24 to 25 hour time-weighted average of the pool's own tick plus a holder
  count. The design documents its limits (`AGENT.md`, "It does not stop a patient buyer"). The review checked
  three things the design relies on:
  - Every successful swap records an observation. Confirmed: no gas limit lets a swap through while the
    calculator call runs out of gas (rejected candidate R-01).
  - The price cannot be moved for free upward. Confirmed: the upper position reaches the usable tick limit
    (`src/DicesHook.sol:646`, `:653`).
  - The price can be moved for free downward once the pool's USDC is exhausted, because nothing sits below the
    launch tick. This lowers the average and can only delay a level. It needs more coins than the pool has sold,
    which in practice means the bankroll (DICES-21).
- **Flash liquidity.** The holder count ignores same-block joiners (`src/DicesCoin.sol:168-175`), which defeats
  borrowing coins from the PoolManager within one unlock. It does not defeat holding across one block boundary.
- **Flash accounting.** The hook and swap pool `take` USDC inside `afterSwap`, before the router has paid the
  swapper's input. That works because the PoolManager holds every pool's USDC; it is an integration assumption
  rather than a bug (DICES-19). The swap pool also calls `sync` inside the swapper's unlock, so a router that
  syncs before swapping fails with `CurrencyNotSettled`; the code documents this
  (`src/core/InternalSwapPool.sol:219-222`).
- **External protocol assumptions.** USDC can pause or block addresses; the hook, the swap pool and the escrow
  all sit in the swap path. Uniswap governance can switch on a protocol fee for any v4 pool. Neither is under
  the project's control; both are noted in `tob-token-integration.md`.

---

## Action plan

Ordered by what reduces risk most for the least change. Effort is for the code change and its test.

| Priority | Action | Finding | Effort |
| --- | --- | --- | --- |
| High | Reject a zero `creator` in `createCoin` and a zero `_buyAndBurnRecipient` in the constructor | DICES-01 | Under an hour |
| High | Decide what levels 9 and 10 should require, then change the floors or the threshold | DICES-02 | Client decision, then under an hour |
| High | Cap the fee rate in the hook and check that the split sums to the fee | DICES-03 | Half a day |
| High | Make `V001` refuse a mainnet deployment without a `PROTOCOL_OWNER`; move to two-step ownership | DICES-04 | Half a day |
| Medium | Separate "may trade in the launch block" from "is asked for `msgSender()`" | DICES-06 | Half a day |
| Medium | Bound the level returned by the calculator and make a malformed return non-fatal | DICES-07 | A few hours |
| High | Give fee conversion a price floor (for example the pool's own time-weighted average), or charge buy fees in USDC | DICES-05 | Design decision, then one to two days |
| Low | Add `slither.config.json` and run Slither in CI | Step 1 | An hour |
| Low | Extend the invariant handler and raise runs and depth | Step 4 | One to two days |
| Low | Bring `AGENT.md` and `README.md` in line with the code | DICES-17 | Half a day |
