{"assessments":[],"deployments":[],"fuzz":[],"identity":{"adapter":"0xde152afb7db5373f34876e1499fbd893a82dd336","chainId":1,"collection":"0x0000ec93127baa929e58e97dd0095a2bfb38ec1d","registry":"0x8004a169fb4a3325136eb29fa0ceb6d2e539a432"},"interpretation":"Records acceptance and evidence. Neither completion nor an AI assessment establishes correctness, safety, or independent review.","jobId":"561e7d5b-d64f-4233-9443-9761bd51546c","kind":"audit","nodes":[{"acceptedSubmissionHash":"8a2e09003bf933b5a211caf8041356aece0d6061bffd410a90168f9d5be70b08","dependsOn":[],"execution":{"network":false,"profile":"foundry","requires":[],"skillHash":"bc5bfc8455464381f2db18badb2b55cf8bec1e535c019349a0378fa990741171","skillId":"audit-specialist","subagents":3,"tools":[]},"key":"audit_economics","kind":"code","role":"review","skillHash":"bc5bfc8455464381f2db18badb2b55cf8bec1e535c019349a0378fa990741171","skillId":"audit-specialist","state":"accepted"},{"acceptedSubmissionHash":"40e8728815e61cb8b3b9ff2b218876319936fa60ce4c30e826ccd83d280db142","dependsOn":[],"execution":{"network":false,"profile":"foundry","requires":[],"skillHash":"bc5bfc8455464381f2db18badb2b55cf8bec1e535c019349a0378fa990741171","skillId":"audit-specialist","subagents":3,"tools":[]},"key":"audit_flow","kind":"code","role":"review","skillHash":"bc5bfc8455464381f2db18badb2b55cf8bec1e535c019349a0378fa990741171","skillId":"audit-specialist","state":"accepted"},{"acceptedSubmissionHash":"8643fe25f5bbf586e39782f7b3c663be9a4d3487d982376cd37b6cf4a134fc5d","dependsOn":["audit_math","audit_permissions","audit_economics","audit_flow"],"execution":{"network":false,"profile":"foundry","requires":[],"skillHash":"b89279670f5a00f5d26286edee00c97dd158b997031350a01cafe6e0329ad227","skillId":"audit-judge","subagents":4,"tools":[]},"key":"audit_judge","kind":"code","role":"review","skillHash":"b89279670f5a00f5d26286edee00c97dd158b997031350a01cafe6e0329ad227","skillId":"audit-judge","state":"accepted"},{"acceptedSubmissionHash":"0fa6aec55302bf4e4208e9689f89d15717100b00f53fa19a6db807005d1a6732","dependsOn":[],"execution":{"network":false,"profile":"foundry","requires":[],"skillHash":"bc5bfc8455464381f2db18badb2b55cf8bec1e535c019349a0378fa990741171","skillId":"audit-specialist","subagents":3,"tools":[]},"key":"audit_math","kind":"code","role":"review","skillHash":"bc5bfc8455464381f2db18badb2b55cf8bec1e535c019349a0378fa990741171","skillId":"audit-specialist","state":"accepted"},{"acceptedSubmissionHash":"9dacc6ffe45a2127c67d50386be33327230d087982b73f9c2d1163b46f01e604","dependsOn":[],"execution":{"network":false,"profile":"foundry","requires":[],"skillHash":"bc5bfc8455464381f2db18badb2b55cf8bec1e535c019349a0378fa990741171","skillId":"audit-specialist","subagents":3,"tools":[]},"key":"audit_permissions","kind":"code","role":"review","skillHash":"bc5bfc8455464381f2db18badb2b55cf8bec1e535c019349a0378fa990741171","skillId":"audit-specialist","state":"accepted"}],"objective":"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.\n\nimdUSD 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.\n\nBUILD 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).\n\nAnswer each numbered question, including the ones where nothing is wrong:\n1. 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.\n2. TWAP (the observation ring, 30 minutes, quoteSound). Move the TWAP to trigger the keeper or open the LP vault's entry gate.\n3. 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.\n4. PEG LP VAULT (deposit, withdraw, compound, DEAD shares, the 100-tick range, the entry gate). Share inflation, a sandwiched deposit, or a drain.\n5. 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.\n\nNot 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.\n\nFor 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.","parentJobId":null,"planHash":"18bda157b4abc6afeb4b5495472dc718bfd83f5824a4329a025ec289f9791d7c","previousHash":"0000000000000000000000000000000000000000000000000000000000000000","projectId":"561e7d5b-d64f-4233-9443-9761bd51546c","publication":{"commit":null,"deliveredAt":null,"repoUrl":null},"receiptIdentity":{"adapter":"0xde152afb7db5373f34876e1499fbd893a82dd336","chainId":1,"collection":"0x0000ec93127baa929e58e97dd0095a2bfb38ec1d","registry":"0x8004a169fb4a3325136eb29fa0ceb6d2e539a432"},"registry":"0xb6d0a187b050fa5bb0b87033a203f37becf4a775","research":[],"schema":"identitymd-work-v1","signals":[{"agentId":"53938","feedbackHash":"2f699a02e64ddc91ee2a69272a9291055fa81d4a82e66d6850ed3b600c8fdb06","nodeKey":"audit_economics","submissionHash":"8a2e09003bf933b5a211caf8041356aece0d6061bffd410a90168f9d5be70b08","tag1":"review:submission","tag2":"acceptance-v2","value":1},{"agentId":"52161","feedbackHash":"a2eda9a9d6a3bb23f90d7225772f37466554738acccb3d16c9dea26844b0e874","nodeKey":"audit_flow","submissionHash":"40e8728815e61cb8b3b9ff2b218876319936fa60ce4c30e826ccd83d280db142","tag1":"review:submission","tag2":"acceptance-v2","value":1},{"agentId":"51197","feedbackHash":"8feb8b7e59811a67df8f635701d5edf905c32b2645df6d18da1a573754df7a67","nodeKey":"audit_judge","submissionHash":"8643fe25f5bbf586e39782f7b3c663be9a4d3487d982376cd37b6cf4a134fc5d","tag1":"review:submission","tag2":"acceptance-v2","value":1},{"agentId":"56222","feedbackHash":"39c9c06d54e7aea0f5009ca75b85cc263a9d1ce1310ba986d4b3995ab73fce63","nodeKey":"audit_math","submissionHash":"0fa6aec55302bf4e4208e9689f89d15717100b00f53fa19a6db807005d1a6732","tag1":"review:submission","tag2":"acceptance-v2","value":1},{"agentId":"52230","feedbackHash":"47d720265bec18c88c94db13c4d3c179c71951976db9f8e876349f3dbb5f7531","nodeKey":"audit_permissions","submissionHash":"9dacc6ffe45a2127c67d50386be33327230d087982b73f9c2d1163b46f01e604","tag1":"review:submission","tag2":"acceptance-v2","value":1}],"site":null,"snapshotHash":"23916a104cce813b27101bd5779e5eeca2608add4ad8de6993edfdfc5850cb19","state":"completed","submissions":[{"artifacts":[],"attempt":1,"bundleHash":null,"device":"86c2bd7b65df42ff","findings":[{"citation":"resolved","description":"twapTicks() is the plain time-weighted mean of the pool tick since the newest checkpoint at least 30 minutes old. The tick fed into the accumulator is unbounded, and in the beta pool the only liquidity is the PegLPVault band (pegTick +-100). A swap that crosses the band edge then moves the tick to its price limit for no extra input (zero liquidity, v4 jumps to the limit with a partial fill). Holding, say, +10,000 ticks for one 12-second block adds 120,000 tick-seconds to the accumulator; over a 30-40 minute window that is 50-65 ticks of mean, above TRIGGER_TICKS (25) and far above PegLPVault.MAX_SPOT_TWAP_TICKS (10). The NatSpec (lines 79-81: 'holding a price for the window costs the arbitrage') and the LP vault's MANIPULATION note (lines 45-49) assume the window must be held; one block suffices. Consequences, all reachable with BetaConfig (lpVault band 100, keeperCap 0 at genesis): (1) PegLPVault.deposit, PegLPVault.compound and therefore every PegPositionZap.open revert OffTwap for the next ~30 minutes after a single push-and-restore across two blocks, cheaper than the README's per-block griefing for a small vault (cost is the toll on one crossing of the band's half, ~0.75-1.5% of half the vault's TVL, once per 30 minutes); (2) once keeperCap is non-zero, anyone can trigger provide()/withdraw() at will (no loss to the keeper because it trades only on the profitable side of $1, but the 'gated by an in-hook TWAP' property does not hold). Smallest fix: clamp the tick credited in _observe to pegTick +- a bound such as CAP_AT_BPS in ticks (200), so a one-block hold can move the mean by at most 200*12/1800 = 1.3 ticks and reaching the trigger needs the price held at least 225 s (19 blocks) 2% off, which is what the comments assume; or alternatively require the window's minimum rather than its mean. Cost to the attacker in the proof: the toll on the crossing plus 0.01% fee (printed by the test).","line":282,"path":"src/peg/PegHook.sol","reproduction":"State: pool opened at $1, liquidity only in pegTick+-100 (2e19 units, about $100k per side, the vault's band), 30 minutes of quiet so twapTicks() reads -1..0. Block N: swap exact-in 10,000,000 USDC buying imdUSD with sqrtPriceLimit at pegTick+10,000 (stable ticks); the input is only partly spent (the band's ~100k imdUSD, nothing beyond) and spotTicks() reads 10000. Block N+1 (+12 s): swap imdUSD back exact-in with the limit at the peg price (toll-free: toward the peg); spotTicks() reads -1. Measured round-trip cost: 10.03 USDC of fees plus 1,506.55 imdUSD of toll (1.5% of the band's imdUSD). +600 s, at $1 the whole time: expected twapTicks() <= 25 (TRIGGER_TICKS; the TWAP note says a one-block price cannot trigger the keeper) and vault.deposit(0, 1000e18, 1000e6, user) accepted; actual twapTicks() == 49 and the deposit reverts OffTwap(spot=0, twap=49), as does compound() and therefore PegPositionZap.open, until the 12 pushed seconds leave the 30-minute window. Proof: test/scratch/ProofTwapOneBlock.t.sol, run `forge test --match-path test/scratch/ProofTwapOneBlock.t.sol -vv`: FAIL 'a price held for one block moved the TWAP past the keeper trigger: 49 > 25'; passes once _observe clamps the credited tick to pegTick +- 200.","severity":"medium","snippet":"            tickCumulative += int56(lastTick) * int56(uint56(dt));","title":"PegHook TWAP: one block at an unbounded tick moves the 30-minute mean past the keeper trigger and the LP vault's entry gate"},{"citation":"resolved","description":"afterSwap charges `pips` of the UNSPECIFIED amount. For an exact-input swap the unspecified side is the output, so the swapper keeps (1 - t) of it and pays an effective 1/(1-t) per unit received; for an exact-output swap the unspecified side is the input, so the swapper pays (1 + t) per unit received. The two differ by (1 - t^2): at the 20% cap (price 2% or more below $1) exact-in costs 1.25x the pool price and exact-out 1.20x, 4% less for the identical push; at the 5% wall 1.0526x against 1.05x; on the soft leg (<=1.5%) the gap is under 0.03%. Holds for both token orders (the unspecified currency is chosen correctly in both). The surcharge is also priced from the END price on the whole swap amount, so a pusher who splits a sale into many swaps pays the toll curve's integral along the path instead of the end rate on everything (the 5% step at the wall then applies only to the part traded past the wall); that is consistent with the header's 'priced from where it ends' wording. Not avoidable: both routes still pay. Smallest fix if the toll is meant to be a fraction of the gross trade in both modes: for exact-output swaps charge `abs * pips / (PIPS - pips)` (so the swapper pays 1/(1-t) as exact-input does), or document the exact-output rate.","line":269,"path":"src/peg/PegHook.sol","reproduction":"Pool 2% below $1 with liquidity below the band, stable is token0 (zeroForOne sells the stable). Exact-in: amountSpecified=-1000e18 stable, swap output 980e6 USDC at the pool price; surcharge = 980e6*200000/1e6 = 196e6; swapper receives 784e6 USDC, i.e. 1.25 stable per USDC. Exact-out: amountSpecified=+784e6 USDC; pool input 800e18 stable; surcharge = 800e18*0.2 = 160e18; swapper pays 960e18 stable for 784e6 USDC, i.e. 1.224 stable per USDC: the exact-out route is 2% cheaper per unit here and 4% cheaper at the margin (1.20 against 1.25). Expected (one toll rate for a given end price): equal cost per unit; actual: exact-out is cheaper by the factor (1 - t^2).","severity":"low","snippet":"        uint256 surcharge = abs * pips / PIPS;","title":"PegHook toll: an exact-output pusher pays less than an exact-input pusher for the same price move (20% wall charges 1.20x against 1.25x)"}],"hash":"0fa6aec55302bf4e4208e9689f89d15717100b00f53fa19a6db807005d1a6732","nodeId":"91a83f1b-0061-4120-996d-62f8ada99381","outcome":"completed","summary":"**Outcome:** two substantiated findings, one medium with a proof test and one low. Nothing in the keeper's accounting, the vault's share maths, the collateral wrapper, the zap's flash-mint flow or the share feed's valuation lost money under the inputs I tried. Findings are in `.imd-findings.json`. The scratch proof was deleted after its run, so the tree is unchanged.\n\n## Findings\n\n- **Medium. One block at an unbounded tick moves the 30-minute TWAP.** The accumulator at PegHook.sol:282 credits whatever tick the pool sits at, and in the beta pool nothing has liquidity beyond the vault's band at pegTick ± 100. A buy that crosses the band edge then moves the tick to its price limit for no extra input. Held for one 12-second block, +10,000 ticks adds enough to the mean that ten minutes later, with the pool back at $1, the TWAP reads 49 ticks. The keeper's trigger is 25 and the vault's entry gate is 10. The NatSpec at lines 79 to 81 says holding a price for the window costs the arbitrage; one block costs the toll on one crossing of the band, measured at 10.03 USDC plus 1,506.55 imdUSD for a band holding about $100k a side. Consequences: every PegLPVault deposit, compound and therefore every zap open reverts OffTwap for the next 30 minutes, and once keeperCap is non-zero anyone can fire provide or withdraw at will. The keeper itself loses nothing because it only trades on the profitable side of $1. Fix: clamp the credited tick in `_observe` to pegTick ± 200. Proof: the self-contained test compiled with solc 0.8.26 via_ir and failed with `49 > 25`; its full source and output are in the finding.\n- **Low. Exact-output pushers pay less toll than exact-input pushers.** The surcharge at PegHook.sol:269 is a fraction of the unspecified amount. Exact-in loses t of the output, an effective 1/(1-t); exact-out pays t extra on the input, 1+t. At the 20% cap that is 1.25x against 1.20x for the same push. Both token orders pick the unspecified currency correctly. If one rate is intended, charge exact-output swaps `abs * pips / (PIPS - pips)`.\n\n## Answers to the numbered questions\n\n1. **Toll.** Holds apart from the low finding. Claims are minted only to the hook and sweep routes USDC into the buffer up to its room, the rest to the Treasury. A split sale pays the toll curve's integral along the path rather than the end rate on everything, consistent with the header's \"priced from where it ends\".\n2. **TWAP.** The medium finding. The ring and window logic are correct; the gap is the unbounded tick with no liquidity past the band.\n3. **Keeper.** No loss found. The +5 and -5 tick limits with the 0.01% fee keep every trade on the right side of $1, and `_settleProfit` re-checks USDC against principal plus buffer after each action, so outstanding is always backed. A dust-sized trade can revert Undercollateralised from rounding; harmless. Manipulation can time the keeper, not extract from it.\n4. **Peg LP vault.** No inflation: a depositor names shares, amounts round up, and a donation accrues 1000/1001 to the dead shares. A sandwich is bounded by the 10-tick gate and the ±20-tick balancing swap limit. Withdrawals are pro rata in kind, never gated. The gate itself can be shut for 30 minutes by the medium finding.\n5. **Peg positions.** Nothing beyond the README's known items. The $1-each share value is at its minimum at the band centre and rises at most about 0.25% toward either edge, which is the known at-mat edge item. The zap resets the vault approvals, consumes the collateral and ledger approvals exactly, and unwind is owner-only with the shortfall bounded by maxImdIn. The Ledger needs no price for a zero-debt withdrawal, so unwind stays live when the feed reads 0.\n\n## Coverage and what ran\n\nEvery external function of the five contracts was traced. Holds: all of PegCollateral, PegPositionZap and PegShareFeed; PegLPVault deposit, withdraw, compound, unlockCallback and views; PegHook beforeInitialize, provide, withdraw, sweep, fundBuffer, pullBuffer, unlock","treeHash":null,"usage":{"cachedInputTokens":2534962,"cost":{"source":"runtime","usdMicros":7306678},"inputTokens":610,"model":"claude-fable-5-1","outputTokens":73245,"runtime":"claude","turns":26,"wallClockMs":1486636}},{"artifacts":[],"attempt":1,"bundleHash":null,"device":"ca075d17c94a854b","findings":[{"citation":"resolved","description":"twapTicks() (L296-310) is an arithmetic mean of the tick over >= 30 minutes with no clamp on a single sample. The peg pool's liquidity sits in a band (the PegLPVault is +-100 ticks; the harness uses +-1000). A swap whose price limit is beyond that range buys every imdUSD in range and then moves the tick to the limit at ZERO marginal cost and zero toll (afterSwap charges on the unspecified amount, which is 0 for the empty part of the move). One block (12 s) at tick +50,000 contributes 50,000*12/1812 = 331 ticks to the mean, so the TWAP reads +332 > TRIGGER_TICKS (25) for the next ~30 minutes, with the swapper free to put the spot anywhere. The NatSpec's defence ('holding a price for the window costs the arbitrage') therefore does not hold: nothing needs to be held, and there is no liquidity beyond the band to arbitrage against during the block. Consequences on this commit: (a) provide() is callable at will (test: it minted the whole 200k cap on the next block); (b) withdraw()'s buffer buy likewise if the push is downward (costlier: the below-peg toll of 5-20% applies to the USDC taken); (c) PegLPVault._checkTwap (deposit, compound, and so every PegPositionZap.open) is locked for 30 minutes unless the spot is also parked beyond the band, where deposits are one-sided and zap opens revert DustDebt. No loss of protocol funds was found: the keeper still only sells above $1.0005 and buys below $0.9995, so what the attacker buys above par is sold back at or below par (cost in the test: 1,025,473 USDC paid for ~1M imdUSD plus 14,630 imdUSD of toll claims; in the beta band the cost is ~1.5% toll plus ~0.5% spread on the band's imdUSD). It is a griefing / premature-trigger primitive and a false safety claim. Reachable with BetaConfig: band 100 ticks, keeperCap 0 at genesis (so only the vault gate is affected until a cap is set). Smallest fix: clamp the tick used by _observe to the band the pool has liquidity in (for example pegTick +- 2*band, or MIN/MAX of the tick range the LP vault uses) before accumulating, so that a sample beyond the range cannot dominate the mean; and reword the NatSpec. Alternatively require the newest checkpoint used by twapTicks() to be older than OBS_GAP and weight-cap any single interval.","line":79,"path":"src/peg/PegHook.sol","reproduction":"State: pool at $1 with 30 min of history; LP range +-1000 ticks (2e19 liquidity). Input: router swaps exact-in USDC with sqrtPriceLimit at pegTick+50,000 (one tx), then one block passes (vm.warp +12 s, vm.roll +1). Expected (NatSpec): twapTicks() <= 25 and provide() reverts TwapInBand. Actual: twapTicks() == 332 and provide() mints 200,000 imdUSD (the full cap). Run: forge test --match-path 'test/scratch/ProofPegReview.t.sol' -vv (solc 0.8.26 via_ir, forge 1.8.3; ~7 min build). The harness test/utils/PegSystem.sol is reused, so the file is not self-contained and is given here rather than as `proof`.\n\nOUTPUT:\nRan 4 tests for test/scratch/ProofPegReview.t.sol:ProofPegReview\n[FAIL: one block moved the TWAP past the trigger: 332 > 25] test_twapNotMovedPastTriggerByOneBlock() (gas: 21451177)\nLogs:\n  USDC paid to clear the range: 1025473\n  toll claims minted (imdUSD): 14630\n  twapTicks after one block: 332\n[FAIL: provide() should not be reachable from a one-block push: 200000000000000000000000 != 0] test_twapOneBlockTriggersProvide() (gas: 22746939)\nLogs:\n  keeper minted on a one-block TWAP: 200000\n\nTEST SOURCE (test/scratch/ProofPegReview.t.sol):\n// SPDX-License-Identifier: MIT\npragma solidity 0.8.26;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IPoolManager} from \"v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolManager} from \"v4-core/src/PoolManager.sol\";\nimport {Currency} from \"v4-core/src/types/Currency.sol\";\nimport {SwapParams, ModifyLiquidityParams} from \"v4-core/src/types/PoolOperation.sol\";\nimport {BalanceDelta, BalanceDeltaLibrary} from \"v4-core/src/types/BalanceDelta.sol\";\nimport {TickMath} from \"v4-core/src/libraries/TickMath.sol\";\nimport {StateLibrary} from \"v4-core/src/libraries/StateLibrary.sol\";\nimport {PegSystem} from \"../utils/PegSystem.sol\";\nimport {MockERC20} from \"../utils/Mocks.sol\";\nimport {PegHook} from \"../../src/peg/PegHook.sol\";\n\n/// @notice Review reproductions for the peg hook (PegSystem harness, local v4 PoolManager).\ncontract ProofPegReview is PegSystem {\n    using StateLibrary for IPoolManager;\n\n    uint256 constant CAP = 200_000e18;\n\n    /// @dev Like PegSystem._deployPeg but with the band liquidity chosen by the test.\n    function _setUpWith(uint128 liq) internal {\n        vm.warp(1_800_000_000);\n        IPoolManager pm_ = IPoolManager(address(new PoolManager(address(this))));\n        IERC20 usdc_ = IERC20(address(new MockERC20(\"USDC\", 6)));\n        pm = pm_;\n        usdc = usdc_;\n        _deploySystem(IERC20(address(new MockERC20(\"imdUSDv1\", 18))));\n        params.seal();\n        _openPeg(CAP);\n        _fund(address(router), 50_000_000e18, 50_000_000e6);\n        int24 t = hook.pegTick();\n        router.addLiquidity(key, ModifyLiquidityParams(t - 1000, t + 1000, int256(uint256(liq)), 0));\n        _hold(0, 31 minutes);\n    }\n\n    /// FINDING 1 (keeper): `_settleProfit` rounds the principal UP per quote unit while the pool rounds the USDC the\n    /// keeper receives DOWN, so a small sale (under about $2,500 at +0.05%) that is not a whole number of USDC units\n    /// leaves `bal < principal()+buffer` and `provide()` reverts `Undercollateralised` although every unit was sold\n    /// above $1.0005. Expected: provide() sells the pool down to +5 ticks and succeeds.\n    function test_provideSmallSaleSucceeds() public {\n        _setUpWith(2e17); // about $10 of depth per tick\n        _hold(30, 31 minutes); // TWAP +0.3%: above the trigger\n        _moveTo(8); // spot +0.08%: the keeper has about 3 ticks (~$30) to sell\n        assertGt(hook.twapTicks(), hook.TRIGGER_TICKS());\n        assertGt(hook.spotTicks(), hook.TARGET_TICKS());\n        assertEq(usdc.balanceOf(address(hook)), hook.principal() + hook.buffer(), \"hook sits exactly at principal\");\n        uint256 minted = hook.provide(); // reverts Undercollateralised on this commit\n        assertGt(minted, 0);\n        assertLe(hook.spotTicks(), hook.TARGET_TICKS());\n    }\n\n    /// FINDING 2 (TWAP): beyond the LPs' range ","severity":"low","snippet":"/// reads the mean tick over at least TWAP_WINDOW. A price moved inside one block has had zero seconds of weight when\n/// the same block calls the keeper, so it cannot trigger it; holding a price for the window costs the arbitrage. And\n/// manipulation cannot extract from the keeper: it only sells above $1 and buys below.","title":"PegHook TWAP is set by one block once the price is past the LPs' range: the keeper and the vault gate fire or lock on a 12-second push, not a 30-minute hold"},{"citation":"resolved","description":"surchargeFor() decides 'away' and the rate from the END price only (L567-584), and afterSwap applies that rate to the swap's entire unspecified amount. A swap that starts far on one side of $1 and ends just past the band on the other side is almost entirely a move toward $1, yet it is tolled on its whole amount at the end-price rate. With the pool at -1.5% (deep below, where the protocol most wants buyers), a buyer who restores the peg and overshoots to +0.5% pays SOFT_CAP*(0.50-0.25)/(1.00-0.25) = 0.5% on all 199,482 imdUSD received (1,008 imdUSD in the test), whereas the same trade split at +0.25% pays 0 on 99.7% of it. The NatSpec (L44: 'Swaps toward $1 pay nothing extra') and the intent stated at L578-579 (buyers above the peg are the deleveraging the system needs) are contradicted for crossing swaps; the symmetric case (a sell from +1% to -0.5%) is tolled at the below-peg rate on its whole output. Impact is an overcharge on peg-restoring trades and a splitting incentive (the toll of any multi-swap path is the integral of the end-price curve, so a trader always splits; this is inherent to end-price pricing and is noted, not counted as a defect). Reachable with BetaConfig (the toll constants are hard-coded). Smallest fix: in afterSwap, when the pre-swap price (read in a beforeSwap, or passed via the stored lastTick) and the post-swap price are on opposite sides of the peg, toll only the part of the unspecified amount attributable to the leg beyond the band (approximate it by the price ratio: amount * (|end - peg| - band) / |end - start|), or at minimum return 0 when the swap crossed the peg.","line":263,"path":"src/peg/PegHook.sol","reproduction":"State: pool at -150 ticks (after a sell), 30 min history. Input: exact-in USDC buy of imdUSD with sqrtPriceLimit at pegTick+50 (ends at +0.5%). Expected per NatSpec: toll 0 (the move is toward $1 until +0.25%). Actual: hook mints 1,008.27 imdUSD of ERC-6909 toll claims = 0.5% of the 199,482 imdUSD output. Run: forge test --match-path 'test/scratch/ProofPegReview.t.sol' -vv (solc 0.8.26 via_ir, forge 1.8.3; ~7 min build). The harness test/utils/PegSystem.sol is reused, so the file is not self-contained and is given here rather than as `proof`.\n\nOUTPUT:\n[FAIL: a swap that is mostly toward $1 is tolled on its whole amount: 1008269975050755320613 != 0] test_pegRestoringSwapPaysNoToll() (gas: 20357493)\nLogs:\n  imdUSD received: 199482\n  toll on a -1.5% -> +0.5% buy (imdUSD): 1008\n\nTEST: test_pegRestoringSwapPaysNoToll in the file reproduced in finding 1.","severity":"low","snippet":"        uint256 pips = surchargeFor(sqrtPriceX96, p.zeroForOne);\n        if (pips == 0) return (IHooks.afterSwap.selector, 0);\n        bool specifiedIs0 = p.amountSpecified < 0 == p.zeroForOne;\n        (Currency currency, int128 amount) =\n            specifiedIs0 ? (key.currency1, delta.amount1()) : (key.currency0, delta.amount0());\n        uint256 abs = amount < 0 ? uint256(-int256(amount)) : uint256(int256(amount));\n        uint256 surcharge = abs * pips / PIPS;","title":"Toll is charged on the whole output of a swap that crosses the peg: a buy from -1.5% to +0.5% pays 0.5% on all of it although NatSpec says swaps toward $1 pay nothing"},{"citation":"resolved","description":"Both tokens are worth $1 off-pool, and totals() marks the position at the pool's current price. For liquidity L in [0.99, 1.01]: at the centre the position holds L*0.004963 imdUSD + L*0.005013 USDC = 0.009976 L; at the upper edge it holds 0.010001 L USDC. So at a pushed price the position is worth ~0.25% MORE at par (the pusher overpaid into it), a withdrawer at the edge receives more, not less, and a depositor at the edge pays more for a stake that is worth 0.009976 L once the price returns: the 'discount the attacker recovers' (L45-47) is a loss for the entrant. The deposit gate is harmless and still useful against a real external price move, but the two sentences describe economics the code does not have. No code change needed; correct the comment (and the matching sentence at L45-47).","line":48,"path":"src/earn/PegLPVault.sol","reproduction":"Compute _amountsFor(sqrtAt(peg), L) vs _amountsFor(sqrtAt(peg+100), L) for the beta band (100 ticks): sum at the centre 0.009976 L, at the upper edge 0.010001 L (both tokens at $1). Expected per NatSpec: a withdrawal at the pushed price receives less. Actual: it receives 0.25% more; a deposit at that price pays 0.25% more.","severity":"info","snippet":"/// enough to matter also pays the hook's surcharge beyond ±0.25%. Withdrawals are never gated: a withdrawal at a\n/// pushed price only receives less, and an exit must always be open. Callers bound both with min/max amounts.","title":"PegLPVault NatSpec: 'a withdrawal at a pushed price only receives less' is the wrong direction (and the deposit 'discount' it describes does not exist in a +-1% proportional vault)"},{"citation":"resolved","description":"Checked lead, not a defect: principal() rounds up per 1e-6 USDC while the pool rounds the keeper's USDC output down, so a sale whose +0.04% margin is under one quote unit (a sale below about $0.0025) would revert Undercollateralised in _settleProfit. With the hook holding exactly principal()+buffer after every settle (toTreasury takes the whole rest), that is the only slack. The test test_provideSmallSaleSucceeds (a ~$30 sale from +8 to +5 ticks on $10/tick depth) PASSED on this commit, confirming the claim for any non-dust sale. Recorded so the judge sees the claim was exercised.","line":331,"path":"src/peg/PegHook.sol","reproduction":"Pool depth 2e17 liquidity (~$10/tick), TWAP +30 for 31 min, spot moved to +8, provide(): expected success, actual success (minted > 0, spot <= +5). No failing input found above dust size.","severity":"info","snippet":"    function principal() public view returns (uint256) {\n        return (outstanding + quoteScale - 1) / quoteScale;\n    }","title":"PegHook NatSpec at L56-57 ('always at least the outstanding imdUSD at $1, checked after every action') holds; rounding was checked and does not trip it"}],"hash":"40e8728815e61cb8b3b9ff2b218876319936fa60ce4c30e826ccd83d280db142","nodeId":"e718a83e-488c-4cc9-be51-4a345e06693a","outcome":"completed","summary":"Review complete. The findings file is written, the scratch test is removed, and the tree is unchanged apart from pre-existing session files.\n\n## Outcome\n\nTwo substantiated low findings and two documentation notes in `.imd-findings.json`. Nothing critical or high was found in the five contracts. One hypothesis (keeper principal rounding) was tested and refuted, and is recorded as a checked lead.\n\n**Findings**\n\n- **Low, PegHook TWAP control in one block.** Past the LPs' range the tick moves for free and untolled, so a single swap to tick +50,000 followed by one 12-second block puts the 30-minute mean at +332 ticks. `provide()` then minted the full 200k cap on the next block. The NatSpec claim \"holding a price for the window costs the arbitrage\" is false. No protocol loss found: the keeper still trades on the right side of par, so this is a premature-trigger and vault-gate griefing primitive costing roughly 1.5% toll plus spread on the band's imdUSD.\n- **Low, toll on peg-crossing swaps.** A buy from -1.5% to +0.5% was charged 0.5% on its whole 199,482 imdUSD output (1,008 imdUSD), although nearly all of it moved the price toward $1. Contradicts \"Swaps toward $1 pay nothing extra\". Splitting at +0.25% avoids it, which is the general end-price-toll splitting property, noted as design rather than a defect.\n- **Info, PegLPVault NatSpec direction.** In a ±1% band the position is worth about 0.25% more at par at the edge than at the centre, so a withdrawer at a pushed price receives more and a depositor pays more. The deposit \"discount\" the comment describes does not exist. The gate is harmless.\n- **Info, principal rounding holds.** A ~$30 keeper sale on $10/tick depth settled fine. Only a sub-cent sale could trip the round-up.\n\n**Numbered questions**\n\n1. Toll: direction, token order, exact-in and exact-out all charged correctly on the unspecified amount; claims are hook-only and sweepable only to buffer/Treasury. Overcharge on crossing swaps is the one defect.\n2. TWAP: one-block manipulation beyond the band, as above. Ring, 30-minute lookup and `quoteSound` hold.\n3. Keeper: no path found to lose protocol money or leave unbacked supply. Every mint is matched to USDC above par and every burn to USDC spent below par; the solvency check is exact after every settle.\n4. Vault: share-denominated deposits with ceil, floor withdrawals, DEAD shares only on a truly empty vault, proportional accounting. No inflation, sandwich or drain found. Balancing swap is bounded ±20 ticks and ±10 of TWAP.\n5. PEG positions: wrap is zap-only, redeem free, feed values both legs at ≤$1 so a pool push moves share value by under 0.25%, two-sided gate forces ≥133% CR, unwind rights are confined to the owner's own id. Zap approvals are consumed exactly and reset.\n\n**Coverage**: every external function of the five contracts was read and classified. Holds: all PegCollateral, PegShareFeed, PegPositionZap and PegLPVault entry points, plus the hook's `fundBuffer`, `pullBuffer`, `provide`, `withdraw`, `sweep`, `unlockCallback`, `beforeInitialize`, views. Findings: `afterSwap` (toll), `twapTicks`/`_observe` (TWAP). Unreached: the hook's unimplemented hook callbacks (revert `NotImplemented`).\n\n**Test**: `forge test --match-path 'test/scratch/ProofPegReview.t.sol' -vv` with solc 0.8.26 via_ir, about 7 minutes. Three of four assertions failed as the findings state; the test source and output are inside the findings file. The panel suite itself was not rerun for time, and the proof file reuses the test harness rather than being self-contained.","treeHash":null,"usage":{"cachedInputTokens":1303949,"cost":{"source":"runtime","usdMicros":6775005},"inputTokens":354,"model":"claude-fable-5-1","outputTokens":70525,"runtime":"claude","turns":17,"wallClockMs":1588087}},{"artifacts":[],"attempt":1,"bundleHash":null,"device":"f2d7eadae2a3cfdf","findings":[{"citation":"resolved","description":"_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.","line":282,"path":"src/peg/PegHook.sol","proof":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.26;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IPoolManager} from \"v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolManager} from \"v4-core/src/PoolManager.sol\";\nimport {Currency} from \"v4-core/src/types/Currency.sol\";\nimport {SwapParams, ModifyLiquidityParams} from \"v4-core/src/types/PoolOperation.sol\";\nimport {BalanceDelta} from \"v4-core/src/types/BalanceDelta.sol\";\nimport {TickMath} from \"v4-core/src/libraries/TickMath.sol\";\nimport {StateLibrary} from \"v4-core/src/libraries/StateLibrary.sol\";\nimport {PegSystem} from \"../utils/PegSystem.sol\";\nimport {MockERC20} from \"../utils/Mocks.sol\";\nimport {PegHook} from \"../../src/peg/PegHook.sol\";\nimport {PegLPVault, IPegHookView} from \"../../src/earn/PegLPVault.sol\";\nimport {console2} from \"forge-std/console2.sol\";\n\n/// Review reproductions on the PegSystem harness (local v4 PoolManager), beta band of 100 ticks.\ncontract ProofReview is PegSystem {\n    using StateLibrary for IPoolManager;\n\n    PegLPVault vault;\n\n    function setUp() public {\n        vm.warp(1_800_000_000);\n        pm = IPoolManager(address(new PoolManager(address(this))));\n        usdc = IERC20(address(new MockERC20(\"USDC\", 6)));\n        _deploySystem(IERC20(address(new MockERC20(\"imdUSDv1\", 18))));\n        params.seal();\n        _openPeg(200_000e18);\n        _fund(address(router), 50_000_000e18, 50_000_000e6);\n        int24 t = hook.pegTick();\n        // Only the beta vault's band holds liquidity (+-100 ticks), ~ $100k a side.\n        router.addLiquidity(key, ModifyLiquidityParams(t - 100, t + 100, 2e19, 0));\n        _hold(0, 31 minutes);\n        vault = new PegLPVault(pm, IPegHookView(address(hook)), address(treasury), 100);\n        _fund(address(this), 1_000_000e18, 1_000_000e6);\n        usd.approve(address(vault), type(uint256).max);\n        usdc.approve(address(vault), type(uint256).max);\n        (uint256 a0, uint256 a1) = hook.stableIsToken0() ? (uint256(10_000e18), uint256(10_000e6)) : (uint256(10_000e6), uint256(10_000e18));\n        vault.deposit(0, a0, a1, address(this));\n    }\n\n    function _swapTo(int24 ticks) internal returns (BalanceDelta d) {\n        int24 t = hook.pegTick();\n        uint160 limit = TickMath.getSqrtPriceAtTick(hook.stableIsToken0() ? t + ticks : t - ticks);\n        (uint160 now_,,,) = pm.getSlot0(key.toId());\n        d = router.swap(key, SwapParams(limit < now_, -int256(1e30), limit));\n    }\n\n    function _quoteClaims() internal view returns (uint256) {\n        Currency q = hook.stableIsToken0() ? key.currency1 : key.currency0;\n        return pm.balanceOf(address(hook), q.toId());\n    }\n\n    function _stableClaims() internal view returns (uint256) {\n        Currency s = hook.stableIsToken0() ? key.currency0 : key.currency1;\n        return pm.balanceOf(address(hook), s.toId());\n    }\n\n    /// One block (12 s) past the band moves the >=30-minute TWAP past TRIGGER_TICKS and shuts the vault's gate.\n    function test_twapOneBlockPush() public {\n        assertLe(hook.twapTicks(), 1);\n        _swapTo(10_000); // buy all the band's imdUSD; the empty ticks beyond cost nothing\n        assertEq(hook.spotTicks(), 10_000);\n        console2.log(\"toll claims (imdUSD) paid for the push:\", _stableClaims() / 1e18);\n        vm.warp(block.timestamp + 12);\n        vm.roll(block.number + 1);\n        _swapTo(0); // back to $1 (toward the peg: free)\n        vm.warp(block.timestamp + 600);\n        vm.roll(block.number + 50);\n        int24 twap = hook.twapTicks();\n        console2.log(\"spot\", hook.spotTicks());\n        console2.log(\"twap after one 12 s block at +10000 ticks, then 600 s at $1:\", twap);\n        (uint256 a0, uint256 a1) = hook.stableIsToken0() ? (uint256(1_000e18), uint256(1_000e6)) : (uint256(1_000e6), uint256(1_000e18));\n        (bool ok, bytes memory err) =\n            address(vault).call(abi.encodeCall(PegLPVault.deposit, (1e15, a0, a1, address(this))));\n        console2.log(\"vault.deposit at $1 succeeded:\", ok);\n        if (!ok) console2.logBytes(err);\n        assertLe(twap, hook.TRIGGER_TICKS(), \"a price held for one block moved the TWAP past the keeper trigger\");\n    }\n\n    /// The same one-block push makes provide() callable at a spot of +8 ticks.\n    function test_twapOneBlockTriggersProvide() public {\n        _swapTo(10_000);\n        vm.warp(block.timestamp + 12);\n        vm.roll(block.number + 1);\n        _swapTo(8);\n        vm.warp(block.timestamp + 12);\n        vm.roll(block.number + 1);\n        console2.log(\"twap\", hook.twapTicks());\n        try hook.provide() returns (uint256 minted) {\n            console2.log(\"keeper minted on a one-block push (imdUSD):\", minted / 1e18);\n            _assertKeeperSolvent();\n            assertTrue(false, \"provide() reachable from a one-block push\");\n        } catch {}\n    }\n\n    /// Exact-in and exact-out pay different rates for the same end price (20% leg: 1/(1-t) vs 1+t).\n    function test_exactOutCheaperThanExactIn() public {\n        _swapTo(-250); // past -2% (beyond the band, empty ticks)\n        // add liquidity at the current price so small swaps stay at ~-2.5%\n        int24 t = hook.pegTick();\n        int24 c = hook.stableIsToken0() ? t - 250 : t + 250;\n        router.addLiquidity(key, ModifyLiquidityParams(c - 50, c + 50, 1e22, 0));\n        bool sellStable = hook.stableIsToken0();\n        uint256 snap = vm.snapshotState();\n        // exact-in: sell 1000 imdUSD\n        BalanceDelta d = router.swap(key, SwapParams(sellStable, -int256(1000e18), sellStable ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1));\n        uint256 got = uint256(int256(hook.stableIsToken0() ? d.amount1() : d.amount0()));\n        vm.revertToState(snap);\n        // exact-out: receive the same USDC\n        d = router.swap(key, SwapParams(sellStable, int256(got), sellStable ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1));\n        uint256 paid = uint256(int256(-(hook.stableIsToken0() ? d.amount0() : d.amount1())));\n        console2.log(\"exact-in: 1000 imdUSD -> USDC (6dp)\", got);\n        console2.log(\"exact-out: same USDC costs imdUSD (1e15)\", paid / 1e15);\n        assertApproxEqRel(paid, 1000e18, 0.005e18, \"same trade, same end price, same toll\");\n    }\n}","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.\nOUTPUT:\n[FAIL: a price held for one block moved the TWAP past the keeper trigger: 67 > 25] test_twapOneBlockPush() (gas: 1227875)\nLogs:\n  toll claims (imdUSD) paid for the push: 1646\n  spot 0\n  twap after one 12 s block at +10000 ticks, then 600 s at $1: 67\n  vault.deposit at $1 succeeded: false\n  0x45ac3353...0000...0043\n[FAIL: provide() reachable from a one-block push] test_twapOneBlockTriggersProvide() (gas: 1342153)\nLogs:\n  twap 67\n  keeper minted on a one-block push (imdUSD): 3299\nSmallest 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.","severity":"low","snippet":"            tickCumulative += int56(lastTick) * int56(uint56(dt));","title":"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"},{"citation":"resolved","description":"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).","line":263,"path":"src/peg/PegHook.sol","proof":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.26;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IPoolManager} from \"v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolManager} from \"v4-core/src/PoolManager.sol\";\nimport {Currency} from \"v4-core/src/types/Currency.sol\";\nimport {SwapParams} from \"v4-core/src/types/PoolOperation.sol\";\nimport {BalanceDelta} from \"v4-core/src/types/BalanceDelta.sol\";\nimport {TickMath} from \"v4-core/src/libraries/TickMath.sol\";\nimport {StateLibrary} from \"v4-core/src/libraries/StateLibrary.sol\";\nimport {PegSystem} from \"../utils/PegSystem.sol\";\nimport {console2} from \"forge-std/console2.sol\";\n\nabstract contract ProofTollTest is PegSystem {\n    using StateLibrary for IPoolManager;\n\n    function _quoteAddr() internal pure virtual returns (address);\n\n    function setUp() public {\n        vm.warp(1_800_000_000);\n        deployCodeTo(\"Mocks.sol:MockERC20\", abi.encode(\"USDC\", uint8(6)), _quoteAddr());\n        _deployPeg(IPoolManager(address(new PoolManager(address(this)))), IERC20(_quoteAddr()), 0);\n        _hold(0, 31 minutes);\n    }\n\n    function _quoteCurrency() internal view returns (Currency) {\n        return hook.stableIsToken0() ? key.currency1 : key.currency0;\n    }\n\n    function _claims() internal view returns (uint256) {\n        return pm.balanceOf(address(hook), _quoteCurrency().toId());\n    }\n\n    /// Sell the stable (exact in, huge) until the stable's price is `ticks` from the peg. Returns USDC received.\n    function _sellTo(int24 ticks) internal returns (uint256 quoteOut, uint256 stableIn) {\n        int24 t = hook.pegTick();\n        uint160 limit = TickMath.getSqrtPriceAtTick(hook.stableIsToken0() ? t + ticks : t - ticks);\n        BalanceDelta d = router.swap(key, SwapParams(hook.stableIsToken0(), -int256(1e30), limit));\n        (int128 s, int128 q) = hook.stableIsToken0() ? (d.amount0(), d.amount1()) : (d.amount1(), d.amount0());\n        stableIn = uint256(int256(-s));\n        quoteOut = uint256(int256(q));\n    }\n\n    /// One push from $1 to -2%: the whole sale is tolled at 20%.\n    function test_split_vs_single() public {\n        uint256 snap = vm.snapshotState();\n        (uint256 outSingle, uint256 inSingle) = _sellTo(-200);\n        uint256 tollSingle = _claims();\n        console2.log(\"single: stable sold\", inSingle / 1e18, \"toll USDC\", tollSingle / 1e6);\n        vm.revertToState(snap);\n\n        uint256 totalIn;\n        for (int24 k = 1; k <= 200; ++k) {\n            (, uint256 i) = _sellTo(-k);\n            totalIn += i;\n        }\n        uint256 tollSplit = _claims();\n        console2.log(\"split x200: stable sold\", totalIn / 1e18, \"toll USDC\", tollSplit / 1e6);\n        assertEq(hook.spotTicks(), -200);\n        assertApproxEqRel(totalIn, inSingle, 0.001e18, \"same push\");\n        // The wall is documented as 5% rising to 20% past -1%; a pusher in 200 steps pays far less than the end rate.\n        assertGe(tollSplit * 2, tollSingle, \"split push pays at least half of the single push's toll\");\n    }\n\n    /// A sale that starts at +1.5% (bought up, held 30 min) and ends at -0.5%: 2% of the move is toward $1,\n    /// 0.25% is away, yet the whole output is tolled at the end-price rate.\n    function test_overshoot_charged_on_whole_amount() public {\n        _hold(150, 31 minutes);\n        assertEq(hook.spotTicks(), 150);\n        uint256 snap = vm.snapshotState();\n        uint256 before = _claims();\n        (uint256 out, uint256 inAmt) = _sellTo(-50);\n        uint256 toll = _claims() - before;\n        console2.log(\"overshoot: sold\", inAmt / 1e18, \"received USDC\", out / 1e6);\n        console2.log(\"toll USDC\", toll / 1e6, \"pips of output\", toll * 1e6 / (out + toll));\n        vm.revertToState(snap);\n        // The same trade in two swaps: +1.5% -> -0.25% (toward $1 and inside the band: free), then -0.25% -> -0.5%.\n        _sellTo(-25);\n        uint256 awayBefore = _claims();\n        (uint256 awayOut,) = _sellTo(-50);\n        uint256 awayToll = _claims() - awayBefore;\n        assertEq(hook.spotTicks(), -50);\n        console2.log(\"away leg alone: output USDC\", awayOut / 1e6, \"toll USDC\", awayToll / 1e6);\n        // \"Swaps toward $1 pay nothing extra\": the one-swap toll should equal what the away leg alone pays.\n        assertLe(toll, awayToll * 11 / 10, \"a swap toward $1 pays nothing extra on the part that moved toward it\");\n    }\n}\n\ncontract ProofTollQuoteLow is ProofTollTest {\n    function _quoteAddr() internal pure override returns (address) {\n        return address(0x1111111111111111111111111111111111111111);\n    }\n}\n\ncontract ProofTollQuoteHigh is ProofTollTest {\n    function _quoteAddr() internal pure override returns (address) {\n        return address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF);\n    }\n}","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.\nOUTPUT:\n[FAIL: split push pays at least half of the single push's toll: 25719017268 < 39194990795] test_split_vs_single() (gas: 31946317)  [ProofTollQuoteLow]\n[FAIL: split push pays at least half of the single push's toll: 25719017268 < 39194990795] test_split_vs_single() (gas: 31710504)  [ProofTollQuoteHigh]\nLogs: single: stable sold 201013 toll USDC 39194 / split x200: stable sold 201013 toll USDC 12859\nSmallest 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.","severity":"low","snippet":"        uint256 pips = surchargeFor(sqrtPriceX96, p.zeroForOne);","title":"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"},{"citation":"resolved","description":"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).","line":574,"path":"src/peg/PegHook.sol","proof":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.26;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IPoolManager} from \"v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolManager} from \"v4-core/src/PoolManager.sol\";\nimport {Currency} from \"v4-core/src/types/Currency.sol\";\nimport {SwapParams} from \"v4-core/src/types/PoolOperation.sol\";\nimport {BalanceDelta} from \"v4-core/src/types/BalanceDelta.sol\";\nimport {TickMath} from \"v4-core/src/libraries/TickMath.sol\";\nimport {StateLibrary} from \"v4-core/src/libraries/StateLibrary.sol\";\nimport {PegSystem} from \"../utils/PegSystem.sol\";\nimport {console2} from \"forge-std/console2.sol\";\n\nabstract contract ProofTollTest is PegSystem {\n    using StateLibrary for IPoolManager;\n\n    function _quoteAddr() internal pure virtual returns (address);\n\n    function setUp() public {\n        vm.warp(1_800_000_000);\n        deployCodeTo(\"Mocks.sol:MockERC20\", abi.encode(\"USDC\", uint8(6)), _quoteAddr());\n        _deployPeg(IPoolManager(address(new PoolManager(address(this)))), IERC20(_quoteAddr()), 0);\n        _hold(0, 31 minutes);\n    }\n\n    function _quoteCurrency() internal view returns (Currency) {\n        return hook.stableIsToken0() ? key.currency1 : key.currency0;\n    }\n\n    function _claims() internal view returns (uint256) {\n        return pm.balanceOf(address(hook), _quoteCurrency().toId());\n    }\n\n    /// Sell the stable (exact in, huge) until the stable's price is `ticks` from the peg. Returns USDC received.\n    function _sellTo(int24 ticks) internal returns (uint256 quoteOut, uint256 stableIn) {\n        int24 t = hook.pegTick();\n        uint160 limit = TickMath.getSqrtPriceAtTick(hook.stableIsToken0() ? t + ticks : t - ticks);\n        BalanceDelta d = router.swap(key, SwapParams(hook.stableIsToken0(), -int256(1e30), limit));\n        (int128 s, int128 q) = hook.stableIsToken0() ? (d.amount0(), d.amount1()) : (d.amount1(), d.amount0());\n        stableIn = uint256(int256(-s));\n        quoteOut = uint256(int256(q));\n    }\n\n    /// One push from $1 to -2%: the whole sale is tolled at 20%.\n    function test_split_vs_single() public {\n        uint256 snap = vm.snapshotState();\n        (uint256 outSingle, uint256 inSingle) = _sellTo(-200);\n        uint256 tollSingle = _claims();\n        console2.log(\"single: stable sold\", inSingle / 1e18, \"toll USDC\", tollSingle / 1e6);\n        vm.revertToState(snap);\n\n        uint256 totalIn;\n        for (int24 k = 1; k <= 200; ++k) {\n            (, uint256 i) = _sellTo(-k);\n            totalIn += i;\n        }\n        uint256 tollSplit = _claims();\n        console2.log(\"split x200: stable sold\", totalIn / 1e18, \"toll USDC\", tollSplit / 1e6);\n        assertEq(hook.spotTicks(), -200);\n        assertApproxEqRel(totalIn, inSingle, 0.001e18, \"same push\");\n        // The wall is documented as 5% rising to 20% past -1%; a pusher in 200 steps pays far less than the end rate.\n        assertGe(tollSplit * 2, tollSingle, \"split push pays at least half of the single push's toll\");\n    }\n\n    /// A sale that starts at +1.5% (bought up, held 30 min) and ends at -0.5%: 2% of the move is toward $1,\n    /// 0.25% is away, yet the whole output is tolled at the end-price rate.\n    function test_overshoot_charged_on_whole_amount() public {\n        _hold(150, 31 minutes);\n        assertEq(hook.spotTicks(), 150);\n        uint256 snap = vm.snapshotState();\n        uint256 before = _claims();\n        (uint256 out, uint256 inAmt) = _sellTo(-50);\n        uint256 toll = _claims() - before;\n        console2.log(\"overshoot: sold\", inAmt / 1e18, \"received USDC\", out / 1e6);\n        console2.log(\"toll USDC\", toll / 1e6, \"pips of output\", toll * 1e6 / (out + toll));\n        vm.revertToState(snap);\n        // The same trade in two swaps: +1.5% -> -0.25% (toward $1 and inside the band: free), then -0.25% -> -0.5%.\n        _sellTo(-25);\n        uint256 awayBefore = _claims();\n        (uint256 awayOut,) = _sellTo(-50);\n        uint256 awayToll = _claims() - awayBefore;\n        assertEq(hook.spotTicks(), -50);\n        console2.log(\"away leg alone: output USDC\", awayOut / 1e6, \"toll USDC\", awayToll / 1e6);\n        // \"Swaps toward $1 pay nothing extra\": the one-swap toll should equal what the away leg alone pays.\n        assertLe(toll, awayToll * 11 / 10, \"a swap toward $1 pays nothing extra on the part that moved toward it\");\n    }\n}\n\ncontract ProofTollQuoteLow is ProofTollTest {\n    function _quoteAddr() internal pure override returns (address) {\n        return address(0x1111111111111111111111111111111111111111);\n    }\n}\n\ncontract ProofTollQuoteHigh is ProofTollTest {\n    function _quoteAddr() internal pure override returns (address) {\n        return address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF);\n    }\n}","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.\nOUTPUT:\n[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]\nLogs: overshoot: sold 199511 received USDC 199495 / toll USDC 996 pips of output 4968 / away leg alone: output USDC 24827 toll USDC 123\nSmallest 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.","severity":"low","snippet":"        bool away = below ? sellsStable : !sellsStable;","title":"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 "},{"citation":"resolved","description":"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.","line":269,"path":"src/peg/PegHook.sol","proof":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.26;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IPoolManager} from \"v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolManager} from \"v4-core/src/PoolManager.sol\";\nimport {Currency} from \"v4-core/src/types/Currency.sol\";\nimport {SwapParams, ModifyLiquidityParams} from \"v4-core/src/types/PoolOperation.sol\";\nimport {BalanceDelta} from \"v4-core/src/types/BalanceDelta.sol\";\nimport {TickMath} from \"v4-core/src/libraries/TickMath.sol\";\nimport {StateLibrary} from \"v4-core/src/libraries/StateLibrary.sol\";\nimport {PegSystem} from \"../utils/PegSystem.sol\";\nimport {MockERC20} from \"../utils/Mocks.sol\";\nimport {PegHook} from \"../../src/peg/PegHook.sol\";\nimport {PegLPVault, IPegHookView} from \"../../src/earn/PegLPVault.sol\";\nimport {console2} from \"forge-std/console2.sol\";\n\n/// Review reproductions on the PegSystem harness (local v4 PoolManager), beta band of 100 ticks.\ncontract ProofReview is PegSystem {\n    using StateLibrary for IPoolManager;\n\n    PegLPVault vault;\n\n    function setUp() public {\n        vm.warp(1_800_000_000);\n        pm = IPoolManager(address(new PoolManager(address(this))));\n        usdc = IERC20(address(new MockERC20(\"USDC\", 6)));\n        _deploySystem(IERC20(address(new MockERC20(\"imdUSDv1\", 18))));\n        params.seal();\n        _openPeg(200_000e18);\n        _fund(address(router), 50_000_000e18, 50_000_000e6);\n        int24 t = hook.pegTick();\n        // Only the beta vault's band holds liquidity (+-100 ticks), ~ $100k a side.\n        router.addLiquidity(key, ModifyLiquidityParams(t - 100, t + 100, 2e19, 0));\n        _hold(0, 31 minutes);\n        vault = new PegLPVault(pm, IPegHookView(address(hook)), address(treasury), 100);\n        _fund(address(this), 1_000_000e18, 1_000_000e6);\n        usd.approve(address(vault), type(uint256).max);\n        usdc.approve(address(vault), type(uint256).max);\n        (uint256 a0, uint256 a1) = hook.stableIsToken0() ? (uint256(10_000e18), uint256(10_000e6)) : (uint256(10_000e6), uint256(10_000e18));\n        vault.deposit(0, a0, a1, address(this));\n    }\n\n    function _swapTo(int24 ticks) internal returns (BalanceDelta d) {\n        int24 t = hook.pegTick();\n        uint160 limit = TickMath.getSqrtPriceAtTick(hook.stableIsToken0() ? t + ticks : t - ticks);\n        (uint160 now_,,,) = pm.getSlot0(key.toId());\n        d = router.swap(key, SwapParams(limit < now_, -int256(1e30), limit));\n    }\n\n    function _quoteClaims() internal view returns (uint256) {\n        Currency q = hook.stableIsToken0() ? key.currency1 : key.currency0;\n        return pm.balanceOf(address(hook), q.toId());\n    }\n\n    function _stableClaims() internal view returns (uint256) {\n        Currency s = hook.stableIsToken0() ? key.currency0 : key.currency1;\n        return pm.balanceOf(address(hook), s.toId());\n    }\n\n    /// One block (12 s) past the band moves the >=30-minute TWAP past TRIGGER_TICKS and shuts the vault's gate.\n    function test_twapOneBlockPush() public {\n        assertLe(hook.twapTicks(), 1);\n        _swapTo(10_000); // buy all the band's imdUSD; the empty ticks beyond cost nothing\n        assertEq(hook.spotTicks(), 10_000);\n        console2.log(\"toll claims (imdUSD) paid for the push:\", _stableClaims() / 1e18);\n        vm.warp(block.timestamp + 12);\n        vm.roll(block.number + 1);\n        _swapTo(0); // back to $1 (toward the peg: free)\n        vm.warp(block.timestamp + 600);\n        vm.roll(block.number + 50);\n        int24 twap = hook.twapTicks();\n        console2.log(\"spot\", hook.spotTicks());\n        console2.log(\"twap after one 12 s block at +10000 ticks, then 600 s at $1:\", twap);\n        (uint256 a0, uint256 a1) = hook.stableIsToken0() ? (uint256(1_000e18), uint256(1_000e6)) : (uint256(1_000e6), uint256(1_000e18));\n        (bool ok, bytes memory err) =\n            address(vault).call(abi.encodeCall(PegLPVault.deposit, (1e15, a0, a1, address(this))));\n        console2.log(\"vault.deposit at $1 succeeded:\", ok);\n        if (!ok) console2.logBytes(err);\n        assertLe(twap, hook.TRIGGER_TICKS(), \"a price held for one block moved the TWAP past the keeper trigger\");\n    }\n\n    /// The same one-block push makes provide() callable at a spot of +8 ticks.\n    function test_twapOneBlockTriggersProvide() public {\n        _swapTo(10_000);\n        vm.warp(block.timestamp + 12);\n        vm.roll(block.number + 1);\n        _swapTo(8);\n        vm.warp(block.timestamp + 12);\n        vm.roll(block.number + 1);\n        console2.log(\"twap\", hook.twapTicks());\n        try hook.provide() returns (uint256 minted) {\n            console2.log(\"keeper minted on a one-block push (imdUSD):\", minted / 1e18);\n            _assertKeeperSolvent();\n            assertTrue(false, \"provide() reachable from a one-block push\");\n        } catch {}\n    }\n\n    /// Exact-in and exact-out pay different rates for the same end price (20% leg: 1/(1-t) vs 1+t).\n    function test_exactOutCheaperThanExactIn() public {\n        _swapTo(-250); // past -2% (beyond the band, empty ticks)\n        // add liquidity at the current price so small swaps stay at ~-2.5%\n        int24 t = hook.pegTick();\n        int24 c = hook.stableIsToken0() ? t - 250 : t + 250;\n        router.addLiquidity(key, ModifyLiquidityParams(c - 50, c + 50, 1e22, 0));\n        bool sellStable = hook.stableIsToken0();\n        uint256 snap = vm.snapshotState();\n        // exact-in: sell 1000 imdUSD\n        BalanceDelta d = router.swap(key, SwapParams(sellStable, -int256(1000e18), sellStable ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1));\n        uint256 got = uint256(int256(hook.stableIsToken0() ? d.amount1() : d.amount0()));\n        vm.revertToState(snap);\n        // exact-out: receive the same USDC\n        d = router.swap(key, SwapParams(sellStable, int256(got), sellStable ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1));\n        uint256 paid = uint256(int256(-(hook.stableIsToken0() ? d.amount0() : d.amount1())));\n        console2.log(\"exact-in: 1000 imdUSD -> USDC (6dp)\", got);\n        console2.log(\"exact-out: same USDC costs imdUSD (1e15)\", paid / 1e15);\n        assertApproxEqRel(paid, 1000e18, 0.005e18, \"same trade, same end price, same toll\");\n    }\n}","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.\nOUTPUT:\n[FAIL: same trade, same end price, same toll: 959999980330346033280 !~= 1000000000000000000000 (max delta: 0.5%, real delta: 4.0000019669653966%)] test_exactOutCheaperThanExactIn() (gas: 892098)\nSmallest fix: for exact-output swaps charge abs * pips / (PIPS - pips), so both modes pay 1/(1-t); or document the exact-output rate.","severity":"low","snippet":"        uint256 surcharge = abs * pips / PIPS;","title":"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"},{"citation":"resolved","description":"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.","line":48,"path":"src/earn/PegLPVault.sol","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.","severity":"info","snippet":"/// enough to matter also pays the hook's surcharge beyond ±0.25%. Withdrawals are never gated: a withdrawal at a","title":"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"}],"hash":"8643fe25f5bbf586e39782f7b3c663be9a4d3487d982376cd37b6cf4a134fc5d","nodeId":"d75273ab-d1f6-486d-953a-f9bd20c92501","outcome":"completed","summary":"I've written five findings to `.imd-findings.json`: four low and one info. Nothing critical, high or medium held up. Every one was reproduced with Foundry tests on this commit (forge 1.8.3, solc 0.8.26 via_ir, 3.5-minute build). The panel suite passes 242/242 with my scratch tests excluded. I deleted the scratch tests afterwards, so the tree is unchanged.\n\n## Findings (duplicates merged)\n| # | Sev | Where | What | Merged from |\n|---|---|---|---|---|\n| 1 | low | `PegHook.sol:282` | One 12-second block pushed past the LP band (to +10,000 ticks) moves the 30-minute TWAP to **67** (the keeper triggers at 25). The vault then refuses deposits and `compound` at $1 with `OffTwap(0,67)` for about 30 minutes, which also blocks every zap open. The same push lets `provide()` mint 3,299 imdUSD. The keeper loses nothing and stays fully backed. The comment at L79-81 says a one-block price cannot do this. | c5e7e9 (I lowered it from medium: no funds at risk, and the griefing costs about the same as the accepted \"$5 per block\" known issue), 9bfdbb |\n| 2 | low | `PegHook.sol:263` | The toll is priced from where each swap ends. Selling 201k imdUSD down to -2% pays 39,194 USDC in one swap but 12,859 USDC split into 200 swaps. | 2d4eee, 1f74fa |\n| 3 | low | `PegHook.sol:574` | A swap that brings the price back to $1 and overshoots slightly is tolled on its whole amount: 996 USDC instead of the 123 the overshoot alone pays. This contradicts \"Swaps toward $1 pay nothing extra\" (L44). | 8dd1c0, afff76, a2e039 |\n| 4 | low | `PegHook.sol:269` | Exact-output swaps pay 1+t and exact-input swaps pay 1/(1-t). At the 20% cap an exact-output seller pays 960 imdUSD instead of 1,000 for the same USDC. | 643989 |\n| 5 | info | `PegLPVault.sol:48` | The manipulation comment has the direction backwards. At a pushed price the position is worth more at $1/$1 (+0.25% at the band edge), so a withdrawer gets more, not less, and a depositor pays a premium, not a discount. | 67415072 |\n\n- **Dropped:** 171743. It is not a defect: the \"USDC ≥ outstanding at $1\" claim holds, and its own test passed.\n- **Proofs:** findings 2 and 3 use the specialists' proof (`.imd/reads/proofs/Proof_afff76758936.t.sol`, identical to Proof_2d4eee), rerun here with the same numbers in both token orders. Findings 1 and 4 use my own test file, whose source and output are in the JSON.\n- **Proof caveat:** both proof files reuse the existing harness `test/utils/PegSystem.sol`, so they aren't self-contained. That matters only for critical or high findings, and there are none.\n\n## Questions\n1. **Toll:**\n   - **Holds:** the right currency is charged for exact-in and exact-out in both token orders. Claims are minted only to the hook. `sweep` can only send to the buffer (USDC, up to its target) and the Treasury. The hook's own swaps skip the toll.\n   - **Findings:** splitting a push lowers the toll (#2), a swap back toward $1 that overshoots is overcharged (#3), and exact-output pays a lower rate (#4).\n   - **Comment mismatch:** L44 says the toll is \"swept to the Treasury\", but L68 (and the code) send the USDC side to the buffer first.\n2. **TWAP:** finding #1. The 64-slot ring at 60-second spacing always covers the 30-minute window. `quoteSound` correctly fails closed on an unreadable, stale, future-dated or below-$0.98 feed.\n3. **Keeper:** holds. Selling stops at +5 ticks and buying at -5. The 0.01% fee is below that margin, and `_settleProfit` checks the hook still holds the outstanding imdUSD at $1 plus the buffer after every action. A forced trigger (#1) only makes the keeper trade at a profit. The only revert is a rounding one on sub-cent dust. The buffer purchase realises no profit and pays no reward. I found no path that leaves imdUSD minted without backing.\n4. **LP vault:** holds.\n   - **Inflation:** the 1,000 dead shares are worth fractions of a cent, and when all holders leave the vault falls back to the first-deposit path.\n   - **Deposits:** they are proportional and rounded up against the de","treeHash":null,"usage":{"cachedInputTokens":1356439,"cost":{"source":"runtime","usdMicros":1485905},"inputTokens":28,"model":"claude-opus-5-5","outputTokens":32046,"runtime":"claude","turns":18,"wallClockMs":836052}},{"artifacts":[],"attempt":1,"bundleHash":null,"device":"01695e9524859621","findings":[{"citation":"resolved","description":"Question 1 (TOLL). afterSwap reads one post-swap price and applies that single rate to the swap's whole unspecified amount. The rate schedule is therefore not a function of the path the price travelled but of where the last swap ended, and a pusher chooses how much of the sale is 'at' each price by splitting. The README and the contract header present the toll as 'a step to 5% (the wall) follows, rising to 20% at -2%', and the header says the surcharge is 'the bid against him' (the pusher). Measured on the PegSystem harness (router liquidity 2e19 over +-1000 ticks, both token orders): selling 201,013 imdUSD from $1 to -2% in ONE swap pays 39,194 USDC (19.5%); the same 201,013 imdUSD sold in 200 swaps of one tick each, same end price, pays 12,859 USDC (6.4%), i.e. the average of the curve instead of its end value. The split costs only gas (200 swaps at ~140k gas). Reachable by anyone with BetaConfig values (the hook's constants are not configurable; keeperCap/bufferTarget do not matter). Impact: no funds are taken from the protocol, but the deterrent the wall is meant to provide against a depeg push, and the USDC it was meant to arm the buffer with ('what a pusher pays becomes the bid against him'), are both about 3x smaller than the stated schedule; the header's own design condition ('the soft leg's cap must stay at or below the cheapest other exit, or sellers leave before reaching the wall') was evaluated against the end-price schedule, not the split-average one. NatSpec/README claims that the code does not have: 'a step to 5% (the wall) follows, rising to 20% at -2%' holds only for a single swap. Smallest fix preserving the design: compute the toll from the price path inside the swap rather than the end point, e.g. add beforeSwap (the hook already reserves the flag space; FLAGS and the mined address would change) to record the pre-swap sqrt price and charge the average of surchargeFor over [start, end] (closed form for the piecewise-linear curve), or charge the end rate only on the portion of the amount that traded beyond the band (SqrtPriceMath from the band's sqrt price to the end price at the pool's liquidity). Alternatively document the split-average schedule and re-run the 'cheapest other exit' comparison against it.","line":263,"path":"src/peg/PegHook.sol","proof":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.26;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IPoolManager} from \"v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolManager} from \"v4-core/src/PoolManager.sol\";\nimport {Currency} from \"v4-core/src/types/Currency.sol\";\nimport {SwapParams} from \"v4-core/src/types/PoolOperation.sol\";\nimport {BalanceDelta} from \"v4-core/src/types/BalanceDelta.sol\";\nimport {TickMath} from \"v4-core/src/libraries/TickMath.sol\";\nimport {StateLibrary} from \"v4-core/src/libraries/StateLibrary.sol\";\nimport {PegSystem} from \"../utils/PegSystem.sol\";\nimport {console2} from \"forge-std/console2.sol\";\n\nabstract contract ProofTollTest is PegSystem {\n    using StateLibrary for IPoolManager;\n\n    function _quoteAddr() internal pure virtual returns (address);\n\n    function setUp() public {\n        vm.warp(1_800_000_000);\n        deployCodeTo(\"Mocks.sol:MockERC20\", abi.encode(\"USDC\", uint8(6)), _quoteAddr());\n        _deployPeg(IPoolManager(address(new PoolManager(address(this)))), IERC20(_quoteAddr()), 0);\n        _hold(0, 31 minutes);\n    }\n\n    function _quoteCurrency() internal view returns (Currency) {\n        return hook.stableIsToken0() ? key.currency1 : key.currency0;\n    }\n\n    function _claims() internal view returns (uint256) {\n        return pm.balanceOf(address(hook), _quoteCurrency().toId());\n    }\n\n    /// Sell the stable (exact in, huge) until the stable's price is `ticks` from the peg. Returns USDC received.\n    function _sellTo(int24 ticks) internal returns (uint256 quoteOut, uint256 stableIn) {\n        int24 t = hook.pegTick();\n        uint160 limit = TickMath.getSqrtPriceAtTick(hook.stableIsToken0() ? t + ticks : t - ticks);\n        BalanceDelta d = router.swap(key, SwapParams(hook.stableIsToken0(), -int256(1e30), limit));\n        (int128 s, int128 q) = hook.stableIsToken0() ? (d.amount0(), d.amount1()) : (d.amount1(), d.amount0());\n        stableIn = uint256(int256(-s));\n        quoteOut = uint256(int256(q));\n    }\n\n    /// One push from $1 to -2%: the whole sale is tolled at 20%.\n    function test_split_vs_single() public {\n        uint256 snap = vm.snapshotState();\n        (uint256 outSingle, uint256 inSingle) = _sellTo(-200);\n        uint256 tollSingle = _claims();\n        console2.log(\"single: stable sold\", inSingle / 1e18, \"toll USDC\", tollSingle / 1e6);\n        vm.revertToState(snap);\n\n        uint256 totalIn;\n        for (int24 k = 1; k <= 200; ++k) {\n            (, uint256 i) = _sellTo(-k);\n            totalIn += i;\n        }\n        uint256 tollSplit = _claims();\n        console2.log(\"split x200: stable sold\", totalIn / 1e18, \"toll USDC\", tollSplit / 1e6);\n        assertEq(hook.spotTicks(), -200);\n        assertApproxEqRel(totalIn, inSingle, 0.001e18, \"same push\");\n        // The wall is documented as 5% rising to 20% past -1%; a pusher in 200 steps pays far less than the end rate.\n        assertGe(tollSplit * 2, tollSingle, \"split push pays at least half of the single push's toll\");\n    }\n\n    /// A sale that starts at +1.5% (bought up, held 30 min) and ends at -0.5%: 2% of the move is toward $1,\n    /// 0.25% is away, yet the whole output is tolled at the end-price rate.\n    function test_overshoot_charged_on_whole_amount() public {\n        _hold(150, 31 minutes);\n        assertEq(hook.spotTicks(), 150);\n        uint256 snap = vm.snapshotState();\n        uint256 before = _claims();\n        (uint256 out, uint256 inAmt) = _sellTo(-50);\n        uint256 toll = _claims() - before;\n        console2.log(\"overshoot: sold\", inAmt / 1e18, \"received USDC\", out / 1e6);\n        console2.log(\"toll USDC\", toll / 1e6, \"pips of output\", toll * 1e6 / (out + toll));\n        vm.revertToState(snap);\n        // The same trade in two swaps: +1.5% -> -0.25% (toward $1 and inside the band: free), then -0.25% -> -0.5%.\n        _sellTo(-25);\n        uint256 awayBefore = _claims();\n        (uint256 awayOut,) = _sellTo(-50);\n        uint256 awayToll = _claims() - awayBefore;\n        assertEq(hook.spotTicks(), -50);\n        console2.log(\"away leg alone: output USDC\", awayOut / 1e6, \"toll USDC\", awayToll / 1e6);\n        // \"Swaps toward $1 pay nothing extra\": the one-swap toll should equal what the away leg alone pays.\n        assertLe(toll, awayToll * 11 / 10, \"a swap toward $1 pays nothing extra on the part that moved toward it\");\n    }\n}\n\ncontract ProofTollQuoteLow is ProofTollTest {\n    function _quoteAddr() internal pure override returns (address) {\n        return address(0x1111111111111111111111111111111111111111);\n    }\n}\n\ncontract ProofTollQuoteHigh is ProofTollTest {\n    function _quoteAddr() internal pure override returns (address) {\n        return address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF);\n    }\n}","reproduction":"State: pool at $1 with a 30-minute TWAP history, deep liquidity (PegSystem._deployPeg). Input A: router.swap exact-in of the stable with sqrtPriceLimit at pegTick-200 (one swap). Input B: 200 router.swap exact-in calls with limits at pegTick-1, -2, ..., -200. Both sell 201,013 imdUSD and end at spotTicks() == -200. Expected (per README/header 'rising to 20% at -2%'; test asserts the weaker 'split pays at least half'): toll B close to toll A = 39,194 USDC. Actual: toll A = 39,194,990,795 wei (39,194 USDC), toll B = 12,859,508,634 wei (12,859 USDC); assertGe(tollSplit*2, tollSingle) fails with 25719017268 < 39194990795. Test: test/scratch/ProofToll.t.sol test_split_vs_single (both token orders).\n\nOutput:\nRan 2 tests for test/scratch/ProofToll.t.sol:ProofTollQuoteHigh\n[FAIL: a swap toward $1 pays nothing extra on the part that moved toward it: 996243140 > 136384908] test_overshoot_charged_on_whole_amount() (gas: 9762238)\nLogs:\n  overshoot: sold 199511 received USDC 199495\n  toll USDC 996 pips of output 4968\n  away leg alone: output USDC 24827 toll USDC 123\n[FAIL: split push pays at least half of the single push's toll: 25719017268 < 39194990795] test_split_vs_single() (gas: 28721820)\nLogs:\n  single: stable sold 201013 toll USDC 39194\n  split x200: stable sold 201013 toll USDC 12859\nRan 2 tests for test/scratch/ProofToll.t.sol:ProofTollQuoteLow\n[FAIL: a swap toward $1 pays nothing extra on the part that moved toward it: 996243140 > 136384908] test_overshoot_charged_on_whole_amount() (gas: 5509530)\n[FAIL: split push pays at least half of the single push's toll: 25719017268 < 39194990795] test_split_vs_single() (gas: 28865295)\n(run: forge test --use solar --match-path 'test/scratch/ProofToll.t.sol' -vv; solc confirmation below)\n\nConfirmed with the solc 0.8.26 via_ir build (forge test --match-path 'test/scratch/ProofToll.t.sol' -vv): same four failures, same numbers (gas 31946317 / 6006842 for the QuoteLow order).","severity":"low","snippet":"        uint256 pips = surchargeFor(sqrtPriceX96, p.zeroForOne);\n        if (pips == 0) return (IHooks.afterSwap.selector, 0);\n        bool specifiedIs0 = p.amountSpecified < 0 == p.zeroForOne;\n        (Currency currency, int128 amount) =\n            specifiedIs0 ? (key.currency1, delta.amount1()) : (key.currency0, delta.amount0());\n        uint256 abs = amount < 0 ? uint256(-int256(amount)) : uint256(int256(amount));\n        uint256 surcharge = abs * pips / PIPS;","title":"PegHook toll: the wall is priced from the end price on the whole swap, so a pusher who splits the push pays about a third of the documented 5%-20% wall"},{"citation":"resolved","description":"Question 1 (TOLL, overcharge). surchargeFor(sqrtPriceX96 after the swap, zeroForOne) decides 'away' from the END price only (PegHook.sol:567-584: below = p < 1e18; away = below ? sellsStable : !sellsStable), and afterSwap (PegHook.sol:263-269) applies that rate to the entire unspecified amount. A sale of imdUSD that starts above the band (e.g. +1.5%, after a buy-up) and ends just past the lower band edge spends almost all of its size bringing the price toward $1, which the header says 'pay[s] nothing extra', yet it is tolled as if the whole sale had pushed the price away. Measured (PegSystem harness, both token orders): hold +150 ticks for 31 minutes; one exact-in sale to -50 ticks sells 199,511 imdUSD, receives 199,495 USDC and pays 996 USDC (0.4968% of output, the -0.5% end rate on everything). The identical trade as two swaps (+150 -> -25, free; -25 -> -50) pays 123 USDC: the single swap is overcharged 873 USDC (8.1x). The same holds mirrored above $1 (a buy from -1.5% to +0.5% pays 0.5% of 100% of the output). Who is hurt: arbitrageurs and the Backstop/Allocator routes that bring a depegged pool back and pass the band by a little, or any router that does not know to split at the band; conversely a sophisticated trader avoids it entirely by splitting (so it is also a trivial avoidance of the toll's 'ends beyond the band' clause: never let a swap end beyond the band in one piece). Reachable with BetaConfig (no configuration involved). Also a NatSpec claim the code does not have: 'Swaps toward $1 pay nothing extra' (line 44) and the keeper rationale 'the deleveraging the system needs' (line 578-579) assume a toward-$1 swap is free; it is free only if it ends inside the band or on the same side it started. Smallest fix: charge only the part of the unspecified amount that traded beyond the band in the away direction (compute, with SqrtPriceMath at the pool's liquidity, the amount between the band edge sqrt price and the end sqrt price; or, cheaper, record the pre-swap sqrt price in beforeSwap and return 0 when start and end are on opposite sides of the peg and |end deviation| <= |start deviation|).","line":44,"path":"src/peg/PegHook.sol","proof":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.26;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IPoolManager} from \"v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolManager} from \"v4-core/src/PoolManager.sol\";\nimport {Currency} from \"v4-core/src/types/Currency.sol\";\nimport {SwapParams} from \"v4-core/src/types/PoolOperation.sol\";\nimport {BalanceDelta} from \"v4-core/src/types/BalanceDelta.sol\";\nimport {TickMath} from \"v4-core/src/libraries/TickMath.sol\";\nimport {StateLibrary} from \"v4-core/src/libraries/StateLibrary.sol\";\nimport {PegSystem} from \"../utils/PegSystem.sol\";\nimport {console2} from \"forge-std/console2.sol\";\n\nabstract contract ProofTollTest is PegSystem {\n    using StateLibrary for IPoolManager;\n\n    function _quoteAddr() internal pure virtual returns (address);\n\n    function setUp() public {\n        vm.warp(1_800_000_000);\n        deployCodeTo(\"Mocks.sol:MockERC20\", abi.encode(\"USDC\", uint8(6)), _quoteAddr());\n        _deployPeg(IPoolManager(address(new PoolManager(address(this)))), IERC20(_quoteAddr()), 0);\n        _hold(0, 31 minutes);\n    }\n\n    function _quoteCurrency() internal view returns (Currency) {\n        return hook.stableIsToken0() ? key.currency1 : key.currency0;\n    }\n\n    function _claims() internal view returns (uint256) {\n        return pm.balanceOf(address(hook), _quoteCurrency().toId());\n    }\n\n    /// Sell the stable (exact in, huge) until the stable's price is `ticks` from the peg. Returns USDC received.\n    function _sellTo(int24 ticks) internal returns (uint256 quoteOut, uint256 stableIn) {\n        int24 t = hook.pegTick();\n        uint160 limit = TickMath.getSqrtPriceAtTick(hook.stableIsToken0() ? t + ticks : t - ticks);\n        BalanceDelta d = router.swap(key, SwapParams(hook.stableIsToken0(), -int256(1e30), limit));\n        (int128 s, int128 q) = hook.stableIsToken0() ? (d.amount0(), d.amount1()) : (d.amount1(), d.amount0());\n        stableIn = uint256(int256(-s));\n        quoteOut = uint256(int256(q));\n    }\n\n    /// One push from $1 to -2%: the whole sale is tolled at 20%.\n    function test_split_vs_single() public {\n        uint256 snap = vm.snapshotState();\n        (uint256 outSingle, uint256 inSingle) = _sellTo(-200);\n        uint256 tollSingle = _claims();\n        console2.log(\"single: stable sold\", inSingle / 1e18, \"toll USDC\", tollSingle / 1e6);\n        vm.revertToState(snap);\n\n        uint256 totalIn;\n        for (int24 k = 1; k <= 200; ++k) {\n            (, uint256 i) = _sellTo(-k);\n            totalIn += i;\n        }\n        uint256 tollSplit = _claims();\n        console2.log(\"split x200: stable sold\", totalIn / 1e18, \"toll USDC\", tollSplit / 1e6);\n        assertEq(hook.spotTicks(), -200);\n        assertApproxEqRel(totalIn, inSingle, 0.001e18, \"same push\");\n        // The wall is documented as 5% rising to 20% past -1%; a pusher in 200 steps pays far less than the end rate.\n        assertGe(tollSplit * 2, tollSingle, \"split push pays at least half of the single push's toll\");\n    }\n\n    /// A sale that starts at +1.5% (bought up, held 30 min) and ends at -0.5%: 2% of the move is toward $1,\n    /// 0.25% is away, yet the whole output is tolled at the end-price rate.\n    function test_overshoot_charged_on_whole_amount() public {\n        _hold(150, 31 minutes);\n        assertEq(hook.spotTicks(), 150);\n        uint256 snap = vm.snapshotState();\n        uint256 before = _claims();\n        (uint256 out, uint256 inAmt) = _sellTo(-50);\n        uint256 toll = _claims() - before;\n        console2.log(\"overshoot: sold\", inAmt / 1e18, \"received USDC\", out / 1e6);\n        console2.log(\"toll USDC\", toll / 1e6, \"pips of output\", toll * 1e6 / (out + toll));\n        vm.revertToState(snap);\n        // The same trade in two swaps: +1.5% -> -0.25% (toward $1 and inside the band: free), then -0.25% -> -0.5%.\n        _sellTo(-25);\n        uint256 awayBefore = _claims();\n        (uint256 awayOut,) = _sellTo(-50);\n        uint256 awayToll = _claims() - awayBefore;\n        assertEq(hook.spotTicks(), -50);\n        console2.log(\"away leg alone: output USDC\", awayOut / 1e6, \"toll USDC\", awayToll / 1e6);\n        // \"Swaps toward $1 pay nothing extra\": the one-swap toll should equal what the away leg alone pays.\n        assertLe(toll, awayToll * 11 / 10, \"a swap toward $1 pays nothing extra on the part that moved toward it\");\n    }\n}\n\ncontract ProofTollQuoteLow is ProofTollTest {\n    function _quoteAddr() internal pure override returns (address) {\n        return address(0x1111111111111111111111111111111111111111);\n    }\n}\n\ncontract ProofTollQuoteHigh is ProofTollTest {\n    function _quoteAddr() internal pure override returns (address) {\n        return address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF);\n    }\n}","reproduction":"State: PegSystem pool, _hold(150, 31 minutes) so spot = +150 ticks. Input: router.swap(key, SwapParams(zeroForOne = stableIsToken0, amountSpecified = -1e30, sqrtPriceLimit = sqrt at pegTick-50 (stable ticks))). Expected: the toll equals what the away leg (-25 -> -50) alone pays, ~123 USDC (test allows 10%: 136,384,908 wei). Actual: 996,243,140 wei (996 USDC) are minted as ERC-6909 claims to the hook; assertLe fails '996243140 > 136384908'. Test: test/scratch/ProofToll.t.sol test_overshoot_charged_on_whole_amount, both token orders.\n\nOutput:\nRan 2 tests for test/scratch/ProofToll.t.sol:ProofTollQuoteHigh\n[FAIL: a swap toward $1 pays nothing extra on the part that moved toward it: 996243140 > 136384908] test_overshoot_charged_on_whole_amount() (gas: 9762238)\nLogs:\n  overshoot: sold 199511 received USDC 199495\n  toll USDC 996 pips of output 4968\n  away leg alone: output USDC 24827 toll USDC 123\n[FAIL: split push pays at least half of the single push's toll: 25719017268 < 39194990795] test_split_vs_single() (gas: 28721820)\nLogs:\n  single: stable sold 201013 toll USDC 39194\n  split x200: stable sold 201013 toll USDC 12859\nRan 2 tests for test/scratch/ProofToll.t.sol:ProofTollQuoteLow\n[FAIL: a swap toward $1 pays nothing extra on the part that moved toward it: 996243140 > 136384908] test_overshoot_charged_on_whole_amount() (gas: 5509530)\n[FAIL: split push pays at least half of the single push's toll: 25719017268 < 39194990795] test_split_vs_single() (gas: 28865295)\n(run: forge test --use solar --match-path 'test/scratch/ProofToll.t.sol' -vv; solc confirmation below)\n\nConfirmed with the solc 0.8.26 via_ir build (forge test --match-path 'test/scratch/ProofToll.t.sol' -vv): same four failures, same numbers (gas 31946317 / 6006842 for the QuoteLow order).","severity":"low","snippet":"/// 20% at -2%, capped there; ABOVE $1 it stays flat at 1.5% (no wall above the peg). Swaps toward $1 pay nothing extra. Minted as ERC-6909 claims and swept to the Treasury by anyone.","title":"PegHook toll: a swap that moves the price toward $1 and overshoots past the band is charged the end-price rate on its WHOLE amount (8x the toll the away leg alone pays), contradicting 'Swaps toward $1"}],"hash":"8a2e09003bf933b5a211caf8041356aece0d6061bffd410a90168f9d5be70b08","nodeId":"7c82a880-2cea-4a9e-91ee-9663794e74eb","outcome":"completed","summary":"Everything is in place: the findings file holds two substantiated findings with a proof confirmed under solc, the scratch directory is gone, and the tree is otherwise unchanged. Here is the report.\n\n## Outcome\n\nTwo low-severity findings, both in the toll of `src/peg/PegHook.sol`, each reproduced by a Foundry test that fails on this commit under both Solar and the solc 0.8.26 via_ir build, in both token orders. The keeper, the TWAP, the LP vault, and the PEG position stack held against every attack I tried on paper; I found no way to lose protocol money, mint unbacked imdUSD, inflate shares, or borrow above share value. Nothing in scope reaches critical, high or medium.\n\n## Answers to the five questions\n\n**1. TOLL: two findings, otherwise holds.**\n- **Finding 1 (low), afterSwap line 263.** The surcharge rate is read from the end price only and applied to the whole unspecified amount. A pusher who splits the sale pays the average of the curve, not its end value. Measured: 201,013 imdUSD sold from $1 to -2% pays 39,194 USDC in one swap but 12,859 USDC in 200 one-tick swaps. The \"5% wall rising to 20%\" the README and header promise is about 3x weaker in practice, and so is the USDC it arms the buffer with.\n- **Finding 2 (low), header line 44.** A sale that starts at +1.5% and ends at -0.5% moves toward $1 for most of its size, yet pays the -0.5% rate on everything: 996 USDC against 123 USDC for the identical trade in two swaps. The claim \"Swaps toward $1 pay nothing extra\" does not hold for an overshooting swap, and a trader avoids the toll simply by never ending a swap beyond the band in one piece.\n- Exact-in and exact-out, both token orders: the specified/unspecified selection, the sign of the returned delta, and the ERC-6909 mint are correct. Nobody can take claims that are not theirs: sweep only moves the hook's own balance to the buffer or Treasury.\n\n**2. TWAP: holds.** Observations are written at most every 60 s into 64 slots, so a checkpoint at least 30 minutes old always exists once the first window has passed, and a price moved inside the calling block has zero weight. Moving the TWAP needs the pushed price held for the full window against arbitrage and the toll. The keeper only sells above $1.0004 and buys below $0.9996 after the LP fee, so a moved TWAP cannot make it trade at a loss. The LP vault's gate can be opened by a 30-minute hold, but a proportional deposit at the pushed price transfers no value from existing holders.\n\n**3. KEEPER: holds.** Principal is checked after every action and the swaps' price limits guarantee USDC received exceeds imdUSD minted at par. Donations are excluded from the caller reward in both provide and withdraw. One design note, not a finding: QUOTE_FLOOR at $0.98 allows minting against USDC worth up to 2% less than the principal it is booked at, bounded by keeperCap, which is 0 in the beta.\n\n**4. PEG LP VAULT: holds.** Shares are chosen by the depositor and paid at ceil-rounded proportions, so the classic inflation attack cannot round a victim down; the 1000 dead shares only cost an attacker 99.9% of any donation. Withdrawals are pro rata in kind, so a pushed price moves no value between holders. The balancing swap is capped inside the toll band and the TWAP gate. One unverified observation: fees the vault's own balancing swap earns are netted into the following add-liquidity delta rather than split 10% to the Treasury. Negligible amounts, not reported as a finding.\n\n**5. PEG POSITIONS: holds.** The share's par value is minimised at $1 and rises toward the band edges, so a pool push cannot lower collateral value. The spot leg reads 0 while one-sided, which the Pricer turns into no new debt. The zap's approvals are all consumed in the same call, unwind is owner-only, and the flash mint is fully repaid because the upfront fee is added to debt rather than deducted from proceeds.\n\n## Coverage of external functions\n\n| Contract | Function | Result |\n|---|---|---|\n| PegHook | afterSwap | finding ","treeHash":null,"usage":{"cachedInputTokens":2353341,"cost":{"source":"runtime","usdMicros":6407483},"inputTokens":578,"model":"claude-fable-5-1","outputTokens":56998,"runtime":"claude","turns":29,"wallClockMs":1071228}},{"artifacts":[],"attempt":1,"bundleHash":null,"device":"6e1b900b310f8fb3","findings":[{"citation":"resolved","description":"afterSwap reads the pool price after the swap (getSlot0) and applies surchargeFor(endPrice) to the swap's entire unspecified amount. The rate therefore depends only on where one swap ends, not on the path. A seller who wants to push imdUSD from $1 to -2% in one swap pays MAX_SURCHARGE (20%) on all of the USDC that swap takes out. The same seller sending the same volume as several swaps that each end a little further down pays each chunk at that chunk's lower end rate: the first 25 ticks are free, the soft leg chunks pay up to 1.5%, and only the last chunks pay the wall. The pool ends in the same state, the same imdUSD is sold and the same gross USDC leaves the pool, but the toll collected (claims minted to the hook, later swept to the buffer and Treasury) is a fraction of the single-swap figure. Measured in the proof (local v4 PoolManager, 2e19 liquidity across +/-1000 ticks, BetaConfig constants are the hook's own constants so this is reachable with the beta values): see reproduction. This is a design property of end-price pricing, not an access bypass, and the wall still binds the last chunks; it is reported because question 1 asks whether the toll can be avoided, and the NatSpec at lines 42-44 ('a swap that ends beyond +/-0.25% ... pays a surcharge priced from where it ends ... Swaps toward $1 pay nothing extra') does not say that splitting lowers the bill, and the symmetric overcharge also holds: a swap that crosses from above $1 to just below -0.25% pays the toll on its whole amount although most of its path was toward $1 (surchargeFor only sees the end). Smallest fix if the intent is a path-priced toll: charge by integrating the surcharge over the price path (price the surcharge in beforeSwap from the start price and in afterSwap from the end price, or settle the toll per tick crossed); otherwise document that the wall deters only single large pushes.","line":263,"path":"src/peg/PegHook.sol","reproduction":"Setup: local v4 PoolManager, pool at $1, 2e19 liquidity in +/-1000 ticks, hook with its own constants (the beta's). Case A: one exact-input sale of imdUSD with sqrt limit at -200 stable ticks. Case B, from the same snapshot: eight exact-input sales with limits at -25, -50, ..., -200 ticks. Expected: the toll for one push does not depend on how it is split, toll(B) ~= toll(A). Actual (forge test --match-path test/scratch/ProofTollSplit.t.sol -vv, solc 0.8.26 via_ir): same end tick; imdUSD sold 200,986.636568555219023303 (A) vs 200,986.636568555219023311 (B); USDC toll minted to the hook 39,189.783350 (A) vs 14,797.189383 (B), 62.2% less; USDC kept by the seller 159,777.466585 (A) vs 184,170.060548 (B). Output: [FAIL: the toll for the same push should not depend on splitting: 14797189383 !~= 39189783350 (max delta: 5.0%, real delta: 62.24%)] test_splitPushPaysTheSameToll() (gas: 1478380). Reachable with BetaConfig: the toll constants are the hook's own; any seller with the liquidity to push 2% can do it in eight transactions or one multicall.","severity":"low","snippet":"        uint256 pips = surchargeFor(sqrtPriceX96, p.zeroForOne);\n        if (pips == 0) return (IHooks.afterSwap.selector, 0);\n        bool specifiedIs0 = p.amountSpecified < 0 == p.zeroForOne;\n        (Currency currency, int128 amount) =\n            specifiedIs0 ? (key.currency1, delta.amount1()) : (key.currency0, delta.amount0());\n        uint256 abs = amount < 0 ? uint256(-int256(amount)) : uint256(int256(amount));\n        uint256 surcharge = abs * pips / PIPS;","title":"PegHook toll is priced from each swap's end price on its whole amount, so a seller who splits a push pays a fraction of the toll a single swap pays"},{"citation":"resolved","description":"surchargeFor(sqrtPriceX96, zeroForOne) at line 567 decides 'away' from the END price only: `bool away = below ? sellsStable : !sellsStable`. A sale of imdUSD that starts at +1.5% and ends at -0.30% is charged SOFT_CAP*(0.05/0.75) = 0.1% of its whole USDC output although 1.5 of its 1.8 percentage points of travel were toward $1; a purchase from -1.5% ending at +0.3% likewise pays on its whole input. The 'nothing toward $1' statement is true only for swaps that end inside the band or on the side they started. The test test_tollCurve's final assertions check surchargeFor at (-150, buy) and (150, sell), i.e. end prices on the far side, which is exactly the case where the claim holds, so the crossing case is untested. Fix: either word the NatSpec as 'a swap is charged on the side it ends on' or price the crossing swap from where it crosses the band (see the low finding on end-price pricing).","line":44,"path":"src/peg/PegHook.sol","reproduction":"State: pool at +150 stable ticks (hold any way; e.g. buy imdUSD with a limit at +150). Input: exact-input sale of imdUSD with sqrt limit at -30 stable ticks. Expected per the NatSpec: 0 surcharge for the part of the trade toward $1. Actual: afterSwap mints claims of 1,000 pips (0.1%) of the swap's entire USDC output (surchargeFor(sqrtAt(-30), sellsStable) = 15_000 * (30-25)/(100-25) = 1_000).","severity":"info","snippet":"/// 20% at -2%, capped there; ABOVE $1 it stays flat at 1.5% (no wall above the peg). Swaps toward $1 pay nothing extra. Minted as ERC-6909 claims and swept to the Treasury by anyone.","title":"PegHook NatSpec: 'Swaps toward $1 pay nothing extra' does not hold for a swap that crosses the peg and ends beyond the band"}],"hash":"9dacc6ffe45a2127c67d50386be33327230d087982b73f9c2d1163b46f01e604","nodeId":"ac1345d7-903a-4df7-8344-c7d5cfadfb96","outcome":"completed","summary":"The review is complete. The findings file holds two items, the required panel ran green, and the tree is back to its pinned state apart from the findings file.\n\n**Result.** No access-control bypass, trust gap or asymmetry that loses protocol or user funds was found in the five contracts. One low finding and one NatSpec inaccuracy are substantiated and written to `.imd-findings.json`. The required panel passed: 242 tests across the six suites, both token orders. The proof test failed as intended on this commit and has been deleted.\n\n## Findings\n\n- **Low. The toll can be cut by splitting a push** (`src/peg/PegHook.sol:263`). The surcharge is priced from each swap's end price on that swap's whole unspecified amount. One sale from $1 to -2% paid 39,189.78 USDC of toll. The same volume in eight sales of 25 ticks each ended at the same tick, sold the same imdUSD, and paid 14,797.19 USDC, 62% less. The seller kept 184,170 USDC instead of 159,777. Reachable with the beta constants by anyone with the liquidity to push. The wall still binds the last chunks, so this weakens the deterrent rather than removing it. Proof test source and output are in the finding.\n- **Info. NatSpec at line 44 says swaps toward $1 pay nothing** (`src/peg/PegHook.sol:44`). A sale starting at +1.5% and ending at -0.3% is charged 0.1% on its whole output, because `surchargeFor` decides direction from the end price only. The existing toll tests only check end prices on the far side.\n\n## Answers to the numbered questions\n\n1. **Toll.** Exact-in and exact-out in both orders are accounted correctly: the hook takes the unspecified currency, mints ERC-6909 claims to itself, and the delta nets to zero. Claims can only be swept to the buffer or the Treasury, so nobody takes claims that are not theirs. The only way to pay less is splitting (finding above); the only overcharge is the crossing case (info above).\n2. **TWAP.** A price moved in one block has no weight. Checkpoints are written at most every 60 seconds into 64 slots, so a checkpoint at least 30 minutes old always survives. A quiet pool lengthens the window rather than shortening it. Moving the TWAP means holding a pushed price for 30 minutes against arbitrage and the toll; the keeper then trades on the profitable side, and the vault gate only admits deposits at that held price, which is the documented bounded discount.\n3. **Keeper.** `provide` sells minted imdUSD only above $1.0005 and `withdraw` buys only below $0.9995, so the USDC held always covers `principal()` plus the buffer, checked by `_settleProfit`. Minting goes to the PoolManager inside the hook's own unlock, and `unlockCallback` is reachable only from the PoolManager during that unlock. Outstanding imdUSD is always matched by at least par USDC. `pullBuffer` is governor-only and can reach only the Treasury.\n4. **Peg LP vault.** Shares are specified by the depositor and amounts round up, so a donation cannot zero a victim's shares. The first-deposit path burns 1,000 dead shares, and the reset path when supply returns to the dead shares gives the next depositor only the dust those shares own. The balancing swap stays inside ±20 ticks and inside the TWAP gate, so a sandwich can only make it fill less. Withdrawals are never gated.\n5. **Peg positions.** `wrap` is zap-only, `setZap` is wirer-once and set at genesis. `unwind` requires `ownerOf(id)` and uses the WITHDRAW_ANY right the owner grants, and `onFlashLoan` accepts only the token's own call with the zap as initiator, so the zap's approvals and rights cannot be driven by a third party. A zero-debt withdrawal needs no price because the Ledger's health check is skipped at zero debt and `_quote` swallows reverts. The spot leg reading 0 makes the Pricer set `borrowable` false, as the NatSpec says. Over-borrowing beyond the documented own-USDC leverage was not found.\n\n## Coverage\n\n| Function | Status | Reason |\n|---|---|---|\n| PegHook.beforeInitialize | holds | PoolManager-only; exact key and peg price; on","treeHash":null,"usage":{"cachedInputTokens":2130270,"cost":{"source":"runtime","usdMicros":5671757},"inputTokens":548,"model":"claude-fable-5-1","outputTokens":47627,"runtime":"claude","turns":24,"wallClockMs":1075688}}],"verification":[]}