# Uniswap v4 Security Foundations assessment: DicesHook

| | |
| --- | --- |
| Skill | `uniswap-hooks` 1.6.0 / `v4-security-foundations` (loaded with the Skill tool; `references/audit-checklist.md`, `references/vulnerabilities-catalog.md` and `references/base-hook-template.md` read in full) |
| Commit | `bcd45b2` on `main` |
| Date | 2026-11-25 |
| Scope | `src/DicesHook.sol` and everything it calls inside hook callbacks: `src/core/InternalSwapPool.sol`, `src/core/FeeEscrow.sol`, `src/core/TrustedRouters.sol`, `src/calculators/LiveCalculator.sol`, `src/calculators/FeeCalculator.sol`, `src/libraries/CurrencySettler.sol`, `src/libraries/UniswapEvents.sol`, `src/DicesCoin.sol`; deployment and flag mining in `script/deployment/V001.s.sol`; tests in `test/` |
| Method | Manual read of every file in scope and of the v4-core code the answers depend on (`PoolManager.sol`, `libraries/Hooks.sol`, `libraries/Pool.sol`). Nothing was built, run or fuzzed by this reviewer. Size, test, coverage, Slither and gas figures are the ones measured earlier today and supplied with the task. No network access was used; the skill's external links were skipped. |

Conventions. Evidence is `file:line` in this repository. `v4-core/` is short for `lib/v4-hooks-public/lib/v4-core/src/`, `v4-periphery/` for `lib/v4-hooks-public/lib/v4-periphery/src/`, `BaseHook.sol` for `lib/v4-hooks-public/src/base/BaseHook.sol`. "ISP" is `InternalSwapPool`, "PM" is the Uniswap v4 `PoolManager`. An item passes only where the code that makes it pass was found; "not determined" means it could not be settled by reading.

## Summary

- The hook enables six of the fourteen permissions. `beforeSwapReturnDelta` is **not** enabled; `beforeSwap` returns a zero delta and a zero fee override. The only returned delta is the `afterSwap` fee, which equals the amount the hook `take`s in the same call.
- By reading, every delta the hook and the ISP create is closed inside the same `PoolManager.swap` call. No path was found that leaves a delta or the stored JIT state open between `beforeSwap` and `afterSwap`.
- Risk score: **19 of 33**, tier **High: professional audit required** (section 9). The permissions category is ambiguous in the skill; a risk-weighted reading gives 27 (Critical). Both are shown.
- Twelve findings are logged (section 10): one Medium, five Low, six Informational. None is a loss-of-funds path for swappers that was demonstrated by reading. The Medium is an owner-trust issue: the fee rate has no on-chain cap and ownership is single-step with no timelock.
- `AGENT.md` and `README.md` describe a different fee model from the code (USDC-only fees, ERC-6909 claims, reserve and race pool). The code was treated as the source of truth throughout.

## 1. Threat model

| Threat area | Applies to this hook | Evidence | Assessment |
| --- | --- | --- | --- |
| Caller verification | Every enabled callback and `unlockCallback` can only be entered by the PM. | External entry points carry `onlyPoolManager`: `BaseHook.sol:36-39, 62-67, 80-85, 144-147, 161-167`; modifier at `v4-periphery/base/ImmutableState.sol:17-20`; `src/DicesHook.sol:587`. The hook overrides only the internal `_before*`/`_after*` functions (`src/DicesHook.sol:254, 289, 302, 325, 372`). Test: `test/DicesHook.t.sol:259-275`. Helper contracts accept only the hook: `src/core/InternalSwapPool.sol:352-358` on `deposit`, `createInternalSwapPool`, `closeInternalSwapPool` (`:127, :146, :226`); `src/calculators/LiveCalculator.sol:146, 406-412`. | Mitigated |
| Sender identity | `msg.sender` is never used as the swapper. The `sender` argument is used as the router: for the launch-block allowlist check and for event topics. | `src/DicesHook.sol:334` (`trustedRouters[sender]`), `:378, :383` (events). The end user is resolved through `IMsgSender.msgSender()` on allow-listed routers by `staticcall` (`src/core/TrustedRouters.sol:37-52`) and passed to the ISP (`src/DicesHook.sol:350, 373`), where the parameter is unnamed and unused (`src/core/InternalSwapPool.sol:146, 226`). `hookData` is forwarded and never decoded (same lines). | Mitigated. The resolved identity currently has no effect (finding V4SF-05). |
| Router context | An owner-managed allowlist exists. It gates one thing: who may swap in a pool's launch block. | `src/core/TrustedRouters.sol:17-28`; `src/DicesHook.sol:334-336`. The deployment trusts the public Universal Router (`script/deployment/V001.s.sol:238`, asserted at `:516`). | Mechanism present, but the gate does not restrict users of the trusted router (finding V4SF-03). |
| State exposure | No secret or commit-reveal data is stored. State readable mid-transaction: `poolLevel`, `launchBlock`, `lastSwapBlock`, pool lookups (`src/DicesHook.sol:160-185`), ISP inventory (`src/core/InternalSwapPool.sol:95`), price history (`src/calculators/LiveCalculator.sol:114`), holder count (`src/DicesCoin.sol:168-175`). | `lastSwapBlock` is written in `beforeSwap` before any external call (`src/DicesHook.sol:339`). The holder count hides same-block joiners (`src/DicesCoin.sol:170-172`). Levels use a 24-hour tick average (`src/calculators/LiveCalculator.sol:309-338`). | Mitigated. The JIT range is placed from the spot price (`src/core/InternalSwapPool.sol:168`); see catalogue entry 7. |
| Reentrancy surface | Large. `beforeSwap` and `afterSwap` call the ISP, which calls back into the PM (`modifyLiquidity`, `sync`, `settle`, `take`), the coin, USDC, the fee calculator and the escrow. `afterSwap` also calls the Live calculator in a `try`, and a linked library by delegatecall. Neither the hook nor the ISP has a reentrancy guard; `FeeEscrow` has one (`src/core/FeeEscrow.sol:34, 80, 89`). | Call sites: `src/DicesHook.sol:350, 373, 436, 462, 473-481, 506, 519, 384`; `src/core/InternalSwapPool.sol:207, 239, 258, 262, 265-277`. No callee is chosen by the swapper: PM, ISP, escrow (fixed at construction, `src/DicesHook.sol:212-215`), calculators (owner-set, code-checked, `:819-838`), trusted routers (`staticcall` only), USDC, the hook's own coin clone (`_afterTokenTransfer` makes no external call, `src/DicesCoin.sol:195-224`). `FeeEscrow.deposit` never calls the beneficiary (`src/core/FeeEscrow.sol:34-73`). `Pool.swap` makes no external call (`v4-core/libraries/Pool.sol:279-463`), so nothing can run between the two callbacks of one swap. The PM allows one `unlock` at a time (`v4-core/PoolManager.sol:105`). | No exploitable path found. Trust boundary includes the owner-set calculators and routers. |

## 2. Permission matrix

`getHookPermissions()` is at `src/DicesHook.sol:236-243`. `HOOK_FLAGS` is at `script/deployment/V001.s.sol:120`. Flag bit values are at `v4-core/libraries/Hooks.sol:29-47`.

| Permission | Skill risk | `getHookPermissions()` | In `HOOK_FLAGS` | Justification found in the code |
| --- | --- | --- | --- | --- |
| `beforeInitialize` | LOW | enabled (`:237`) | yes | Rejects any pool initialisation not made by the hook (`src/DicesHook.sol:256-258`), so every pool carrying this hook was launched by `createCoin`. |
| `afterInitialize` | LOW | not enabled | no | n/a |
| `beforeAddLiquidity` | MEDIUM | enabled (`:238`) | yes | Only the hook and the ISP may add liquidity (`:291-293`). Third-party LPs are excluded by design: the hook is the only permanent LP. |
| `afterAddLiquidity` | LOW | not enabled | no | n/a |
| `beforeRemoveLiquidity` | HIGH | enabled (`:239`) | yes | Only the ISP may remove, and it can only remove positions it owns (`:303-305`; position owner is the PM caller, `v4-core/PoolManager.sol:161`). Test: `test/DicesHook.t.sol:386-402`. |
| `afterRemoveLiquidity` | LOW | not enabled | no | n/a |
| `beforeSwap` | HIGH | enabled (`:240`) | yes | Launch-block guard, `lastSwapBlock`, creation of the JIT position (`:334-350`). |
| `afterSwap` | MEDIUM | enabled (`:241`) | yes | Removal of the JIT position, fee collection, level sync, indexer events (`:373-385`). |
| `beforeDonate` | LOW | not enabled | no | n/a |
| `afterDonate` | LOW | not enabled | no | n/a |
| `beforeSwapReturnDelta` | CRITICAL | **not enabled** | no | n/a |
| `afterSwapReturnDelta` | HIGH | enabled (`:242`) | yes | Charges the trading fee on the unspecified currency (`:377, 471-473`). |
| `afterAddLiquidityReturnDelta` | HIGH | not enabled | no | n/a |
| `afterRemoveLiquidityReturnDelta` | HIGH | not enabled | no | n/a |

Cross-check. The six enabled flags are bits 13, 11, 9, 7, 6 and 2, which is `0x2AC4`; `HOOK_FLAGS` ORs the same six constants. The hook constructor validates the address against the permissions (`BaseHook.sol:18-20, 31-33`; `v4-core/libraries/Hooks.sol:83-103`). The script mines for an exact match on all 14 bits (`script/deployment/V001.s.sol:432`) and re-asserts it after deployment (`:511`). Tests: `test/scripts/V001.t.sol:361`, `test/DicesHook.t.sol:196-208`. The Base Sepolia address book in `deployments/deployment-84532.md` lists the hook at an address ending `...6Ac4`, whose low 14 bits are `0x2AC4`; that book has no bankroll row, so it appears to predate the current script.

