# Audit report

> Audit src/peg/PegHook.sol, src/earn/PegLPVault.sol, src/earn/PegCollateral.sol, src/earn/PegPositionZap.sol, src/earn/PegShareFeed.sol, at the pinned commit, for a capped mainnet beta. Read whatever else in src/ these depend on, but report on this scope.
>
> imdUSD v2 is a multi-collateral CDP stablecoin; this is its capped mainnet beta on Ethereum. Positions are NFT ids; borrowers set their own interest rate and redemptions take from the lowest rates first; liquidation is mark then bite, with a standing bid from Backstop sleeves; the peg pool is a Uniswap v4 pool with our own hook; prices come from Chainlink and from swarm-attested feeds (EIP-712 attestations bound to pinned questions). README.md gives the scope, the key invariants, the trust model and the known issues: read it first.
>
> BUILD AND TEST (required; Foundry, solc 0.8.26 via_ir per foundry.toml). Never build or test the whole project: with every suite it needs about 49 GB and the compiler will be killed. Run only this panel's tests: `forge test --match-path 'test/unit/{PegHook,PegLPVault,PegLPVaultReview,PegPositions,PegCollateral,PanelPeg}.t.sol'` (measured: about 3.9 GB peak, 10 minutes). One build at a time on your machine. Write each proof as a new file test/unit/Proof<Name>.t.sol, add it to the glob and run it; paste it with its output into the finding, then delete it: your submission must leave the tree unchanged. With Foundry 1.9 or later, `forge test --use solar --no-match-path 'test/fork/*'` builds everything and runs all 1,179 tests in seconds under 1 GB (Solar accepts a little syntax solc refuses: confirm a proof with the solc command).
>
> Answer each numbered question, including the ones where nothing is wrong:
> 1. TOLL (beforeSwap and afterSwap; 0.01% base fee, free within 0.25%, 1.5% at 1% off, 5% rising to 20% at 2% below, a flat 1.5% above $1, nothing toward $1; ERC-6909 claims and sweep). Avoid the toll, be overcharged, or take claims that are not yours; check exact-in and exact-out in both token orders.
> 2. TWAP (the observation ring, 30 minutes, quoteSound). Move the TWAP to trigger the keeper or open the LP vault's entry gate.
> 3. KEEPER (provide, withdraw, keeperCap, outstanding, the buffer and its buy below peg, _settleProfit). Make the keeper lose protocol money or leave imdUSD minted without backing.
> 4. PEG LP VAULT (deposit, withdraw, compound, DEAD shares, the 100-tick range, the entry gate). Share inflation, a sandwiched deposit, or a drain.
> 5. PEG POSITIONS (PegCollateral wrap, PegShareFeed and its spot leg, PegPositionZap open and unwind with the flash mint). Borrow more than the shares are worth, or misuse the zap's approvals and rights.
>
> Not findings: anything listed under README.md 'Known issues and accepted risks' (say so if you find it worse than written); src/bridge, src/dex, src/earn/LoopVault.sol and src/stocks (after the beta) unless a question names them; test/ and its mocks; gas optimisations unless they change behaviour.
>
> For every finding: severity by impact; file, line and the lines copied; the call sequence from an external caller; a concrete failing input or state with expected against actual; whether it is reachable with the values in script/DeployConfig.sol (BetaConfig); the smallest fix; and a Foundry test that fails on this commit, RUN as BUILD says and pasted in full in the finding with its output (the judge reruns it). The test/ tree has harnesses to reuse (test/utils/System.sol, the unit suites). Answer every numbered question, including those where nothing is wrong. Give a coverage row (holds, finding or unreached, with a reason) for every external function of the contracts in scope. Also report every comment or NatSpec that claims a property the code does not have.

| | |
|---|---|
| Repository | https://github.com/fa11up/imdusd-v2-audit.git |
| Commit | `2875ffb22a726f041bd6891f32f35ddc7cdb983d` |
| Job | `561e7d5b-d64f-4233-9443-9761bd51546c` |
| Judged | 2026-11-10 21:11 UTC |
| Findings | 4 low · 1 info |

Four agents audited the code as it is at `2875ffb`, each in one area (math, permissions, economics, control flow),
and a judge reproduced, merged and ranked what they found, then read the code once more itself. Nothing in the repository was changed or deployed.

## Findings

### 1. Low: PegHook TWAP: one 12-second block at an unbounded tick past the LP band moves the >=30-minute mean past TRIGGER_TICKS and locks PegLPVault deposits/compound (and every zap open) for ~30 minutes; NatSp

`src/peg/PegHook.sol:282`

```
            tickCumulative += int56(lastTick) * int56(uint56(dt));
```

_observe credits the tick that prevailed since the last update with no bound on the tick, and twapTicks() (L296-310) is the plain arithmetic mean since the newest checkpoint >= TWAP_WINDOW old. In the beta the only liquidity is PegLPVault's band (pegTick +-100, BetaConfig lpVault.band = 100). A swap whose price limit is beyond the band buys the band's imdUSD and then moves the tick through empty ticks to the limit at no further cost; the toll above $1 is flat 1.5% (SOFT_CAP) of what was actually traded. Holding +10,000 ticks for one 12 s block adds 120,000 tick-seconds, i.e. +67 ticks to the mean read 10 minutes later (TRIGGER_TICKS = 25, PegLPVault.MAX_SPOT_TWAP_TICKS = 10). Consequences: (1) PegLPVault.deposit and compound revert OffTwap(spot 0, twap 67) at $1 until the 12 pushed seconds leave the window (~30 min), and so does PegPositionZap.open (it calls compound and deposit); one push buys a 30-minute lock, versus the README's accepted per-block ($5/block) griefing, at a cost of ~1.5% of the band's imdUSD (1,646 imdUSD on a ~$100k-a-side band in the test). (2) Once keeperCap > 0 (0 at genesis in BetaConfig, so only after a governed raise), provide() becomes callable without any sustained price above $1.0025; it still sells only above $1.0005, so no protocol loss was found and principal coverage holds (_assertKeeperSolvent passes in the test before the assertion). Symmetrically withdraw()'s buffer buy can be triggered by a downward one-block push (costlier: the below-peg toll is up to 20%). No loss of funds; it is a premature-trigger / griefing primitive and the NatSpec at L79-81 ('holding a price for the window costs the arbitrage') and PegLPVault's MANIPULATION note assume a hold the code does not require. Merged from audit_math c5e7e9 (rated medium; downgraded: no funds at risk, griefing cost of the same order as the accepted known issue) and audit_flow 9bfdbb.

**Reproduction**

State: pool at $1, liquidity 2e19 in pegTick+-100 only (the beta band), 31 min of history; PegLPVault(band 100) seeded with 10k+10k; keeperCap 200k. Block N: router exact-in buy of imdUSD with sqrtPriceLimit at +10,000 stable ticks (spotTicks()==10000, 1,646 imdUSD of toll claims). Block N+1 (+12 s): sell back to $1 (toward the peg, free). +600 s at $1. Expected per NatSpec: twapTicks() <= 25 and vault.deposit accepted. Actual: twapTicks()==67, vault.deposit reverts OffTwap(0,67) (selector 0x45ac3353). Second test: same push, then spot set to +8 for 12 s: expected provide() reverts TwapInBand; actual it mints 3,299 imdUSD. Run: forge test --match-path 'test/scratch/*.t.sol' -vv (forge 1.8.3, solc 0.8.26 via_ir, 3.5 min build). Both files reuse the harness test/utils/PegSystem.sol (local v4 PoolManager, real PegHook/PegLPVault); no fork, no ffi.
OUTPUT:
[FAIL: a price held for one block moved the TWAP past the keeper trigger: 67 > 25] test_twapOneBlockPush() (gas: 1227875)
Logs:
  toll claims (imdUSD) paid for the push: 1646
  spot 0
  twap after one 12 s block at +10000 ticks, then 600 s at $1: 67
  vault.deposit at $1 succeeded: false
  0x45ac3353...0000...0043
[FAIL: provide() reachable from a one-block push] test_twapOneBlockTriggersProvide() (gas: 1342153)
Logs:
  twap 67
  keeper minted on a one-block push (imdUSD): 3299
Smallest fix: clamp the tick credited in _observe to pegTick +- a bound (e.g. CAP_AT_BPS = 200 ticks, or the LP band), so one block can move the mean by at most ~1.3 ticks; and reword L79-81.

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {PoolManager} from "v4-core/src/PoolManager.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {SwapParams, ModifyLiquidityParams} from "v4-core/src/types/PoolOperation.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";
import {PegSystem} from "../utils/PegSystem.sol";
import {MockERC20} from "../utils/Mocks.sol";
import {PegHook} from "../../src/peg/PegHook.sol";
import {PegLPVault, IPegHookView} from "../../src/earn/PegLPVault.sol";
import {console2} from "forge-std/console2.sol";

/// Review reproductions on the PegSystem harness (local v4 PoolManager), beta band of 100 ticks.
contract ProofReview is PegSystem {
    using StateLibrary for IPoolManager;

    PegLPVault vault;

    function setUp() public {
        vm.warp(1_800_000_000);
        pm = IPoolManager(address(new PoolManager(address(this))));
        usdc = IERC20(address(new MockERC20("USDC", 6)));
        _deploySystem(IERC20(address(new MockERC20("imdUSDv1", 18))));
        params.seal();
        _openPeg(200_000e18);
        _fund(address(router), 50_000_000e18, 50_000_000e6);
        int24 t = hook.pegTick();
        // Only the beta vault's band holds liquidity (+-100 ticks), ~ $100k a side.
        router.addLiquidity(key, ModifyLiquidityParams(t - 100, t + 100, 2e19, 0));
        _hold(0, 31 minutes);
        vault = new PegLPVault(pm, IPegHookView(address(hook)), address(treasury), 100);
        _fund(address(this), 1_000_000e18, 1_000_000e6);
        usd.approve(address(vault), type(uint256).max);
        usdc.approve(address(vault), type(uint256).max);
        (uint256 a0, uint256 a1) = hook.stableIsToken0() ? (uint256(10_000e18), uint256(10_000e6)) : (uint256(10_000e6), uint256(10_000e18));
        vault.deposit(0, a0, a1, address(this));
    }

    function _swapTo(int24 ticks) internal returns (BalanceDelta d) {
        int24 t = hook.pegTick();
        uint160 limit = TickMath.getSqrtPriceAtTick(hook.stableIsToken0() ? t + ticks : t - ticks);
        (uint160 now_,,,) = pm.getSlot0(key.toId());
        d = router.swap(key, SwapParams(limit < now_, -int256(1e30), limit));
    }

    function _quoteClaims() internal view returns (uint256) {
        Currency q = hook.stableIsToken0() ? key.currency1 : key.currency0;
        return pm.balanceOf(address(hook), q.toId());
    }

    function _stableClaims() internal view returns (uint256) {
        Currency s = hook.stableIsToken0() ? key.currency0 : key.currency1;
        return pm.balanceOf(address(hook), s.toId());
    }

    /// One block (12 s) past the band moves the >=30-minute TWAP past TRIGGER_TICKS and shuts the vault's gate.
    function test_twapOneBlockPush() public {
        assertLe(hook.twapTicks(), 1);
        _swapTo(10_000); // buy all the band's imdUSD; the empty ticks beyond cost nothing
        assertEq(hook.spotTicks(), 10_000);
        console2.log("toll claims (imdUSD) paid for the push:", _stableClaims() / 1e18);
        vm.warp(block.timestamp + 12);
        vm.roll(block.number + 1);
        _swapTo(0); // back to $1 (toward the peg: free)
        vm.warp(block.timestamp + 600);
        vm.roll(block.number + 50);
        int24 twap = hook.twapTicks();
        console2.log("spot", hook.spotTicks());
        console2.log("twap after one 12 s block at +10000 ticks, then 600 s at $1:", twap);
        (uint256 a0, uint256 a1) = hook.stableIsToken0() ? (uint256(1_000e18), uint256(1_000e6)) : (uint256(1_000e6), uint256(1_000e18));
        (bool ok, bytes memory err) =
            address(vault).call(abi.encodeCall(PegLPVault.deposit, (1e15, a0, a1, address(this))));
        console2.log("vault.deposit at $1 succeeded:", ok);
        if (!ok) console2.logBytes(err);
        assertLe(twap, hook.TRIGGER_TICKS(), "a price held for one block moved the TWAP past the keeper trigger");
    }

    /// The same one-block push makes provide() callable at a spot of +8 ticks.
    function test_twapOneBlockTriggersProvide() public {
        _swapTo(10_000);
        vm.warp(block.timestamp + 12);
        vm.roll(block.number + 1);
        _swapTo(8);
        vm.warp(block.timestamp + 12);
        vm.roll(block.number + 1);
        console2.log("twap", hook.twapTicks());
        try hook.provide() returns (uint256 minted) {
            console2.log("keeper minted on a one-block push (imdUSD):", minted / 1e18);
            _assertKeeperSolvent();
            assertTrue(false, "provide() reachable from a one-block push");
        } catch {}
    }

    /// Exact-in and exact-out pay different rates for the same end price (20% leg: 1/(1-t) vs 1+t).
    function test_exactOutCheaperThanExactIn() public {
        _swapTo(-250); // past -2% (beyond the band, empty ticks)
        // add liquidity at the current price so small swaps stay at ~-2.5%
        int24 t = hook.pegTick();
        int24 c = hook.stableIsToken0() ? t - 250 : t + 250;
        router.addLiquidity(key, ModifyLiquidityParams(c - 50, c + 50, 1e22, 0));
        bool sellStable = hook.stableIsToken0();
        uint256 snap = vm.snapshotState();
        // exact-in: sell 1000 imdUSD
        BalanceDelta d = router.swap(key, SwapParams(sellStable, -int256(1000e18), sellStable ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1));
        uint256 got = uint256(int256(hook.stableIsToken0() ? d.amount1() : d.amount0()));
        vm.revertToState(snap);
        // exact-out: receive the same USDC
        d = router.swap(key, SwapParams(sellStable, int256(got), sellStable ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1));
        uint256 paid = uint256(int256(-(hook.stableIsToken0() ? d.amount0() : d.amount1())));
        console2.log("exact-in: 1000 imdUSD -> USDC (6dp)", got);
        console2.log("exact-out: same USDC costs imdUSD (1e15)", paid / 1e15);
        assertApproxEqRel(paid, 1000e18, 0.005e18, "same trade, same end price, same toll");
    }
}
```

### 2. Low: PegHook toll is priced from each swap's END price on its whole amount: splitting a push from $1 to -2% into many swaps pays about a third of the documented 5%-20% wall

`src/peg/PegHook.sol:263`

```
        uint256 pips = surchargeFor(sqrtPriceX96, p.zeroForOne);
```

afterSwap reads the post-swap price and applies one rate to the swap's entire unspecified amount (L263-269). The toll therefore depends on where each swap ends, not on the path; a pusher chooses how much of the sale is charged at each rate by splitting. Selling 201,013 imdUSD from $1 to -2% in one swap pays 39,194 USDC (20% of output); the same sale as 200 one-tick swaps ending at the same price pays 12,859 USDC (the curve's average). Splitting costs only gas (or one multicall). The header (L42-44) and README present the wall as 'a step to 5% ... rising to 20% at -2%', and L68 says 'what a pusher pays becomes the bid against him': both the deterrent and the buffer funding are ~3x smaller against any pusher who splits. No protocol funds are taken. Reachable with BetaConfig (the toll constants are hard-coded). Merged from audit_economics 2d4eee and audit_permissions 1f74fa (same mechanism).

**Reproduction**

State: PegSystem pool at $1, 2e19 liquidity over +-1000 ticks, 31 min history. A: one exact-in sale of imdUSD with limit at -200 stable ticks. B (same snapshot): 200 exact-in sales with limits -1, -2, ..., -200. Both sell 201,013 imdUSD and end at spotTicks()==-200. Expected: comparable toll. Actual: A 39,194.99 USDC, B 12,859.51 USDC. Run: forge test --match-path 'test/scratch/*.t.sol' -vv (forge 1.8.3, solc 0.8.26 via_ir, 3.5 min build). Both files reuse the harness test/utils/PegSystem.sol (local v4 PoolManager, real PegHook/PegLPVault); no fork, no ffi. Both token orders.
OUTPUT:
[FAIL: split push pays at least half of the single push's toll: 25719017268 < 39194990795] test_split_vs_single() (gas: 31946317)  [ProofTollQuoteLow]
[FAIL: split push pays at least half of the single push's toll: 25719017268 < 39194990795] test_split_vs_single() (gas: 31710504)  [ProofTollQuoteHigh]
Logs: single: stable sold 201013 toll USDC 39194 / split x200: stable sold 201013 toll USDC 12859
Smallest fix: price the toll over the path: record the pre-swap sqrt price (a beforeSwap hook; flags and mined address change) and charge the integral of surchargeFor between start and end (closed form for the piecewise-linear curve), or charge the end rate only on the part of the amount traded beyond the band; otherwise document that the wall binds a single swap only.

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {PoolManager} from "v4-core/src/PoolManager.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {SwapParams} from "v4-core/src/types/PoolOperation.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";
import {PegSystem} from "../utils/PegSystem.sol";
import {console2} from "forge-std/console2.sol";

abstract contract ProofTollTest is PegSystem {
    using StateLibrary for IPoolManager;

    function _quoteAddr() internal pure virtual returns (address);

    function setUp() public {
        vm.warp(1_800_000_000);
        deployCodeTo("Mocks.sol:MockERC20", abi.encode("USDC", uint8(6)), _quoteAddr());
        _deployPeg(IPoolManager(address(new PoolManager(address(this)))), IERC20(_quoteAddr()), 0);
        _hold(0, 31 minutes);
    }

    function _quoteCurrency() internal view returns (Currency) {
        return hook.stableIsToken0() ? key.currency1 : key.currency0;
    }

    function _claims() internal view returns (uint256) {
        return pm.balanceOf(address(hook), _quoteCurrency().toId());
    }

    /// Sell the stable (exact in, huge) until the stable's price is `ticks` from the peg. Returns USDC received.
    function _sellTo(int24 ticks) internal returns (uint256 quoteOut, uint256 stableIn) {
        int24 t = hook.pegTick();
        uint160 limit = TickMath.getSqrtPriceAtTick(hook.stableIsToken0() ? t + ticks : t - ticks);
        BalanceDelta d = router.swap(key, SwapParams(hook.stableIsToken0(), -int256(1e30), limit));
        (int128 s, int128 q) = hook.stableIsToken0() ? (d.amount0(), d.amount1()) : (d.amount1(), d.amount0());
        stableIn = uint256(int256(-s));
        quoteOut = uint256(int256(q));
    }

    /// One push from $1 to -2%: the whole sale is tolled at 20%.
    function test_split_vs_single() public {
        uint256 snap = vm.snapshotState();
        (uint256 outSingle, uint256 inSingle) = _sellTo(-200);
        uint256 tollSingle = _claims();
        console2.log("single: stable sold", inSingle / 1e18, "toll USDC", tollSingle / 1e6);
        vm.revertToState(snap);

        uint256 totalIn;
        for (int24 k = 1; k <= 200; ++k) {
            (, uint256 i) = _sellTo(-k);
            totalIn += i;
        }
        uint256 tollSplit = _claims();
        console2.log("split x200: stable sold", totalIn / 1e18, "toll USDC", tollSplit / 1e6);
        assertEq(hook.spotTicks(), -200);
        assertApproxEqRel(totalIn, inSingle, 0.001e18, "same push");
        // The wall is documented as 5% rising to 20% past -1%; a pusher in 200 steps pays far less than the end rate.
        assertGe(tollSplit * 2, tollSingle, "split push pays at least half of the single push's toll");
    }

    /// A sale that starts at +1.5% (bought up, held 30 min) and ends at -0.5%: 2% of the move is toward $1,
    /// 0.25% is away, yet the whole output is tolled at the end-price rate.
    function test_overshoot_charged_on_whole_amount() public {
        _hold(150, 31 minutes);
        assertEq(hook.spotTicks(), 150);
        uint256 snap = vm.snapshotState();
        uint256 before = _claims();
        (uint256 out, uint256 inAmt) = _sellTo(-50);
        uint256 toll = _claims() - before;
        console2.log("overshoot: sold", inAmt / 1e18, "received USDC", out / 1e6);
        console2.log("toll USDC", toll / 1e6, "pips of output", toll * 1e6 / (out + toll));
        vm.revertToState(snap);
        // The same trade in two swaps: +1.5% -> -0.25% (toward $1 and inside the band: free), then -0.25% -> -0.5%.
        _sellTo(-25);
        uint256 awayBefore = _claims();
        (uint256 awayOut,) = _sellTo(-50);
        uint256 awayToll = _claims() - awayBefore;
        assertEq(hook.spotTicks(), -50);
        console2.log("away leg alone: output USDC", awayOut / 1e6, "toll USDC", awayToll / 1e6);
        // "Swaps toward $1 pay nothing extra": the one-swap toll should equal what the away leg alone pays.
        assertLe(toll, awayToll * 11 / 10, "a swap toward $1 pays nothing extra on the part that moved toward it");
    }
}

contract ProofTollQuoteLow is ProofTollTest {
    function _quoteAddr() internal pure override returns (address) {
        return address(0x1111111111111111111111111111111111111111);
    }
}

contract ProofTollQuoteHigh is ProofTollTest {
    function _quoteAddr() internal pure override returns (address) {
        return address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF);
    }
}
```

### 3. Low: PegHook toll: a swap that moves toward $1 and ends just past the band on the other side is tolled at the end rate on its WHOLE amount (8x what the away leg alone pays), contradicting 'Swaps toward $1

`src/peg/PegHook.sol:574`

```
        bool away = below ? sellsStable : !sellsStable;
```

surchargeFor decides 'away' from the end price only (L567-584) and afterSwap applies the rate to the swap's whole unspecified amount. A sale that starts at +1.5% and ends at -0.5% spends almost all of its size bringing the price back to $1, yet pays the -0.5% rate (0.4968%) on all of its output: 996 USDC on 199,495 USDC, while the same trade split at the band (+150 -> -25 free, -25 -> -50) pays 123 USDC. The mirror case (a buy from -1.5% to +0.5%) is likewise tolled on all of it. Who pays: arbitrageurs, liquidation/Backstop routes and any router that restores a depegged pool and overshoots the band; a sophisticated trader avoids it by splitting. Contradicts NatSpec L44 ('Swaps toward $1 pay nothing extra') and the rationale at L578-579. Reachable with BetaConfig. Merged from audit_flow 8dd1c0, audit_economics afff76 and audit_permissions a2e039 (info, same root cause).

**Reproduction**

State: PegSystem pool, _hold(150, 31 minutes) (spot +150). Input: router.swap(zeroForOne = stableIsToken0, amountSpecified = -1e30, limit = sqrt at -50 stable ticks). Expected: toll ~= away leg alone (123 USDC; test allows +10%: 136,384,908). Actual: 996,243,140 (996 USDC) minted as ERC-6909 claims to the hook. Run: forge test --match-path 'test/scratch/*.t.sol' -vv (forge 1.8.3, solc 0.8.26 via_ir, 3.5 min build). Both files reuse the harness test/utils/PegSystem.sol (local v4 PoolManager, real PegHook/PegLPVault); no fork, no ffi. Both token orders.
OUTPUT:
[FAIL: a swap toward $1 pays nothing extra on the part that moved toward it: 996243140 > 136384908] test_overshoot_charged_on_whole_amount() (gas: 6006842) [QuoteLow] / (gas: 10880102) [QuoteHigh]
Logs: overshoot: sold 199511 received USDC 199495 / toll USDC 996 pips of output 4968 / away leg alone: output USDC 24827 toll USDC 123
Smallest fix: when start and end prices are on opposite sides of the peg, charge only the part of the amount traded beyond the band edge (SqrtPriceMath between the band-edge sqrt price and the end price at the pool's liquidity), which needs the start price from a beforeSwap; or at minimum reword L44.

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {PoolManager} from "v4-core/src/PoolManager.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {SwapParams} from "v4-core/src/types/PoolOperation.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";
import {PegSystem} from "../utils/PegSystem.sol";
import {console2} from "forge-std/console2.sol";

abstract contract ProofTollTest is PegSystem {
    using StateLibrary for IPoolManager;

    function _quoteAddr() internal pure virtual returns (address);

    function setUp() public {
        vm.warp(1_800_000_000);
        deployCodeTo("Mocks.sol:MockERC20", abi.encode("USDC", uint8(6)), _quoteAddr());
        _deployPeg(IPoolManager(address(new PoolManager(address(this)))), IERC20(_quoteAddr()), 0);
        _hold(0, 31 minutes);
    }

    function _quoteCurrency() internal view returns (Currency) {
        return hook.stableIsToken0() ? key.currency1 : key.currency0;
    }

    function _claims() internal view returns (uint256) {
        return pm.balanceOf(address(hook), _quoteCurrency().toId());
    }

    /// Sell the stable (exact in, huge) until the stable's price is `ticks` from the peg. Returns USDC received.
    function _sellTo(int24 ticks) internal returns (uint256 quoteOut, uint256 stableIn) {
        int24 t = hook.pegTick();
        uint160 limit = TickMath.getSqrtPriceAtTick(hook.stableIsToken0() ? t + ticks : t - ticks);
        BalanceDelta d = router.swap(key, SwapParams(hook.stableIsToken0(), -int256(1e30), limit));
        (int128 s, int128 q) = hook.stableIsToken0() ? (d.amount0(), d.amount1()) : (d.amount1(), d.amount0());
        stableIn = uint256(int256(-s));
        quoteOut = uint256(int256(q));
    }

    /// One push from $1 to -2%: the whole sale is tolled at 20%.
    function test_split_vs_single() public {
        uint256 snap = vm.snapshotState();
        (uint256 outSingle, uint256 inSingle) = _sellTo(-200);
        uint256 tollSingle = _claims();
        console2.log("single: stable sold", inSingle / 1e18, "toll USDC", tollSingle / 1e6);
        vm.revertToState(snap);

        uint256 totalIn;
        for (int24 k = 1; k <= 200; ++k) {
            (, uint256 i) = _sellTo(-k);
            totalIn += i;
        }
        uint256 tollSplit = _claims();
        console2.log("split x200: stable sold", totalIn / 1e18, "toll USDC", tollSplit / 1e6);
        assertEq(hook.spotTicks(), -200);
        assertApproxEqRel(totalIn, inSingle, 0.001e18, "same push");
        // The wall is documented as 5% rising to 20% past -1%; a pusher in 200 steps pays far less than the end rate.
        assertGe(tollSplit * 2, tollSingle, "split push pays at least half of the single push's toll");
    }

    /// A sale that starts at +1.5% (bought up, held 30 min) and ends at -0.5%: 2% of the move is toward $1,
    /// 0.25% is away, yet the whole output is tolled at the end-price rate.
    function test_overshoot_charged_on_whole_amount() public {
        _hold(150, 31 minutes);
        assertEq(hook.spotTicks(), 150);
        uint256 snap = vm.snapshotState();
        uint256 before = _claims();
        (uint256 out, uint256 inAmt) = _sellTo(-50);
        uint256 toll = _claims() - before;
        console2.log("overshoot: sold", inAmt / 1e18, "received USDC", out / 1e6);
        console2.log("toll USDC", toll / 1e6, "pips of output", toll * 1e6 / (out + toll));
        vm.revertToState(snap);
        // The same trade in two swaps: +1.5% -> -0.25% (toward $1 and inside the band: free), then -0.25% -> -0.5%.
        _sellTo(-25);
        uint256 awayBefore = _claims();
        (uint256 awayOut,) = _sellTo(-50);
        uint256 awayToll = _claims() - awayBefore;
        assertEq(hook.spotTicks(), -50);
        console2.log("away leg alone: output USDC", awayOut / 1e6, "toll USDC", awayToll / 1e6);
        // "Swaps toward $1 pay nothing extra": the one-swap toll should equal what the away leg alone pays.
        assertLe(toll, awayToll * 11 / 10, "a swap toward $1 pays nothing extra on the part that moved toward it");
    }
}

contract ProofTollQuoteLow is ProofTollTest {
    function _quoteAddr() internal pure override returns (address) {
        return address(0x1111111111111111111111111111111111111111);
    }
}

contract ProofTollQuoteHigh is ProofTollTest {
    function _quoteAddr() internal pure override returns (address) {
        return address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF);
    }
}
```

### 4. Low: PegHook toll: exact-output swaps pay (1+t) per unit, exact-input swaps 1/(1-t): at the 20% cap an exact-output pusher pays 4% less for the same trade

`src/peg/PegHook.sol:269`

```
        uint256 surcharge = abs * pips / PIPS;
```

The surcharge is pips of the UNSPECIFIED amount: for exact-in that is the output (the swapper keeps 1-t of it), for exact-out the input (the swapper pays 1+t). The currency choice is correct in both token orders; the rate is not the same: 1.25x vs 1.20x at MAX_SURCHARGE, 1.0526x vs 1.05x at the wall, <0.03% on the soft leg. A pusher at the wall simply uses exact-output to save 4%. Reported by audit_math 643989; reproduced. Not a funds loss; the documented '20%' holds only for one of the two modes.

**Reproduction**

Pool pushed to -250 stable ticks, 1e22 liquidity added at +-50 ticks around it. Exact-in: sell 1000 imdUSD -> 780.172865 USDC. Same snapshot, exact-out of 780.172865 USDC: costs 959.999980 imdUSD. Expected (one rate for one end price): ~1000 imdUSD. Actual: 960 (4.0% less). Run: forge test --match-path 'test/scratch/*.t.sol' -vv (forge 1.8.3, solc 0.8.26 via_ir, 3.5 min build). Both files reuse the harness test/utils/PegSystem.sol (local v4 PoolManager, real PegHook/PegLPVault); no fork, no ffi.
OUTPUT:
[FAIL: same trade, same end price, same toll: 959999980330346033280 !~= 1000000000000000000000 (max delta: 0.5%, real delta: 4.0000019669653966%)] test_exactOutCheaperThanExactIn() (gas: 892098)
Smallest fix: for exact-output swaps charge abs * pips / (PIPS - pips), so both modes pay 1/(1-t); or document the exact-output rate.

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";
import {PoolManager} from "v4-core/src/PoolManager.sol";
import {Currency} from "v4-core/src/types/Currency.sol";
import {SwapParams, ModifyLiquidityParams} from "v4-core/src/types/PoolOperation.sol";
import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";
import {TickMath} from "v4-core/src/libraries/TickMath.sol";
import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";
import {PegSystem} from "../utils/PegSystem.sol";
import {MockERC20} from "../utils/Mocks.sol";
import {PegHook} from "../../src/peg/PegHook.sol";
import {PegLPVault, IPegHookView} from "../../src/earn/PegLPVault.sol";
import {console2} from "forge-std/console2.sol";

/// Review reproductions on the PegSystem harness (local v4 PoolManager), beta band of 100 ticks.
contract ProofReview is PegSystem {
    using StateLibrary for IPoolManager;

    PegLPVault vault;

    function setUp() public {
        vm.warp(1_800_000_000);
        pm = IPoolManager(address(new PoolManager(address(this))));
        usdc = IERC20(address(new MockERC20("USDC", 6)));
        _deploySystem(IERC20(address(new MockERC20("imdUSDv1", 18))));
        params.seal();
        _openPeg(200_000e18);
        _fund(address(router), 50_000_000e18, 50_000_000e6);
        int24 t = hook.pegTick();
        // Only the beta vault's band holds liquidity (+-100 ticks), ~ $100k a side.
        router.addLiquidity(key, ModifyLiquidityParams(t - 100, t + 100, 2e19, 0));
        _hold(0, 31 minutes);
        vault = new PegLPVault(pm, IPegHookView(address(hook)), address(treasury), 100);
        _fund(address(this), 1_000_000e18, 1_000_000e6);
        usd.approve(address(vault), type(uint256).max);
        usdc.approve(address(vault), type(uint256).max);
        (uint256 a0, uint256 a1) = hook.stableIsToken0() ? (uint256(10_000e18), uint256(10_000e6)) : (uint256(10_000e6), uint256(10_000e18));
        vault.deposit(0, a0, a1, address(this));
    }

    function _swapTo(int24 ticks) internal returns (BalanceDelta d) {
        int24 t = hook.pegTick();
        uint160 limit = TickMath.getSqrtPriceAtTick(hook.stableIsToken0() ? t + ticks : t - ticks);
        (uint160 now_,,,) = pm.getSlot0(key.toId());
        d = router.swap(key, SwapParams(limit < now_, -int256(1e30), limit));
    }

    function _quoteClaims() internal view returns (uint256) {
        Currency q = hook.stableIsToken0() ? key.currency1 : key.currency0;
        return pm.balanceOf(address(hook), q.toId());
    }

    function _stableClaims() internal view returns (uint256) {
        Currency s = hook.stableIsToken0() ? key.currency0 : key.currency1;
        return pm.balanceOf(address(hook), s.toId());
    }

    /// One block (12 s) past the band moves the >=30-minute TWAP past TRIGGER_TICKS and shuts the vault's gate.
    function test_twapOneBlockPush() public {
        assertLe(hook.twapTicks(), 1);
        _swapTo(10_000); // buy all the band's imdUSD; the empty ticks beyond cost nothing
        assertEq(hook.spotTicks(), 10_000);
        console2.log("toll claims (imdUSD) paid for the push:", _stableClaims() / 1e18);
        vm.warp(block.timestamp + 12);
        vm.roll(block.number + 1);
        _swapTo(0); // back to $1 (toward the peg: free)
        vm.warp(block.timestamp + 600);
        vm.roll(block.number + 50);
        int24 twap = hook.twapTicks();
        console2.log("spot", hook.spotTicks());
        console2.log("twap after one 12 s block at +10000 ticks, then 600 s at $1:", twap);
        (uint256 a0, uint256 a1) = hook.stableIsToken0() ? (uint256(1_000e18), uint256(1_000e6)) : (uint256(1_000e6), uint256(1_000e18));
        (bool ok, bytes memory err) =
            address(vault).call(abi.encodeCall(PegLPVault.deposit, (1e15, a0, a1, address(this))));
        console2.log("vault.deposit at $1 succeeded:", ok);
        if (!ok) console2.logBytes(err);
        assertLe(twap, hook.TRIGGER_TICKS(), "a price held for one block moved the TWAP past the keeper trigger");
    }

    /// The same one-block push makes provide() callable at a spot of +8 ticks.
    function test_twapOneBlockTriggersProvide() public {
        _swapTo(10_000);
        vm.warp(block.timestamp + 12);
        vm.roll(block.number + 1);
        _swapTo(8);
        vm.warp(block.timestamp + 12);
        vm.roll(block.number + 1);
        console2.log("twap", hook.twapTicks());
        try hook.provide() returns (uint256 minted) {
            console2.log("keeper minted on a one-block push (imdUSD):", minted / 1e18);
            _assertKeeperSolvent();
            assertTrue(false, "provide() reachable from a one-block push");
        } catch {}
    }

    /// Exact-in and exact-out pay different rates for the same end price (20% leg: 1/(1-t) vs 1+t).
    function test_exactOutCheaperThanExactIn() public {
        _swapTo(-250); // past -2% (beyond the band, empty ticks)
        // add liquidity at the current price so small swaps stay at ~-2.5%
        int24 t = hook.pegTick();
        int24 c = hook.stableIsToken0() ? t - 250 : t + 250;
        router.addLiquidity(key, ModifyLiquidityParams(c - 50, c + 50, 1e22, 0));
        bool sellStable = hook.stableIsToken0();
        uint256 snap = vm.snapshotState();
        // exact-in: sell 1000 imdUSD
        BalanceDelta d = router.swap(key, SwapParams(sellStable, -int256(1000e18), sellStable ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1));
        uint256 got = uint256(int256(hook.stableIsToken0() ? d.amount1() : d.amount0()));
        vm.revertToState(snap);
        // exact-out: receive the same USDC
        d = router.swap(key, SwapParams(sellStable, int256(got), sellStable ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1));
        uint256 paid = uint256(int256(-(hook.stableIsToken0() ? d.amount0() : d.amount1())));
        console2.log("exact-in: 1000 imdUSD -> USDC (6dp)", got);
        console2.log("exact-out: same USDC costs imdUSD (1e15)", paid / 1e15);
        assertApproxEqRel(paid, 1000e18, 0.005e18, "same trade, same end price, same toll");
    }
}
```

### 5. Info: PegLPVault MANIPULATION NatSpec is backwards: at a pushed price a band position is worth MORE at $1/$1, so a withdrawal receives more and a pushed deposit pays a premium, not a discount

`src/earn/PegLPVault.sol:48`

```
/// enough to matter also pays the hook's surcharge beyond ±0.25%. Withdrawals are never gated: a withdrawal at a
```

With both tokens valued at $1 (as PegShareFeed and any holder at par does), the band position's value x(p)+y(p) has derivative L/(2*sqrt p)*(1-1/p): minimal at p = $1 and rising either side. At the beta band (+-100 ticks) the position is worth +0.063% at 50 ticks and +0.25% at the band edge. So L45-47 ('buys shares at a discount ... that the attacker recovers') and L48-49 ('a withdrawal at a pushed price only receives less') describe the opposite of the code's economics: the entrant at a pushed price overpays and the leaver gains (at the pusher's expense). The gate is harmless and still useful; only the comment is wrong. Reported by audit_flow 67415072; confirmed by computation.

**Reproduction**

_amountsFor at pegTick, +50, +100 for band 100, both tokens at $1: value ratio 1.000000, 1.000627, 1.002506 (node: x=1/sqrt(p)-1/sqrt(pb), y=sqrt(p)-sqrt(pa)). Expected per NatSpec: a withdrawal at the pushed price receives less. Actual: +0.25% more at the edge. Fix: reword L45-49.

---

Judge's submission `8643fe25f5bbf586e39782f7b3c663be9a4d3487d982376cd37b6cf4a134fc5d`, accepted on the IdentityMD network. Acceptance means the report met the job's checks;
it is not a guarantee that the code has no other defects.