`beforeSwapReturnDelta` is disabled and `_beforeSwap` returns `(IHooks.beforeSwap.selector, BeforeSwapDelta.wrap(0), 0)` (`src/DicesHook.sol:357`). Without the flag the PM does not parse a returned delta at all (`v4-core/libraries/Hooks.sol:266`), and the pool is not a dynamic-fee pool (`fee: 0`, `src/DicesHook.sol:564`), so the third return value is ignored (`v4-core/libraries/Hooks.sol:263`).

Callbacks skipped for the hook's own calls. `Hooks.noSelfCall` and the explicit self checks (`v4-core/libraries/Hooks.sol:171-175, 178, 195-200, 217, 253, 293`) skip every callback when the hook is the PM caller. Consequences in this hook:

- The hook's own `initialize` (`src/DicesHook.sol:598`) never reaches `_beforeInitialize`. A third-party `initialize` reverts at `:256-258`. The fee, tick-spacing and USDC checks at `:260-273` and the write at `:276` are therefore unreachable on a real launch (they are reached only by test pranks, `test/DicesHook.t.sol:234-257`). The launch block is recorded separately at `:601`. See V4SF-12.
- The hook's own `modifyLiquidity` (`:715`) never reaches `_beforeAddLiquidity`.
- `_beforeRemoveLiquidity` would not stop the hook itself. The lock on the launch positions rests on the hook containing no call with a negative `liquidityDelta`: the only `modifyLiquidity` call in `src/DicesHook.sol` is `:715`, with `int(uint(liquidity))`. A zero `liquidityDelta` from a third party routes to `beforeRemoveLiquidity` (`v4-core/libraries/Hooks.sol:203`) and reverts.
- A swap made by the hook would skip both swap callbacks. `src/` contains no `poolManager.swap` call.

## 3. Delta accounting trace

### 3.1 What the PoolManager does

- `swap` calls `beforeSwap`, runs `Pool.swap`, calls `afterSwap`, then accounts the hook's delta to the hook and `swapDelta - hookDelta` to the caller (`v4-core/PoolManager.sol:198-226`).
- The value returned from `afterSwap` is added to the unspecified-currency hook delta. It is placed in `amount1` when `amountSpecified < 0 == zeroForOne`, otherwise in `amount0`, and subtracted from the swapper's delta (`v4-core/libraries/Hooks.sol:295-313`). A positive return credits the hook and charges the swapper.
- `take` debits the caller's delta and transfers tokens out (`v4-core/PoolManager.sol:291-296`). `settle` credits `balance now - balance at the last sync` (`:349-364`). `sync` keeps one synced currency (`:279-288`).
- `modifyLiquidity` called from inside a swap callback is an ordinary call: the position owner is `msg.sender` (`:161`), the resulting delta is accounted to `msg.sender` (`:183`), and the `sender` passed to `beforeAddLiquidity`/`beforeRemoveLiquidity` is that same `msg.sender` (`v4-core/libraries/Hooks.sol:202, 204`). The enclosing swap's `sender` is unaffected: `afterSwap` receives the PM's `msg.sender` for the swap (`:300`). The price is not changed; active liquidity changes only if the range contains the current tick (`v4-core/libraries/Pool.sol:209-236`).
- `unlock` reverts unless every address's delta in every currency is zero at the end (`v4-core/PoolManager.sol:112`).

### 3.2 Fee currency and return delta, per swap mode

The fee currency is chosen by the same expression the PM uses for the unspecified currency:

```solidity
(fee.currency, unspecified) = params.amountSpecified < 0 == params.zeroForOne ? (key.currency1, delta.amount1()) : (key.currency0, delta.amount0());
uint amount = SafeCast.toUint256(unspecified < 0 ? -int(unspecified) : int(unspecified));
fee.amount = Math.mulDiv(amount, feeCalculator.getSwapFee(poolLive(key.toId())), FEE_DENOMINATOR);
```

(`src/DicesHook.sol:460-462`). The rate is 1,250 or 1,000 per 100,000 (`src/calculators/FeeCalculator.sol:33, 38, 72-74`), read before `_syncLevel` runs (`src/DicesHook.sol:375` then `:382`), so the swap that takes a pool Live pays the pre-Live rate. In the tables, D0 and D1 are the pool's swap deltas from the swapper's side and r is the rate.

Coin is currency0, USDC is currency1:

| Mode | `zeroForOne` | `amountSpecified` | Fee currency | Fee | Swapper's net |
| --- | --- | --- | --- | --- | --- |
| Buy, exact input (USDC in) | false | negative | currency0 = coin (output) | floor(D0 x r) | pays abs(D1) USDC, receives D0 - fee coin |
| Buy, exact output (coin out) | false | positive | currency1 = USDC (input) | floor(abs(D1) x r) | pays abs(D1) + fee USDC, receives D0 coin |
| Sell, exact input (coin in) | true | negative | currency1 = USDC (output) | floor(D1 x r) | pays abs(D0) coin, receives D1 - fee USDC |
| Sell, exact output (USDC out) | true | positive | currency0 = coin (input) | floor(abs(D0) x r) | pays abs(D0) + fee coin, receives D1 USDC |

USDC is currency0, coin is currency1 (mirror image):

| Mode | `zeroForOne` | `amountSpecified` | Fee currency | Fee | Swapper's net |
| --- | --- | --- | --- | --- | --- |
| Buy, exact input (USDC in) | true | negative | currency1 = coin (output) | floor(D1 x r) | pays abs(D0) USDC, receives D1 - fee coin |
| Buy, exact output (coin out) | true | positive | currency0 = USDC (input) | floor(abs(D0) x r) | pays abs(D0) + fee USDC, receives D1 coin |
| Sell, exact input (coin in) | false | negative | currency0 = USDC (output) | floor(D0 x r) | pays abs(D1) coin, receives D0 - fee USDC |
| Sell, exact output (USDC out) | false | positive | currency1 = coin (input) | floor(abs(D1) x r) | pays abs(D1) + fee coin, receives D0 USDC |

So the fee is in the coin for exact-input buys and exact-output sells, and in USDC for exact-output buys and exact-input sells. This is not the "all fees in USDC" model in `AGENT.md` section 3 and `README.md:10-13` (V4SF-11). Test for all eight cases: `test/DicesHookTrading.t.sol:90-117`.

How the return delta is computed and backed, identically in every mode (`src/DicesHook.sol:471-483`):

1. `hookDelta = SafeCast.toInt128(SafeCast.toInt256(fee.amount))` (`:472`).
2. `fee.currency.take(poolManager, address(this), fee.amount)` (`:473`): real tokens move PM to hook; the hook's delta in the fee currency becomes `-fee`.
3. `_afterSwap` returns `hookDelta` (`:377, 385`); the PM credits the hook `+fee` and charges the swapper (`v4-core/libraries/Hooks.sol:305-313`; `v4-core/PoolManager.sol:224-226`). Hook delta is zero again.

The returned delta and the `take` use the same `fee.amount`, so the delta is always backed one for one. When the fee rounds to zero nothing is taken and zero is returned (`:376`).

Where the taken tokens go:

- Fee in the coin: transferred hook to ISP and registered as inventory (`src/DicesHook.sol:474-476`; `src/core/InternalSwapPool.sol:127-138`). It is sold for USDC by a later buy (3.3).
- Fee in USDC: split by `feeCalculator.getFeeDistribution` into platform 40%, creator 30%, buy-and-burn 30% (`src/calculators/FeeCalculator.sol:85-94`) and deposited into `FeeEscrow` as pull credits for `feeRecipient`, `poolCreators[poolId]` and `buyAndBurnRecipient` (`src/DicesHook.sol:478-481, 731-741`). The escrow pulls with `transferFrom` and checks the amount received (`src/core/FeeEscrow.sol:59-67`).

The hook holds no ERC-6909 claims and keeps no USDC or fee coins after the call. The invariant suite asserts `usd.balanceOf(hook) == 0` and that the hook's coin balance stays at its launch dust (`test/DicesHookInvariant.t.sol:87-91`).

Two properties that could not be shown from the code alone:

- On exact-output swaps the fee currency is the swapper's input. The hook's `take` runs before the router has paid that input, so it is funded from whatever the PM already holds in that currency. For the coin this is the unsold launch liquidity. For USDC it is the PM's aggregate USDC balance (this pool's earlier buys plus every other pool). The same holds for the ISP's `take` of JIT proceeds on any buy (3.3). The test router pre-funds exact-output swaps for this reason (`test/utils/MsgSenderSwapRouter.sol:55-61, 82-84`; `README.md:81`). Whether the balance suffices is a property of the deployment environment, not of the code (V4SF-09).
- The fee rate is whatever the calculator returns. Nothing bounds it below `FEE_DENOMINATOR` (V4SF-01).

### 3.3 The just-in-time position

Created in `beforeSwap`, only for buys, in both exact modes and both orderings: the condition is `params.zeroForOne != launchedTokenIsCurrency0` and inventory of at least `1e6` raw units (`src/core/InternalSwapPool.sol:154-155, 90`).

What is added (`:163-212`):

- Range: one tick spacing wide, immediately on the coin's upside of the spot price. Coin is currency0: `tickLower` is the spacing multiple at or above the price, `tickUpper = tickLower + 60` (`:170-177`). Coin is currency1: `tickUpper` is the spacing multiple at or below the tick, `tickLower = tickUpper - 60` (`:178-186`). In both cases the range holds only the coin at the current price (`v4-core/libraries/Pool.sol:209-236`). Signed rounding is tested at `test/InternalSwapPool.t.sol:110-128`.
- Size: the liquidity that the whole inventory buys, capped at the remaining per-tick capacity (`:196, 314-347`).
- Call: `poolManager.modifyLiquidity(key, ModifyLiquidityParams(tickLower, tickUpper, +liquidity, JIT_LIQUIDITY_SALT), '')` (`:207`). The caller, position owner and delta holder are all the ISP. The hook's `beforeAddLiquidity` admits the ISP (`src/DicesHook.sol:291`).
- Effect on deltas: ISP owes the coin amount for the position (rounded up). Nothing is settled yet.
- Stored state: ticks, liquidity, ordering, the add delta and `removeJitLiquidity = true`, in ordinary storage, one slot pair for the whole contract, not keyed by pool (`:80, 212`).

What is removed in `afterSwap` (`:226-279`):

1. Return if the flag is not set (`:228-230`).
2. Copy the state to memory and `delete` it (`:233-234`).
3. `modifyLiquidity` with `-liquidity` on the same range and salt (`:239`). The hook's `beforeRemoveLiquidity` admits the ISP (`src/DicesHook.sol:303`). LP fee is zero, so no fees accrue to the position.
4. `net = withdrawn + state.liquidityDelta`; require coin leg `<= 0` and USDC leg `>= 0` (`:243-246`).
5. `spent = -coin leg`, `proceeds = USDC leg`; `internalSwapPool[coin] -= spent` (`:250-254`).
6. If `spent != 0`: `sync(coin)`, transfer coin ISP to PM, `settle()` (`:257-259`, through `lib/v4-hooks-public/lib/v4-core/test/utils/CurrencySettler.sol:27-33`). ISP's coin delta returns to zero.
7. If `proceeds != 0`: `take` USDC to the ISP (`:262`), split it with the ISP's own `feeCalculator.getFeeDistribution`, deposit three escrow credits (`:265-277`). ISP's USDC delta returns to zero.

Balance of the ISP's deltas: after the add the ISP holds `coin: -c_add`; after the remove `coin: -c_add + c_rem = -spent`, `USDC: +proceeds`; `settle(spent)` and `take(proceeds)` close both. `spent` and `proceeds` are read from the PM's own return values, so they equal the open deltas by construction. An untouched position costs at most the rounding difference between add (rounded up) and remove (rounded down).

`spent <= inventory`: for the uncapped case the liquidity is `getLiquidityForAmount0/1(inventory)` (`:326`; `v4-periphery/libraries/LiquidityAmounts.sol:18-44`), which rounds down, and the PM's rounded-up cost of that liquidity does not exceed the input amount; for the capped case the code returns the cap only when `inventory >= maxCost` (`:320-323`). The subtraction at `:254` is checked arithmetic, so a violation would revert the swap rather than corrupt the ledger. A fuzz test covers one tick range (`test/InternalSwapPool.t.sol:161-172`). This was reasoned, not executed.

Every early-return and failure path:

| Path | Delta left open | Stored state left set |
| --- | --- | --- |
| Not a buy, or inventory below `1e6` (`:155`) | none; no PM call | none; `closeInternalSwapPool` returns at `:228-230` |
| Active liquidity is zero (`:159-161`) | none | none |
| Range outside usable ticks (`:190-192`) | none | none |
| Sized liquidity is zero, or boundary ticks are full (`:200-202`) | none | none |
| `modifyLiquidity` (add) reverts | whole `PoolManager.swap` call reverts | reverted with it |
| `Pool.swap` reverts (for example a bad price limit) | whole swap call reverts, including the add | reverted with it |
| `closeInternalSwapPool` reverts (`require` at `:246`, underflow at `:254`, settle, take, escrow deposit) | whole swap call reverts | reverted with it; test `test/InternalSwapPool.t.sol:208-219` |
| Hook fee collection, `_swapFee` or an event helper reverts after the JIT is closed | whole swap call reverts | reverted with it |
| `liveCalculator.qualify` reverts | caught (`src/DicesHook.sol:436-448`); it touches no delta and no ISP state | none |
| Router catches the revert of `PoolManager.swap` | the reverted frame includes both callbacks | none |

Nested or reentrant swaps. A second `unlock` is impossible while one is open (`v4-core/PoolManager.sol:105`). Several swaps inside one `unlock` are sequential: for each, `beforeSwap`, `Pool.swap` and `afterSwap` run inside a single PM call, and `Pool.swap` makes no external call, so no other swap can observe the ISP's stored state between the two callbacks. Inside `beforeSwap` the only calls are a `staticcall` to a trusted router, PM views, and `modifyLiquidity` (which calls back only the hook's view-only `beforeAddLiquidity`). Inside `afterSwap`, the state is deleted before the first external call (`:234` before `:239`). Swaps by the hook itself skip both callbacks symmetrically and the hook never swaps. Conclusion by reading: no delta and no stored JIT state survives a swap, on any path.

One integration constraint follows from step 6 and from the hook's fee `take`: the hook `sync`s the coin and withdraws tokens inside `afterSwap`, which overwrites or disturbs a `sync` a router made before calling `swap`. Such a router ends with `CurrencyNotSettled`. This is documented in the code (`src/core/InternalSwapPool.sol:219-222`; `src/libraries/CurrencySettler.sol:20-22`). `V4Router` syncs at settlement time, after the swap (`v4-periphery/base/DeltaResolver.sol:38-47`), so it is compatible.

### 3.4 Launch

`createCoin` calls `poolManager.unlock` (`src/DicesHook.sol:577`). In `unlockCallback` the hook initialises the pool, adds two coin-only positions with positive liquidity (`:645-646` or `:652-653`, through `:715`), sums the actual debits returned by the PM (`:718`), and settles exactly that sum with `sync`, transfer, `settle` (`:614`; `src/libraries/CurrencySettler.sol:38-48`). Rounding dust stays in the hook as coins. Test: `test/DicesHook.t.sol:137-166` (`_debtFree(address(hook))` at `:161`).

## 4. Security checklist (13 points)

| # | Check | Result | Evidence |
| --- | --- | --- | --- |
| 1 | All hook callbacks verify `msg.sender == poolManager` | Pass | `BaseHook.sol:36-39, 62-67, 80-85, 144-147, 161-167`; `ImmutableState.sol:17-20`; `src/DicesHook.sol:587`; test `test/DicesHook.t.sol:259-275` |
| 2 | Router allowlisting implemented if needed | Pass, with a caveat | `src/core/TrustedRouters.sol:17-28`; used at `src/DicesHook.sol:334`. The allow-listed router is the public Universal Router (`script/deployment/V001.s.sol:238`), so the launch-block restriction does not bind its users (V4SF-03). |
| 3 | No unbounded loops that can cause OOG | Pass | Loops in callbacks: checkpoint catch-up, at most 25 iterations (`src/calculators/LiveCalculator.sol:283-287`); level searches, at most 10 each (`:360-362, 373-375`). None in the hook or the ISP. |
| 4 | Reentrancy guards on external calls | Partial | `FeeEscrow` is guarded (`src/core/FeeEscrow.sol:34, 80, 89`; test `test/FeeEscrow.t.sol:123`). The hook and ISP have no guard. No callee is attacker-chosen and no reentrant path was found (section 1). |
| 5 | Delta accounting sums to zero | Pass | Section 3. Enforced by the PM (`v4-core/PoolManager.sol:112`); asserted after every test trade (`test/DicesHookTrading.t.sol:74-77`) and as an invariant (`test/DicesHookInvariant.t.sol:110-114`). |
| 6 | Fee-on-transfer tokens handled | Not applicable | Pools only pair the hook's own `DicesCoin` clone with the immutable USDC (`src/DicesHook.sol:551, 561-564`); no third-party pool can be initialised (`:256-258`). The escrow rejects short receipts (`src/core/FeeEscrow.sol:60-67`; test `test/FeeEscrow.t.sol:98`). |
| 7 | No hardcoded addresses | Pass | No address literal in `src/` (searched for 40-hex literals). Addresses are constructor arguments or immutables (`src/DicesHook.sol:199-225`; `src/core/InternalSwapPool.sol:105-117`). Chain addresses are constants in the deployment script only (`script/deployment/V001.s.sol:103, 126-128, 140-142`). |
| 8 | Slippage parameters respected | Pass | The hook never changes `amountSpecified` or the price limit. The fee is part of the `swapDelta` the PM returns to the router (`v4-core/PoolManager.sol:221`; `v4-core/libraries/Hooks.sol:312`), so router bounds apply to the net amounts (`v4-periphery/V4Router.sol:93, 150`). Test: `test/DicesHookTrading.t.sol:189-201`. |
| 9 | No sensitive data stored on-chain | Pass | Storage reviewed: `src/DicesHook.sol:110-185`; `src/core/InternalSwapPool.sol:54-95`; `src/calculators/LiveCalculator.sol:99-120`. `CoinParams` is name, symbol, creator (`src/interfaces/IDicesHook.sol:24-37`). |
| 10 | Upgrade mechanisms secured (if applicable) | Partial | No proxy. Replaceable modules are `onlyOwner` (`src/DicesHook.sol:752, 761, 806`), but ownership is single-step with no on-chain timelock and the fee rate is uncapped (V4SF-01). |
| 11 | `beforeSwapReturnDelta` justified if enabled | Not applicable | Not enabled (`src/DicesHook.sol:236-243`). |
| 12 | Fuzz testing completed | Partial | `testFuzz_` tests exist, but `foundry.toml` has no `[fuzz]` section (default 256 runs) and most take only `bool coin0` (V4SF-06). |
| 13 | Invariant testing completed | Pass, with limits | Five invariants, 64 runs x depth 32, `fail_on_revert` (`foundry.toml:67-70`; `test/DicesHookInvariant.t.sol:83-118`). The handler trades one ordering, exact input only, through one trusted router, with no time movement (`:36-51, :67`) (V4SF-06). |

## 5. Pre-deployment audit checklist (12 sections)

### 1. Access control

| Item | Result | Evidence |
| --- | --- | --- |
| 1.1 All hook callbacks verify `msg.sender == address(poolManager)` | Pass | As 4.1 above. |
| 1.1 Verification uses modifier or explicit check at function start | Pass | `onlyPoolManager` modifier, `ImmutableState.sol:17-20`. |
| 1.1 No code paths bypass the verification | Pass | Callback logic is in `internal` functions reachable only from the guarded externals. Other state-changing entry points: `createCoin` (`src/DicesHook.sol:533`), `syncLevel` (`:408`, permissionless by design, runs only the level check), owner setters (`:752-852`). |
| 1.2 Router allowlisting implemented if hook restricts callers | Pass, with a caveat | `src/DicesHook.sol:334`; see V4SF-03. |
| 1.2 Allowlist modifications are admin-protected | Pass | `onlyOwner`, `src/core/TrustedRouters.sol:25`; test `test/TrustedRouters.t.sol:12`. |
| 1.2 Cannot add zero address to allowlist | Fail (harmless) | `src/core/TrustedRouters.sol:25-28` has no check; code quoted in V4SF-08. The PM never passes a zero `sender`. |
| 1.3 Admin role transfer is two-step or timelock-protected | Fail | OpenZeppelin `Ownable`, single-step (`src/core/TrustedRouters.sol:5, 13`; `src/DicesHook.sol:199`). Code quoted in V4SF-01. The Safe and 48-hour timelock in the brief are deferred (`AGENT.md` section 2). |
| 1.3 Critical admin functions have event emissions | Pass | `src/DicesHook.sol:774, 785, 797, 810, 823, 836`; `src/core/TrustedRouters.sol:27`; `Pausable` emits on pause and unpause. Test: `test/DicesHook.t.sol:297-323`. |
| 1.3 Admin cannot brick the contract | Fail | `renounceOwnership` is inherited unchanged (`lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/access/Ownable.sol:76`). The owner can also install a fee calculator that reverts or returns any rate, which stops every swap while liquidity is permanently locked (V4SF-01). |

### 2. Delta accounting

| Item | Result | Evidence |
| --- | --- | --- |
| 2.1 All returned deltas are backed by actual token movements | Pass | `src/DicesHook.sol:472-473`. |
| 2.1 `take()` calls match returned delta values | Pass | Same `fee.amount` at `:472` and `:473`. ISP `take` equals its own open delta (`src/core/InternalSwapPool.sol:251, 262`). |
| 2.1 `settle()` calls properly account for received tokens | Pass | Launch: `src/DicesHook.sol:614, 718`. ISP: `src/core/InternalSwapPool.sol:250, 258`. The PM measures the balance change itself (`v4-core/PoolManager.sol:358-360`). |
| 2.1 Invariant `sum(all deltas) == 0` for every transaction | Pass | Section 3; `v4-core/PoolManager.sol:112`; `test/DicesHookInvariant.t.sol:110-114`. |
| 2.2 Fee-on-transfer tokens handled | Not applicable | Closed token set (4.6). `_collectSwapFee` registers the nominal coin amount after transferring it (`src/DicesHook.sol:475-476`), which is exact for `DicesCoin`. |
| 2.2 Rebasing tokens handled or explicitly blocked | Not applicable | Closed token set. Escrow documents them as unsupported (`src/core/FeeEscrow.sol:17`). |
| 2.2 ERC-777 reentrancy considered | Not applicable | Neither token has transfer callbacks (`src/DicesCoin.sol:195-224`). USDC is an external dependency whose behaviour was not inspected. |
| 2.2 Token decimals not assumed (queried from token) | Pass | USDC decimals are queried and required to be 6 (`src/DicesHook.sol:201`; `script/deployment/V001.s.sol:345`). The coin is the project's own 18-decimal implementation; `1e27` supply constants depend on that (`src/DicesHook.sol:71`; `src/calculators/LiveCalculator.sol:94`). |
| 2.3 Correct order: `sync()` then `transfer()` then `settle()` | Pass | `src/libraries/CurrencySettler.sol:38-48`; `lib/v4-hooks-public/lib/v4-core/test/utils/CurrencySettler.sol:27-33`; test `test/Libraries.t.sol:46-70`. |
| 2.3 No partial settlements left hanging | Pass | Full `owed`, full `spent`, full `proceeds` (section 3). |
| 2.3 Error handling doesn't leave accounting in bad state | Pass | The only `try` wraps `qualify`, which touches no delta (`src/DicesHook.sol:436-448`). Everything else reverts the whole swap. Routers that `sync` before the swap are incompatible, as documented (section 3.3). |

### 3. Permissions review

3.1 is the table in section 2.

| Item | Result | Evidence |
| --- | --- | --- |
| 3.2 NoOp attack vector analyzed and mitigated | Pass (not applicable) | `beforeSwapReturnDelta` disabled; zero delta returned (`src/DicesHook.sol:357`); PM ignores it without the flag (`v4-core/libraries/Hooks.sol:266`). |
| 3.2 All code paths returning non-zero deltas reviewed | Pass | One path: `src/DicesHook.sol:376-377` into `:471-473`. |
| 3.2 Deltas are always backed by liquidity provision | Pass (as a fee) | The delta is a fee charge matched by a `take` of the same amount, not a claim to have filled the swap. |
| 3.2 Multiple independent reviewers have verified | Not determined | Process item. No sign-off record was found in the repository. |

### 4. Reentrancy protection

| Item | Result | Evidence |
| --- | --- | --- |
| 4.1 All external calls identified and documented | Pass (in this report) | Section 1 lists them; the repository has no such list. |
| 4.1 Reentrancy guards applied where needed | Pass | Escrow guarded. No untrusted callee in hook or ISP. |
| 4.1 State changes follow checks-effects-interactions | Partial | Followed in the ISP (`delete` at `:234` before `:239`; inventory at `:254` before `:258`) and for `lastSwapBlock` (`src/DicesHook.sol:339`). Not followed strictly in `_afterSwap` (`poolLevel` is written at `:439` after the ISP, token and escrow calls) or in `createCoin` (pool records at `:570-574` after calls to the clone at `:554-558`). Slither reports these (`reentrancy-eth`, `reentrancy-benign`, `reentrancy-events`). No callee is untrusted, so no exploit path was found. |
| 4.1 No callbacks to untrusted contracts | Pass | Section 1. |
| 4.2 ERC-777 `tokensReceived` hook considered | Not applicable | See 2.2. |
| 4.2 ERC-721/1155 callbacks considered if applicable | Not applicable | None used. |
| 4.2 Flash loan callbacks considered | Pass | v4 flash accounting is addressed for the holder count (`src/DicesCoin.sol:162-175`; test `test/DicesCoin.t.sol:97`) and for levels (24-hour average, `src/calculators/LiveCalculator.sol:309-338`). |

### 5. Gas and DoS

| Item | Result | Evidence |
| --- | --- | --- |
| 5.1 All loops have maximum iteration limits | Pass | `src/calculators/LiveCalculator.sol:283-287` (25), `:360-362, 373-375` (10). `FeeEscrow.claimBatch` loops over the caller's own array outside any callback (`src/core/FeeEscrow.sol:91-93`). |
| 5.1 Limits are appropriate for block gas limit | Pass | Worst measured callback 397,604 gas (section 7). |
| 5.1 User-controllable arrays bounded | Not applicable | None inside callbacks. |
| 5.2 Gas usage tested for worst-case scenarios | Partial | Costs are documented from traces (`AGENT.md` section 3; section 7 here). No gas test or snapshot file is in the repository. |
| 5.2 No operations that could exceed block gas limit | Pass | As 5.1. |
| 5.2 External call gas limits are reasonable | Not applicable | No call sets a gas limit (searched for `{gas:`). |
| 5.3 No unbounded array iterations | Pass | As 5.1. |
| 5.3 No unbounded mapping iterations | Pass | None. |
| 5.3 Failed external calls don't block hook functionality | Fail | Only `qualify` is isolated (`src/DicesHook.sol:436-448`; test `test/DicesHookLive.t.sol:352-365`). A revert in `feeCalculator.getSwapFee`/`getFeeDistribution` (`:462, 478`; ISP `:265`) or `feeEscrow.deposit` (`:736-739`; ISP `:292-295`) reverts the swap. Reachable today through a zero creator (V4SF-02) and through the owner (V4SF-01); code quoted there. |
| 5.3 Griefing attacks considered | Partial | Launch-block guard (V4SF-03), same-block holder exclusion, zero-liquidity guard for the JIT (`src/core/InternalSwapPool.sol:156-161`). Not addressed: V4SF-02, V4SF-10. |

### 6. Input validation

| Item | Result | Evidence |
| --- | --- | --- |
| 6.1 All external inputs validated | Fail | `createCoin` stores `params.creator` unchecked (`src/DicesHook.sol:574`; V4SF-02). `setTrustedRouter` and the constructor's `_buyAndBurnRecipient` have no zero check (V4SF-08). |
| 6.1 hookData properly decoded and validated | Pass (not applicable) | Never decoded (`src/DicesHook.sol:350, 373`; `src/core/InternalSwapPool.sol:146, 226`). |
| 6.1 No assumptions about parameter ranges | Fail | The calculator's rate is assumed to be below `FEE_DENOMINATOR` and is not checked (`src/DicesHook.sol:462`; V4SF-01). |
| 6.1 Overflow/underflow protection | Pass | Solidity 0.8.38 checked arithmetic; `SafeCast` at `src/DicesHook.sol:461, 472, 493, 718` and `src/core/InternalSwapPool.sol:250-251`. Narrowing casts in `LiveCalculator` are bounded and commented (`:271, 326, 337, 400`). |
| 6.2 Hook is authorized for the pool | Pass | Only the hook can initialise a pool with itself attached (`src/DicesHook.sol:256-258, 598`). Swap callbacks do not re-check `poolCoins[poolId]`; given the first point they do not need to. |
| 6.2 Currency addresses validated | Pass | The key is built by the hook from its own clone and the immutable USDC (`:561-564`). |
| 6.2 Fee tier validated if relevant | Pass | `fee: 0` is set by the hook (`:564`). |

### 7. State management

| Item | Result | Evidence |
| --- | --- | --- |
| 7.1 No sensitive data stored on-chain | Pass | As 4.9. |
| 7.1 Storage slots don't collide (if using assembly) | Not applicable | No assembly in `src/`. |
| 7.1 Transient storage used appropriately | Fail (gas only) | None is used. The JIT state that lives only between `beforeSwap` and `afterSwap` is written to and cleared from ordinary storage (`src/core/InternalSwapPool.sol:80, 212, 234`); quoted in V4SF-05. Functionally safe. |
| 7.1 Storage variables initialized correctly | Pass | Constructor sets all references (`src/DicesHook.sol:199-225`). `coinImplementation` is set after deployment (`script/deployment/V001.s.sol:237`); until then `createCoin` reverts when it reads `bankroll()` from a clone with no implementation (`src/DicesHook.sol:558`), by reading. |
| 7.2 All state transitions have valid preconditions | Pass | Level only rises (`src/DicesHook.sol:437-439`); JIT flag set only after a successful add (`src/core/InternalSwapPool.sol:207-212`). |
| 7.2 No invalid intermediate states possible | Pass | Section 3.3. |
| 7.2 State can be recovered from errors | Partial | Calculators are replaceable. `internalSwapPool`, `feeEscrow` and a pool's `poolCreators` entry have no setter (`src/DicesHook.sol:125, 145, 170`), so a pool launched with a zero creator cannot be repaired (V4SF-02). |

### 8. Upgrade safety

The hook is not a proxy. The items are answered for the owner-replaceable modules (`setFeeCalculator`, `setLiveCalculator`, `setCoinImplementation`).

| Item | Result | Evidence |
| --- | --- | --- |
| 8.1 Upgrade mechanism is access-controlled | Pass | `onlyOwner` (`src/DicesHook.sol:752, 761, 806`); test `test/DicesHook.t.sol:325-342`. |
| 8.1 Timelock or governance required for upgrades | Fail | No on-chain delay; replacement takes effect in the same transaction for every pool (V4SF-01). |
| 8.1 Storage layout documented | Not applicable | No proxy. |
| 8.1 Upgrade path tested | Pass | `test/CalculatorUpdates.t.sol:19, 31, 49`; `test/DicesHookLive.t.sol:256, 289`. |
| 8.2 Old state can be migrated to new implementation | Partial | Levels stay in the hook; a new Live calculator restarts each pool's 24 hours of history (`src/calculators/LiveCalculator.sol:37-39`). The ISP keeps its own immutable fee calculator (V4SF-04). |
| 8.2 No loss of funds during migration | Pass | Calculators hold no funds (`src/calculators/FeeCalculator.sol`, `LiveCalculator.sol`: no token or value handling). |
| 8.2 Rollback plan exists | Not determined | None found in `README.md` or `AGENT.md`. |

### 9. Testing requirements

| Item | Result | Evidence |
| --- | --- | --- |
| 9.1 Every public/external function tested | Pass | CI gate requires 100% function coverage of `src/` (`.github/workflows/test.yml:37-44`; `test/check_coverage.py:45-48`). Measured today: 127 tests pass. Not re-run here. |
| 9.1 Every require/revert condition tested | Pass | The same gate requires 100% branch coverage (`test/check_coverage.py:47`). Not re-run here. |
| 9.1 Edge cases tested | Partial | Dust, extreme ticks, tick capacity, signed rounding and zero fees are tested (`test/InternalSwapPool.t.sol:98-159`; `test/DicesHookTrading.t.sol:119, 164`). Not tested: zero creator (V4SF-02); an exact-output buy without pre-funding against an empty PM (V4SF-09). |
| 9.1 All code paths covered | Not determined | Coverage is by line, function and branch; path combinations (for example exact-output buy with an active JIT in the currency1 ordering) were not enumerated. |
| 9.2 Foundry fuzz tests for all state-changing functions | Partial | Present for escrow deposits, ISP sizing, coin transfers and calculators. Swap amounts are fuzzed only inside the invariant handler. Most `testFuzz_` functions take only `bool coin0`. |
| 9.2 Minimum 10,000 fuzz runs | Fail | `foundry.toml` has no `[fuzz]` section, so the Foundry default of 256 applies. |
| 9.2 Custom fuzz invariants defined | Pass | `test/DicesHookInvariant.t.sol:83-118`. |
| 9.2 No failures in extended fuzzing | Not determined | No extended campaign has been run; Echidna, Medusa and Halmos are not installed. |
| 9.3 Core invariants defined and tested | Pass | Escrow solvency, inventory equals balance, launch positions unchanged, zero debts, supply conserved. |
| 9.3 Delta accounting invariants tested | Pass | `:110-114`. |
| 9.3 Balance invariants tested | Pass | `:83-91, 115-117`. |
| 9.3 Access control invariants tested | Fail | The handler exposes only `buy`, `sell`, `claim` (`:36-51, 75-79`). Access control is covered by unit tests only (`test/DicesHook.t.sol:259, 325`). |
| 9.4 Fork tests against mainnet state | Fail | No `createSelectFork`/`createFork` in `test/` or `script/`. `test/scripts/GenerateActivity.t.sol` can optionally be run with `--fork-url base_sepolia` (`README.md:146-148`); CI runs without a fork (`.github/workflows/test.yml:35`). |
| 9.4 Tests with real pool addresses | Fail | None. |
| 9.4 Tests with various token types | Not applicable | Closed token set. A taxed token is used to test escrow rejection (`test/utils/Fixtures.sol:38-52`). |
| 9.4 End-to-end swap flow tested | Pass | Real PM artifact, all four modes, both orderings (`test/DicesHookTrading.t.sol:90-117`; `test/scripts/GenerateActivity.t.sol`). |

### 10. Static analysis

| Item | Result | Evidence |
| --- | --- | --- |
| 10.1 Slither analysis completed (all findings addressed) | Fail | Slither 0.11.5 ran; 95 raw results are untriaged (`audits/2026-11-25-skills-review/slither/slither-detectors.txt`). It could not generate IR for `DicesHook._swapFee`, `DicesHook._addInitialTokenLiquidity` and `InternalSwapPool.closeInternalSwapPool`, which are the delta-critical functions. |
| 10.1 Mythril analysis completed | Fail | Not installed, not run. |
| 10.1 Solhint linting passed | Not determined | No Solhint configuration in the repository. The code carries `forge-lint` directives, but CI does not run a lint step (`.github/workflows/test.yml`). |
| 10.1 Custom detectors for v4-specific issues | Fail | None found. |
| 10.2 Line-by-line code review completed | Partial | Done by this reviewer for the files in scope. No independent sign-off is recorded. |
| 10.2 Business logic reviewed against specification | Fail | The written specification no longer matches the code (V4SF-11). `AGENT.md` says so for four of its sections. |
| 10.2 Comparison with similar audited hooks | Not determined | No comparison document found. |

### 11. Documentation

| Item | Result | Evidence |
| --- | --- | --- |
| 11.1 NatSpec comments for all public functions | Pass | Present throughout `src/DicesHook.sol`, `src/core/*.sol`, `src/calculators/*.sol`, `src/interfaces/IDicesHook.sol`. |
| 11.1 Complex logic explained in comments | Pass | For example `src/core/InternalSwapPool.sol:156-158, 194-199, 219-222`; `src/calculators/LiveCalculator.sol:20-39`. The comment at `src/DicesHook.sol:328` does not match the code (V4SF-03). |
| 11.1 Assumptions documented | Pass | Router sync ordering; "the hook must never swap" (`src/DicesHook.sol:422-425`). |
| 11.2 Architecture diagram | Not determined | Tables in `AGENT.md`; no diagram found other than a generated inheritance graph. |
| 11.2 Threat model document | Fail | None found. Section 1 of this report is a start. |
| 11.2 Deployment procedure | Pass | `script/deployment/V001.s.sol:28-101`; `README.md:101-118`. |
| 11.2 Emergency procedures | Fail | None found. `pause` stops `createCoin` only (`src/DicesHook.sol:533, 843-852`); swaps cannot be paused. |

### 12. Deployment preparation

| Item | Result | Evidence |
| --- | --- | --- |
| 12.1 Hook address mined with correct permission bits | Pass | `script/deployment/V001.s.sol:120, 418-437, 511`; `BaseHook.sol:18-20`; test `test/scripts/V001.t.sol:361`. |
| 12.1 Constructor parameters verified | Pass | `_requireWiring`, `script/deployment/V001.s.sol:510-532`. It does not compare the ISP's `feeCalculator` with the hook's (V4SF-04). |
| 12.1 Deployment script reviewed and tested | Pass (tested) | `test/scripts/V001.t.sol` (19 tests, including `:59`, `:112`, `:293`). Review status not determined. |
| 12.1 Gas estimation for deployment | Not determined | Not measured. Runtime size is 23,077 bytes, 1,499 under the EIP-170 limit. |
| 12.2 Verify source code on block explorer | Not determined | Procedure is described (`script/deployment/V001.s.sol:98-100`); no network access to check the Sepolia deployment. |
| 12.2 Verify permissions match expected | Pass (script) | Asserted after deployment (`:511`). |
| 12.2 Test transaction on mainnet | Not done | Mainnet destinations are unset placeholders (`:131-134`) and the script refuses to run without them (`:323-325`). |
| 12.2 Monitoring and alerting configured | Not determined | Nothing found in the repository. |

### Audit sign-off

| Role | Name | Date | Signature |
| --- | --- | --- | --- |
| Lead Auditor | | | |
| Security Reviewer | | | |
| Code Owner | | | |

### Risk assessment summary

| Category | Risk level | Notes |
| --- | --- | --- |
| Access Control | Medium | Callbacks and helpers are correctly gated. The owner is a single-step `Ownable` with no on-chain timelock and controls an uncapped fee rate, the level logic and the fee recipients (V4SF-01). |
| Delta Accounting | Low to Medium | Balanced on every path by reading and by the tests. The design is complex (liquidity added and removed by a helper inside swap callbacks) and depends on routers syncing after the swap. Slither could not analyse the functions involved. |
| Reentrancy | Low | No untrusted callee inside callbacks; escrow is guarded and pull-based. |
| DoS | Medium | Unisolated dependencies in the swap path; zero-creator pools (V4SF-02); callback gas well above the skill's ceilings (V4SF-05). Liquidity can never be withdrawn, so a pool that cannot be traded is a permanent loss for holders. |
| Upgrade Safety | Medium | No proxy. Module replacement is instant and global. |
| **Overall** | **Medium to High** | Professional audit required before mainnet (section 9). |

## 6. Vulnerability catalogue

| # | Entry | Applies | Evidence |
| --- | --- | --- | --- |
| 1 | NoOp rug pull | Does not apply | `beforeSwapReturnDelta` is disabled (`src/DicesHook.sol:236-243`); `_beforeSwap` returns a zero delta (`:357`). |
| 2 | Missing PoolManager verification | Does not apply | `onlyPoolManager` on every external callback and on `unlockCallback` (section 4, item 1). |
| 3 | Delta accounting mismatch | Does not apply | The catalogue's pattern is a `take` without a matching returned delta. Here both use `fee.amount` (`src/DicesHook.sol:472-473`); the ISP closes its own deltas (section 3.3). |
| 4 | Reentrancy via external calls | Applies in limited form | Many external calls in both swap callbacks and no guard on the hook or ISP. No callee is attacker-chosen, and state is not left half-written for an untrusted party to observe. Residual risk sits with the owner-set calculators and routers. |
| 5 | Unbounded loop DoS | Does not apply | Loops bounded at 25 and 10 (`src/calculators/LiveCalculator.sol:283-287, 360-375`). |
| 6 | Liquidity lock | Applies by design | `_beforeRemoveLiquidity` reverts for everyone but the ISP (`src/DicesHook.sol:302-307`). No third party can add liquidity (`:291-293`), so no user LP funds can be trapped; the launch liquidity is meant to be permanent. Donations to a pool would accrue to the hook's positions and could never be collected. |
| 7 | Price manipulation via single block | Applies in limited form | Levels use a 24-hour tick average in which only the last tick of a block carries weight, plus a holder count that ignores same-block joiners (`src/calculators/LiveCalculator.sol:266-338`; `src/DicesCoin.sol:168-175`). The JIT range is placed from the spot `slot0` (`src/core/InternalSwapPool.sol:168`). It always sits at or above the spot coin price, so it is not sold at a discount to spot; depressing spot first costs fees both ways, and the amount exposed is the queued fee inventory only. The zero-liquidity case is guarded (`:159-161`). No finding raised. |
| 8 | Missing slippage protection | Does not apply | The hook does not modify the specified amount; the fee reaches the router in the returned delta (section 4, item 8). |
| 9 | Fee-on-transfer token mismatch | Does not apply | Closed token set; escrow checks received amounts (`src/core/FeeEscrow.sol:60-67`). |
| 10 | Hardcoded addresses | Does not apply | None in `src/`. |
| 11 | Missing event emissions | Applies in part | Every setter emits. A launch emits only `PoolCreated(poolId, coin, usdc)` (`src/DicesHook.sol:604`); the creator is not in any launch event, and there is no `CoinCreated` event as `AGENT.md` describes (V4SF-11). |
| 12 | Unchecked return values | Applies in part | The ISP settles through v4-core's test `CurrencySettler`, which ignores the boolean returned by `transfer` (V4SF-07). Elsewhere `SafeERC20` and `Currency.transfer` are used (`src/libraries/CurrencySettler.sol:41-43`; `src/core/FeeEscrow.sol:61, 116`). |

## 7. Gas budget

Measured from `forge test -vvvv` traces of `test/DicesHookTrading.t.sol` and `test/DicesHookLive.t.sol` (test environment, cold storage access included; figures supplied with the task, not re-measured).

| Callback | Skill target | Skill hard ceiling | Measured | Against the budget |
| --- | --- | --- | --- | --- |
| `beforeSwap` (n=37) | under 50,000 | 150,000 | min 6,069; median 44,558; p95 185,997; max 202,036 | Median within target. p95 and max exceed the ceiling. |
| `afterSwap` (n=36) | under 30,000 | 100,000 | min 82,696; median 210,011; p95 368,921; max 397,604 | Minimum exceeds the target. Median exceeds the ceiling. |
| Same two, judged as "callbacks with external calls" | under 100,000 | 300,000 | as above | `beforeSwap` stays under 300,000. `afterSwap` p95 and max exceed it. |
| `beforeAddLiquidity`, `beforeRemoveLiquidity` | under 50,000 | 200,000 | not measured separately | Each is one storage read and a comparison (`src/DicesHook.sol:289-307`); they run only inside the JIT calls and are included in the figures above. |
| `beforeInitialize` | none stated | none stated | never completes | See section 2. |

Components inside the callbacks: `createInternalSwapPool` max 181,617 (inside `beforeSwap`); `closeInternalSwapPool` max 302,291 and `LiveCalculator.qualify` median 25,925, max 206,856 (inside `afterSwap`). Outside callbacks: `createCoin` about 689,000; `syncLevel` 28,274 to 265,924.

What drives the worst cases:

- `beforeSwap`: the JIT add. `modifyLiquidity` initialises two ticks, flips two bitmap bits and writes a position in the PM, and the ISP writes two fresh storage slots for the cross-callback state (`src/core/InternalSwapPool.sol:207, 212`).
- `afterSwap`: the JIT removal and settlement (`modifyLiquidity`, `sync`, coin transfer, `settle`, `take`), then up to three escrow deposits for the proceeds, each with an approval, a `transferFrom`, two `balanceOf` calls and a ledger write (`src/core/FeeEscrow.sol:59-71`); then the hook's own fee: either two coin transfers (PM to hook, hook to ISP) or up to three more escrow deposits; then `qualify`, which writes up to 25 hourly checkpoints after a quiet day (`src/calculators/LiveCalculator.sol:283-287`); then three library delegatecalls that emit events and read the PM twice.
- Even the cheapest `afterSwap` (no JIT) is 82,696 because the fee path, `qualify` and three events always run.

Avoidable costs are listed in V4SF-05. `syncLevel` lets anyone pay the checkpoint catch-up outside a swap.

## 8. Absolute prohibitions

| # | Prohibition | Result | Evidence |
| --- | --- | --- | --- |
| 1 | Never trust `msg.sender` for user identity | Respected | In callbacks `msg.sender` is only compared with the PM. `sender` is used as the router (`src/DicesHook.sol:334`). `onlyOwner` and `onlyHook` checks are on non-callback entry points. |
| 2 | Never enable `beforeSwapReturnDelta` without understanding NoOp attacks | Respected | Not enabled. |
| 3 | Never store passwords, keys, or PII on-chain | Respected | Section 4, item 9. |
| 4 | Never use `transfer()` for ETH | Respected | ETH moves by `deposit{value: ...}` (`src/DicesHook.sol:736`) and `SafeTransferLib.safeTransferETH` (`src/core/FeeEscrow.sol:114`). Every `.transfer(` in `src/` is the `Currency` library on an ERC-20 (`src/DicesHook.sol:475, 558`; `src/libraries/CurrencySettler.sol:43`). |
| 5 | Never assume token decimals | Respected | USDC decimals are queried and enforced (`src/DicesHook.sol:201`). The coin's 18 decimals are the project's own implementation. |
| 6 | Never use `block.timestamp` for randomness | Respected | Used only for the price history (`src/calculators/LiveCalculator.sol:271-289, 310-327`). Slither's two `weak-prng` hits are the hour-index modulo and the rounding check at `:322, 331`. |
| 7 | Never hardcode gas limits in calls | Respected | No `{gas:` in `src/`. |
| 8 | Never ignore return values from external calls | Partly breached | `lib/v4-hooks-public/lib/v4-core/test/utils/CurrencySettler.sol:31`, used by the ISP at `src/core/InternalSwapPool.sol:258`, ignores the ERC-20 `transfer` boolean (V4SF-07). Other ignored returns are benign: `unlock` and `initialize` results (`src/DicesHook.sol:577, 598`), the amount returned by `settle` (`src/libraries/CurrencySettler.sol:34, 48`). |
| 9 | Never use `tx.origin` for authorization | Respected | Not present in `src/`. |

## 9. Risk score

| Category | Range | Score | Basis |
| --- | --- | --- | --- |
| Permissions | 0-14 | 6 | Six enabled permissions, one point each: `beforeInitialize`, `beforeAddLiquidity`, `beforeRemoveLiquidity`, `beforeSwap`, `afterSwap`, `afterSwapReturnDelta`. |
| External calls | 0-5 | 5 | Both swap callbacks make many external calls: PM `modifyLiquidity`, `sync`, `settle`, `take`; a helper contract; an escrow; two replaceable calculators (one in a `try`); two tokens; a router `staticcall`; a linked library. |
| State complexity | 0-5 | 4 | Six per-pool mappings and owner configuration in the hook; per-token inventory and a cross-callback stored struct in the ISP; a per-pool oracle with 25 checkpoints; a holder counter in the coin; an escrow ledger. |
| Upgrade mechanism | 0-5 | 3 | No proxy. Fee logic, level logic, coin implementation, routers and recipients are owner-replaceable at once, with single-step ownership and no on-chain timelock or cap. |
| Token handling | 0-4 | 1 | Closed token set: USDC (blocklist, pause and upgrade risk, 6 decimals enforced) and the project's own fixed-supply ERC-20. |
| **Total** | 0-33 | **19** | 6 + 5 + 4 + 3 + 1 |

Tier: **High (13-20): professional audit required.** In the checklist's terms this is Tier 3: the Tier 2 requirements (external developer review, extended fuzzing) plus an audit by a security firm and a bug bounty.

Sensitivity. The skill defines the permissions category as "sum of enabled permission risk levels" with a range of 0-14 but gives no numeric value per level. One point per enabled flag is the only weighting whose maximum is 14 across the 14 flags, so it is used above. If the levels are weighted LOW 1, MEDIUM 2, HIGH 3, CRITICAL 4 and capped at 14, this hook scores 1 + 2 + 3 + 3 + 2 + 3 = 14 for permissions and 27 in total, which is the Critical tier (multiple audits). At 19 the score is also one point below Critical under the flat reading. Given liquidity operations inside swap callbacks and permanently locked user value, the upper end of the High tier should be assumed.

## 10. Findings log

Severity reflects what was shown by reading the code. Nothing here was reproduced by execution.

| ID | Severity | Description | Status | Resolution |
| --- | --- | --- | --- | --- |
| V4SF-01 | Medium | Owner can set any fee rate or halt all swaps; no cap, timelock or two-step ownership on-chain | Open | |
| V4SF-02 | Low | `createCoin` accepts a zero `creator`, after which swaps that credit the creator revert | Open | |
| V4SF-03 | Low | Launch-block guard exempts every user of the trusted Universal Router | Open | |
| V4SF-04 | Low | ISP's fee calculator is immutable while the hook's is replaceable | Open | |
| V4SF-05 | Low | Callback gas exceeds the skill's hard ceilings; several avoidable costs | Open | |
| V4SF-06 | Low | Fuzz, invariant, fork and static-analysis coverage is below the skill's requirements | Open | |
| V4SF-07 | Informational | Production ISP uses v4-core's test `CurrencySettler`, which ignores the `transfer` return value | Open | |
| V4SF-08 | Informational | Admin input hygiene: zero router, unchecked constructor recipient, open `renounceOwnership` | Open | |
| V4SF-09 | Informational | Fee and JIT `take`s run before the swapper settles and depend on the PM's existing balance | Open | |
| V4SF-10 | Informational | The price can be moved at no cost below the launch range | Open | |
| V4SF-11 | Informational | `README.md` and `AGENT.md` describe a fee and ledger model the code does not implement | Open | |
| V4SF-12 | Informational | `_beforeInitialize` validation is unreachable on real launches; the liquidity lock depends on the hook never gaining a removal call | Open | |

### V4SF-01 (Medium): no on-chain bound on the fee rate or on the owner

`src/DicesHook.sol:462` and `:752-754`:

```solidity
fee.amount = Math.mulDiv(amount, feeCalculator.getSwapFee(poolLive(key.toId())), FEE_DENOMINATOR);
```

```solidity
function setFeeCalculator(address _calculator) external onlyOwner {
    _setFeeCalculator(_calculator);
}
```

`_setFeeCalculator` checks only that the address has code (`:819-825`). The rate is not compared with any maximum, the change applies to every pool in the same transaction, and the call is not isolated the way `qualify` is, so a calculator that reverts stops every swap. Ownership is OpenZeppelin `Ownable` (`src/core/TrustedRouters.sol:13`, `abstract contract TrustedRouters is Ownable, ITrustedRouters`): one-step transfer, `renounceOwnership` available. The owner can also redirect `feeRecipient` and `buyAndBurnRecipient` (`:770-799`) and replace the level logic (`:761`). Because launch liquidity can never be removed, a halted pool is permanent for holders. A rate at or above 100% leaves exact-input swappers with nothing unless their router's minimum-output check reverts the trade. The brief asks for a 48-hour timelock and on-chain caps; `AGENT.md` records the timelock as deferred. Suggested: a hard maximum rate in the hook, two-step ownership, and the timelock before mainnet.

### V4SF-02 (Low): zero creator bricks most trading in that pool

`src/DicesHook.sol:574` stores the creator without a check:

```solidity
poolCreators[poolId] = params.creator;
```

Fees in USDC are credited through `_creditFee(poolCreators[poolId], ...)` (`:480`; ISP `src/core/InternalSwapPool.sol:274`), which calls `FeeEscrow.deposit`, which begins (`src/core/FeeEscrow.sol:36-38`):

```solidity
if (_beneficiary == address(0)) {
    revert InvalidBeneficiary();
}
```

With the default 30% creator share, any swap whose USDC fee or JIT proceeds are 4 raw units or more reverts in such a pool: exact-output buys, exact-input sells, and any buy that trades into the JIT range once coin fees are queued. Exact-input buys work until inventory exists, and exact-output sells keep working (their fee is in the coin and no JIT is created on sells). There is no setter for `poolCreators`. Impact is limited to a coin whose launcher passed a zero creator: early buyers can exit only by exact-output sells. No test launches with a zero creator. Suggested: revert in `createCoin` when `params.creator == address(0)`.

### V4SF-03 (Low): launch-block guard does not restrict the public router

`src/DicesHook.sol:328-336`:

```solidity
 * Prevent 0-block buys: Prevents bots from buying in the same block as launch, unless token creator.
...
if (launchBlock[poolId] == block.number && !trustedRouters[sender]) {
    revert CannotBuyZeroBlock();
}
```

`sender` is the router, and the deployment trusts the Universal Router (`script/deployment/V001.s.sol:238`: `hook.setTrustedRouter(cfg.universalRouter, true);`, enforced at `:516`). Anyone can therefore buy in the launch block through that router. The code has no creator check, contrary to the comment. The allowlist carries two meanings (may be asked for `msgSender()`, may trade in the launch block) that probably should be separate. Suggested: decide whether same-block buys are to be prevented; if so, key the exemption on the resolved swapper or a dedicated launch router.

### V4SF-04 (Low): two fee calculators can diverge

`src/core/InternalSwapPool.sol:75` and `:265`:

```solidity
IFeeCalculator public immutable feeCalculator;
...
(uint platform, uint creator, uint buyAndBurn) = feeCalculator.getFeeDistribution(proceeds, dicesHook.poolLive(poolId));
```

The hook's calculator is replaceable (`src/DicesHook.sol:752`) and the hook's `internalSwapPool` has no setter (`:125`). After `setFeeCalculator`, fees charged in USDC follow the new distribution while fees charged in the coin and converted by the JIT keep the original one. `_requireWiring` does not compare the two (`script/deployment/V001.s.sol:523-524`). Suggested: have the ISP read `dicesHook.feeCalculator()`.

### V4SF-05 (Low): callback gas above the skill's ceilings

Figures in section 7. Costs that the code could avoid:

- The swapper is resolved twice per swap and never used. `src/DicesHook.sol:350` and `:373` pass `_getSender(sender)`; the ISP declares the parameter unnamed (`src/core/InternalSwapPool.sol:146`: `function createInternalSwapPool(address, PoolKey calldata key, SwapParams calldata params, bytes calldata) public override onlyHook`). Each resolution is a storage read and a `staticcall` to the router.
- The cross-callback JIT state is held in ordinary storage (`src/core/InternalSwapPool.sol:80`: `InternalSwapPoolState internal _internalSwapPoolState;`, written at `:212`, deleted at `:234`). The compiler target is Osaka, so transient storage is available.
- Coin fees are moved twice, PM to hook then hook to ISP (`src/DicesHook.sol:473-475`), where one `take` to the ISP would do.
- USDC is taken to the hook or ISP and then pulled by the escrow in up to three separate deposits, each with its own approval and two balance reads; an exact-output buy with an active JIT makes six.
- `MINIMUM_INTERNAL_SWAP_POOL_SIZE = 1e6` (`src/core/InternalSwapPool.sol:90`) is 1e-12 of an 18-decimal coin, so the "worth interacting with" test (`:152-153`) passes for inventory of no economic value. Once any coin fee is queued, a later buy pays for a JIT add and remove however little the inventory is worth (reasoned from the constant, not measured).

### V4SF-06 (Low): testing and tooling gaps against the skill

- No `[fuzz]` section in `foundry.toml`; the skill asks for at least 10,000 runs. Most fuzz tests have a single boolean input, for example `function testFuzz_queuedTokenFeesConvertToFundedEscrowCredits(bool coin0)` (`test/DicesHookTrading.t.sol:173`).
- The invariant handler covers one currency ordering (`_prepare(true)`, `test/DicesHookInvariant.t.sol:67`), exact-input swaps only (`:38, :44`), one trusted router, no `vm.warp`/`vm.roll`, no `syncLevel`, one pool. Exact-output swaps, the currency1 ordering, levels and the launch block are outside it.
- No fork test runs by default; none targets mainnet.
- Slither results are untriaged and Slither failed on the three functions that carry the delta logic. Mythril, Echidna, Medusa and Halmos have not been run.

### V4SF-07 (Informational): test utility in production code

`src/core/InternalSwapPool.sol:9`:

```solidity
import {CurrencySettler} from '@uniswap/v4-core/test/utils/CurrencySettler.sol';
```

That library transfers with `IERC20Minimal(Currency.unwrap(currency)).transfer(address(manager), amount);` (`lib/v4-hooks-public/lib/v4-core/test/utils/CurrencySettler.sol:31`) and ignores the returned boolean. With `DicesCoin` a failed transfer reverts, and the PM credits only the measured balance change, so an underpayment would fail the unlock rather than pass silently. The repository already has a hardened equivalent in `src/libraries/CurrencySettler.sol`, which the hook uses.

### V4SF-08 (Informational): admin input hygiene

- `src/core/TrustedRouters.sol:25-28` accepts the zero address:

```solidity
function setTrustedRouter(address _swapRouter, bool _trusted) public override onlyOwner {
    trustedRouters[_swapRouter] = _trusted;
    emit TrustedRouterSet(_swapRouter, _trusted);
}
```

- The constructor assigns `buyAndBurnRecipient = _buyAndBurnRecipient;` without the zero check that the setter has (`src/DicesHook.sol:218` against `:771-773`). A zero value would make every USDC-fee swap revert in the escrow, as in V4SF-02. The deployment script requires a non-zero value (`script/deployment/V001.s.sol:324`).
- `renounceOwnership` is not disabled. Renouncing while paused would end coin creation for good; renouncing at any time removes the ability to replace a faulty calculator.
- `setCreateFee` has no upper bound (`src/DicesHook.sol:783-786`).

### V4SF-09 (Informational): withdrawals precede the swapper's payment

On exact-output buys the hook takes its USDC fee (`src/DicesHook.sol:473`), and on any buy with an active JIT the ISP takes USDC proceeds (`src/core/InternalSwapPool.sol:262`), before the router has paid USDC in. Both rely on the PM already holding that much USDC. The repository's own test router pre-funds for this reason ("Prefund a bounded exact-output input so hooks can take input-currency fees during callbacks.", `test/utils/MsgSenderSwapRouter.sol:55`). The stand-in Universal Router in `test/scripts/GenerateActivity.t.sol:103-123` settles after the swap without pre-funding, and its exact-output buy follows two exact-input buys, so the PM already holds USDC there. On a PM with too little USDC (a fresh test network, first trade is an exact-output buy) the swap reverts in the token transfer. On a busy PM it works. Related, documented constraint: routers must `sync` after the swap, not before (section 3.3).

### V4SF-10 (Informational): free price movement below the launch range

Both launch positions are coin-only and start above the launch price, so active liquidity is zero at launch (`test/DicesHook.t.sol:160`: `assertEq(manager.getLiquidity(id), 0, ...)`) and again whenever the pool holds no USDC. With zero liquidity a swap moves the price to its limit while consuming nothing (`v4-core/libraries/Pool.sol:344-368`); the ISP's own comment describes this (`src/core/InternalSwapPool.sol:156-158`). Anyone can therefore push the price to the tick limit after launch, without owning coins and without paying a fee. Effects found: the next buyer pays extra gas to walk the tick bitmap back to the launch tick; `PoolStateUpdated` and the price history record an extreme low tick, which can only lower a level; the JIT is correctly skipped. The upside has no such gap (the upper position reaches the usable tick limit, `src/DicesHook.sol:646, 653`). Not executed.

### V4SF-11 (Informational): documentation does not match the code

`README.md:10-13` and `AGENT.md` section 3 state that every fee is charged in USDC, accrues as ERC-6909 claims, is withdrawn with `claimFees()`, and includes a 0.50% buy surcharge to a reserve and later a race pool controlled by a `reserveController`; `AGENT.md` also describes a `CoinCreated` event, a `gameCommitment`, a per-pool `PoolConfig` snapshot and `beforeRemoveLiquidity` rejecting everyone. None of these exists in `src/` (searched). The code charges one rate on the unspecified currency, splits 40/30/30, pays through `FeeEscrow`, lets the ISP remove its own liquidity, and applies calculator changes to existing pools. `AGENT.md` flags four of its subsections as stale; `README.md` does not. Integrators and reviewers working from the documents would model the system incorrectly.

### V4SF-12 (Informational): guards that do not run where they appear to

Described in section 2. The checks at `src/DicesHook.sol:260-276` cannot execute during a successful initialisation, and `_beforeRemoveLiquidity` cannot stop the hook itself. The current code is safe because the hook builds its own pool key and has no removal call, but both facts are conventions, not enforced guards. Worth a comment at the call sites and a test that fails if a negative `liquidityDelta` ever appears in the hook.

## Not determined

- Whether the PM on Base mainnet always holds enough USDC for V4SF-09 (no network access; expected to be true).
- Whether the deployed Universal Router completes an exact-output buy against this hook on Base Sepolia (the optional fork run of `test/scripts/GenerateActivity.t.sol` was not executed).
- Gas of `beforeAddLiquidity` and `beforeRemoveLiquidity` on their own.
- Whether a swapper can starve `qualify` of gas so that the `catch` at `src/DicesHook.sol:448` skips a price observation while the swap still succeeds. By arithmetic on the 63/64 rule it would need `qualify` to cost about 63 times the gas the hook still needs afterwards. That tail is two library calls with their events and two PM reads, estimated here at about 7,000 gas, which puts the threshold near 440,000 against a measured `qualify` maximum of 206,856. The estimate was not measured and the scenario was not tested.
- That `spent` never exceeds the ISP inventory for every tick range and amount (reasoned in section 3.3; fuzzed for one range only).
- Triage of the 95 Slither results; any result from Mythril, Echidna, Medusa or Halmos.
- Process items: independent reviewer sign-off, rollback plan, monitoring, block-explorer verification, deployment gas, mainnet test transaction.

---

## Reconciliation with the consolidated findings

Added by the lead reviewer after this report was written. The report above was produced from the code alone,
without sight of the other reviews. Its findings were then checked and merged into [`findings.md`](findings.md)
under `DICES-nn` identifiers; severities there take precedence where they differ. "Run" means a
proof-of-concept test was executed (see [`poc-tests.md`](poc-tests.md)).

| This report | Consolidated | Status after verification |
| --- | --- | --- |
| V4SF-01 | DICES-03, DICES-04 | Confirmed; run (`testPoC4`, `testPoC10`) |
| V4SF-02 | DICES-01 | Confirmed; run for both orderings (`testPoC1`). Rated Medium in the consolidated list: the pool is permanently unrepairable and anyone can create one |
| V4SF-03 | DICES-06 | Confirmed; run (`testPoC2`) |
| V4SF-04 | DICES-08 | Confirmed; run (`testPoC5`) |
| V4SF-05 | DICES-10 | Confirmed from the trace measurements |
| V4SF-06 | DICES-20 | Confirmed |
| V4SF-07 | DICES-11 | Confirmed |
| V4SF-08 | DICES-01 (constructor recipient, `testPoC12`), DICES-04, DICES-22 | Confirmed |
| V4SF-09 | DICES-19 | Confirmed; run (`testPoC11`) |
| V4SF-10 | DICES-21 | Confirmed |
| V4SF-11 | DICES-09, DICES-17 | Confirmed |
| V4SF-12 | DICES-16 | Confirmed |

Items this report left open, now settled:

- **Starving `qualify` of gas.** Tested: no gas limit lets a swap succeed without recording an observation
  (rejected candidate R-01, `testPoC6`).
- **Conversion cost never exceeds inventory.** Proven from the liquidity formulas (rejected candidate R-07).

Findings in the consolidated list that this report does not contain: DICES-02 (levels 9 and 10 are
unreachable), DICES-05 (fee conversion at a price any caller can push down, rated Medium) and DICES-07
(malformed calculator return). Section 3.3 above traces the conversion position's deltas and finds them
balanced, which is correct: DICES-05 is about the price the position is placed at, not its accounting.
