Repository navigation
feat(contracts): venue-neutral BuybackBurner + Uniswap V3 burner - #1003
Conversation
Extract the shared MEV-defense stack (TWAP floor, min/max band, per-epoch liquidity cap) into a new abstract `GuardedBuybackBurner`, leaving `BuybackBurner` venue-neutral: keeper entry point, TOKEN-balance-delta verification, burn, USDC rescue, pause, plus abstract `_performSwap` / `_requireWired` hooks. Rebase `BuybackBurnerBalancerV3` onto the guard (Permit2 swap path unchanged), and add `BuybackBurnerUniswapV3` as a sibling venue: a single `exactInputSingle` USDC->TOKEN swap on SwapRouter02 with a scoped router approval, a slot0-sourced TWAP floor (hand-rolled accumulator, both token orderings), the fee-tier swap fee, and pool USDC balance as the cap denominator. `FeeRouter` is already venue-agnostic (it only transfers the buyback USDC to the burner address), so switching venues is one `setBuybackBurner` call. Targets Arbitrum Sepolia, where Uniswap V3 is live but Balancer V3 is not yet deployed; the Balancer burner can be swapped in later with no FeeRouter change. Closes #1000. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Gas snapshotNo gas changes vs base. |
Contracts coverageLine coverage: 90.12% (2245/2491 lines) |
There was a problem hiding this comment.
Code Review
This pull request refactors the buyback burner architecture to be venue-neutral by introducing an abstract GuardedBuybackBurner contract that houses the shared MEV-defense stack (TWAP accumulator, slippage floor, min/max buyback band, and per-epoch USDC liquidity cap). The existing BuybackBurnerBalancerV3 is refactored to inherit from this new base, and a new BuybackBurnerUniswapV3 implementation is introduced to support Uniswap V3. The review feedback highlights an opportunity to improve consistency and robustness by validating the Uniswap V3 pool address in the constructor of BuybackBurnerUniswapV3 if it is supplied at deployment time, matching the fail-fast behavior of the Balancer V3 burner.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Pull request overview
This PR refactors the buyback burner contracts to be venue-neutral and introduces a Uniswap V3-backed burner for Arbitrum Sepolia, while extracting the shared MEV-defense logic (TWAP floor, slippage/band checks, and per-epoch USDC cap) into a reusable GuardedBuybackBurner layer.
Changes:
- Refactor
BuybackBurnerinto a venue-neutral abstract base with venue wiring delegated to_requireWired()and swap execution delegated to_performSwap(). - Introduce
GuardedBuybackBurneras the shared MEV-defense stack used by both Balancer and Uniswap venue implementations. - Add
BuybackBurnerUniswapV3(plus interfaces and a new unit test suite) and update existing Balancer tests/scripts for the refactor.
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| contracts/src/BuybackBurner.sol | Refactors base burner into venue-neutral abstract contract with _requireWired() hook. |
| contracts/src/GuardedBuybackBurner.sol | Adds shared TWAP floor + band + epoch-cap MEV-defense layer used by venue implementations. |
| contracts/src/BuybackBurnerBalancerV3.sol | Adapts Balancer burner to extend GuardedBuybackBurner and provide Balancer-specific venue hooks and wiring setters. |
| contracts/src/BuybackBurnerUniswapV3.sol | Adds Uniswap V3 burner implementation with slot0-based spot math and scoped router approval. |
| contracts/src/interfaces/IUniswapV3SwapRouter.sol | Adds minimal router interface for exactInputSingle. |
| contracts/src/interfaces/IUniswapV3Pool.sol | Adds minimal pool interface for slot0/token ordering/fee tier reads. |
| contracts/test/BuybackBurner.t.sol | Updates base tests to reflect venue-neutral wiring (_requireWired) instead of Balancer-specific wiring. |
| contracts/test/BuybackBurnerBalancerV3.t.sol | Updates Balancer tests to expect shared GuardedBuybackBurner errors/events after refactor. |
| contracts/test/BuybackBurnerBalancerV3.swapburn.fork.t.sol | Updates fork test expectations for moved error selectors. |
| contracts/test/BuybackBurnerUniswapV3.t.sol | Adds unit tests for Uniswap venue hooks (spot math, wiring validation, scoped approval, guard behavior). |
| contracts/script/ActivateBuyback.s.sol | Updates keeper calldata encoding to the new GuardedBuybackBurner.setKeeper entry point. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Review comments (#1003): - BuybackBurnerUniswapV3: validate a deploy-time pool in the constructor (fail-fast via _spotPrice, symmetric with setPool and the Balancer ctor). - Reset the inherited TWAP accumulator + per-epoch cap on every venue rotation (Uniswap setPool, Balancer setPool/setVault) via a shared GuardedBuybackBurner._resetGuardState(), so the floor/cap re-derive fail-closed against the new venue instead of carrying stale state. - ActivateBuyback script: log GuardedBuybackBurner.setKeeper to match the encoded calldata. CI gates (were red, independent of the comments): - Regenerate .gas-snapshot (stale after the new contracts). - Waive slither incorrect-equality on the epochStartUsdcDepth == 0 lazy-init sentinel — newly tripped because the Uniswap _usdcDepthRaw is balanceOf- backed; the sentinel is intentional (same as twapLastUpdate == 0). - Waive aderyn unsafe-casting on the Permit2 uint160(amountIn) downcast — the bound check moved into the BuybackBurner parent, so aderyn can no longer see it across the contract split; the cast is provably safe. Adds tests for the constructor validation and guard-state reset on rotation. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Walkthrough
ChangesVenue-neutral BuybackBurner + UniswapV3
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
contracts/src/BuybackBurner.sol (1)
142-148: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winClarify that
_performSwapreturns the received delta.Line 144 says “post-swap TOKEN amount,” but Line 132 compares the hook return to
balanceAfter - balanceBefore. Returning the total post-swap balance would spuriously revert when the contract already holds TOKEN.Suggested wording
- /// USDC->TOKEN swap (the TOKEN landing in this contract) and returns the - /// post-swap TOKEN amount. Keeping this `virtual` without a body keeps + /// USDC->TOKEN swap (the TOKEN landing in this contract) and returns the + /// received TOKEN balance delta, not this contract's post-swap TOKEN + /// balance. Keeping this `virtual` without a body keeps🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@contracts/src/BuybackBurner.sol` around lines 142 - 148, The `_performSwap` hook in `BuybackBurner` is documented inconsistently with its caller: it should return the TOKEN amount received from the swap (the delta), not the contract’s total post-swap TOKEN balance. Update the `@dev` comment on `_performSwap` to clearly state that the return value is the received TOKEN increase used against `balanceAfter - balanceBefore`, so the contract can already hold TOKEN without triggering a false revert.contracts/test/BuybackBurnerBalancerV3.t.sol (1)
786-812: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAlso assert the epoch-cap state resets on rotation.
Line 786 and Line 800 only verify the TWAP side of
_resetGuardState()viaTwapNotReady. Accruing someepochSwappedUsdc()before the rotation and asserting it returns to zero afterward would cover the other half of the documented reset behavior and catch a partial-reset regression.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@contracts/test/BuybackBurnerBalancerV3.t.sol` around lines 786 - 812, The rotation tests for setPool and setVault only verify the TWAP reset path, but they should also cover the epoch-cap reset handled by _resetGuardState(). Before calling bb.setPool and bb.setVault, accrue some epochSwappedUsdc() on bb, then assert that value returns to zero after rotation alongside the existing TwapNotReady check. Update test_setPool_resetsGuardStateOnRotation and test_setVault_resetsGuardStateOnRotation so they validate both GuardStateReset behavior and the epoch-swapped state reset.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@contracts/src/BuybackBurnerBalancerV3.sol`:
- Around line 228-229: Add the matching Aderyn waiver immediately above the same
lines that already use slither-disable-next-line missing-zero-check in
BuybackBurnerBalancerV3.setPool and the other affected spot around the later
setter, so both analyzer suppressions are paired on the target line. Keep the
existing Slither suppression and insert the corresponding
aderyn-ignore-next-line(missing-zero-check) directly before each affected
statement to satisfy the repo’s paired-waiver rule.
In `@contracts/src/GuardedBuybackBurner.sol`:
- Around line 215-218: The poke() flow in GuardedBuybackBurner is using a
transient spot via _updateTwapAccumulator(), which lets a permissionless caller
pin a manipulated price across the next TWAP interval. Update poke() and the
related TWAP accumulation logic to derive the floor from finalized cumulative
oracle state or venue observations instead of sampling the latest marginal spot,
and adjust the helper path referenced by _updateTwapAccumulator() so the next
interval cannot be biased by a one-transaction price move.
---
Nitpick comments:
In `@contracts/src/BuybackBurner.sol`:
- Around line 142-148: The `_performSwap` hook in `BuybackBurner` is documented
inconsistently with its caller: it should return the TOKEN amount received from
the swap (the delta), not the contract’s total post-swap TOKEN balance. Update
the `@dev` comment on `_performSwap` to clearly state that the return value is
the received TOKEN increase used against `balanceAfter - balanceBefore`, so the
contract can already hold TOKEN without triggering a false revert.
In `@contracts/test/BuybackBurnerBalancerV3.t.sol`:
- Around line 786-812: The rotation tests for setPool and setVault only verify
the TWAP reset path, but they should also cover the epoch-cap reset handled by
_resetGuardState(). Before calling bb.setPool and bb.setVault, accrue some
epochSwappedUsdc() on bb, then assert that value returns to zero after rotation
alongside the existing TwapNotReady check. Update
test_setPool_resetsGuardStateOnRotation and
test_setVault_resetsGuardStateOnRotation so they validate both GuardStateReset
behavior and the epoch-swapped state reset.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 76197e8d-6d66-4039-a60d-2b29e03573fc
📒 Files selected for processing (12)
contracts/.gas-snapshotcontracts/script/ActivateBuyback.s.solcontracts/src/BuybackBurner.solcontracts/src/BuybackBurnerBalancerV3.solcontracts/src/BuybackBurnerUniswapV3.solcontracts/src/GuardedBuybackBurner.solcontracts/src/interfaces/IUniswapV3Pool.solcontracts/src/interfaces/IUniswapV3SwapRouter.solcontracts/test/BuybackBurner.t.solcontracts/test/BuybackBurnerBalancerV3.swapburn.fork.t.solcontracts/test/BuybackBurnerBalancerV3.t.solcontracts/test/BuybackBurnerUniswapV3.t.sol
| // slither-disable-next-line missing-zero-check | ||
| function setPool(address newPool) external onlyRole(GOVERNANCE_ROLE) { |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Add the matching Aderyn waiver next to these Slither suppressions.
Line 228 and Line 248 add slither-disable-next-line missing-zero-check, but the repo rule requires the paired aderyn-ignore-next-line(...) immediately above the same target line. Without that second waiver, this change can still fail the expected analyzer pass. As per coding guidelines, "Place // slither-disable-next-line <detector> immediately before the targeted line, and place // aderyn-ignore-next-line(<detector>) immediately before the targeted line as well."
Also applies to: 248-249
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@contracts/src/BuybackBurnerBalancerV3.sol` around lines 228 - 229, Add the
matching Aderyn waiver immediately above the same lines that already use
slither-disable-next-line missing-zero-check in BuybackBurnerBalancerV3.setPool
and the other affected spot around the later setter, so both analyzer
suppressions are paired on the target line. Keep the existing Slither
suppression and insert the corresponding
aderyn-ignore-next-line(missing-zero-check) directly before each affected
statement to satisfy the repo’s paired-waiver rule.
Source: Coding guidelines
There was a problem hiding this comment.
Not applying — there's no such paired-waiver rule in this repo, and there's no Aderyn finding to suppress.
missing-zero-checkis a Slither detector. Aderyn v0.6.8 (the version CI runs) reports zeromissing-zero-check/address-without-check findings on these setters, so anaderyn-ignore-next-line(missing-zero-check)would waive a finding that doesn't exist.- The established repo pattern is Slither-only here:
FeeRouter.sol:156uses the same lone// slither-disable-next-line missing-zero-checkand is green onmain. The CLAUDE.md guidance is about placement of each directive when used, not a requirement to pair them.
Verified locally: forge build + Slither (0 medium+) + Aderyn 0.6.8 (0 high) all pass without the added waiver.
| function poke() external { | ||
| _requireWired(); | ||
| _updateTwapAccumulator(); | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift
poke() can pin a transient price for the entire next TWAP interval.
_updateTwapAccumulator() records the current marginal spot and later treats it as if it remained valid until the next sample. Because poke() is permissionless, an attacker can skew the pool, call poke(), unwind immediately, and still have that manipulated spot weighted across the whole interval to the next update. That makes the TWAP floor biasable/DOSable with a one-transaction price move, which undermines the MEV guard this layer is meant to provide. This needs a cumulative oracle derived from finalized interval state (for example the venue’s native oracle/observations) instead of assuming the latest sampled spot persisted after the sampling transaction.
Also applies to: 374-405
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@contracts/src/GuardedBuybackBurner.sol` around lines 215 - 218, The poke()
flow in GuardedBuybackBurner is using a transient spot via
_updateTwapAccumulator(), which lets a permissionless caller pin a manipulated
price across the next TWAP interval. Update poke() and the related TWAP
accumulation logic to derive the floor from finalized cumulative oracle state or
venue observations instead of sampling the latest marginal spot, and adjust the
helper path referenced by _updateTwapAccumulator() so the next interval cannot
be biased by a one-transaction price move.
There was a problem hiding this comment.
This is a real property of the accumulator, but it's the documented, accepted design — not a regression in this PR, and the suggested remedy isn't available on these venues.
- Accepted per ADR 018. The floor is a self-maintained cumulative-price accumulator precisely because Balancer V3 ships no built-in pool oracle (V2's was removed) and TOKEN has no external feed at launch. ADR 018 states it is necessary-not-sufficient and stays layered under mandatory keeper-side private-RPC routing and the per-epoch liquidity cap.
- Native oracle isn't an option here. Balancer V3 has no
observe(); the Uniswap V3 pool is freshly-seeded with observation cardinality 1, so its native oracle returns nothing usable. That's the explicit reason both burners share the hand-rolled accumulator (see the contract header). - The floor is not the primary gate. The effective minimum is
max(twapFloor, keeper minTokenOut)and every buyback is submitted through a private-RPC bundle, so a public single-poke skew can't be paired with a same-block front-run of the keeper's swap. A manipulated-low floor still leaves the keeper's ownminOut; a manipulated-high floor is bounded griefing. - Pre-existing + out of scope.
_updateTwapAccumulator/poke()are lifted byte-identical from the already-mergedBuybackBurnerBalancerV3onmain; this PR only made them venue-neutral. Replacing the accumulator with a finalized-cumulative oracle is an ADR-018-level change for a separate PR, not this venue refactor.
Not changing it here.
From the comprehensive PR review: - BuybackBurnerUniswapV3._spotPrice: guard the direct (USDC=token0) branch against a spot that floor-divides to 0, symmetric with the inverted branch, so an implausibly-cheap TOKEN can't collapse the TWAP floor to 0 (fail-open). - Tests: cover the Uniswap-specific balanceOf-backed per-epoch cap (EpochCapExceeded), depth re-snapshot after a setPool rotation, and the new zero-spot revert guard. - ActivateBuyback: fix the stale doc comment to GuardedBuybackBurner.setKeeper. Regenerated .gas-snapshot for the new tests. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Review round 2 — addressed in
|
…920312 # Conflicts: # contracts/.gas-snapshot
What
Makes
BuybackBurnervenue-neutral and adds a Uniswap V3 burner, so the protocol can run buybacks on Arbitrum Sepolia (where Uniswap V3 is live but Balancer V3 is not deployed — the singleton Vault0xbA13…has no code there).Closes #1000.
Architecture
Three layers, replacing the previous Balancer-only base:
BuybackBurner(abstract, venue-neutral) — keeper entry point, the actual-TOKEN-balance-delta verification + burn, USDC rescue, pause. Abstract hooks:_performSwap,_requireWired.GuardedBuybackBurner(abstract) — the shared MEV-defense stack lifted out of the Balancer contract: TWAPminOutfloor, governedslippageBps/min/max band, per-epoch USDC liquidity cap, keeper rotation. Venue is abstracted behind_spotPrice/_usdcDepthRaw/_swapFeeE18/_swap(+_requireWired).BuybackBurnerBalancerV3andBuybackBurnerUniswapV3— sibling venues binding the hooks. The Balancer Permit2 swap path is unchanged.FeeRouterneeds no change — it onlysafeTransfers the buyback USDC to thebuybackBurneraddress, so switching venues is onesetBuybackBurnergovernance call.BuybackBurnerUniswapV3exactInputSingleUSDC→TOKEN swap onSwapRouter02, scoped ERC20 router approval (V2-style; no Permit2 leg).slot0.sqrtPriceX96(not the pool's nativeobserve()oracle — keeps both burners on one TWAP impl and works on a freshly-seeded pool whose observation cardinality is still 1)._spotPricehandles both token orderings and the USDC decimal gap, unit-tested with exact sqrt-price vectors.setPoolfail-fast-validates the pool is a USDC/TOKEN pair with a live price.Rollout
Wire
BuybackBurnerUniswapV3on Arbitrum Sepolia now; swap toBuybackBurnerBalancerV3viasetBuybackBurneronce Balancer V3 lands there.Verification
forge fmt --check✓FOUNDRY_PROFILE=ci forge build --deny warnings✓forge test(non-fork): 654 passed, 0 failed, incl. 14 new Uniswap V3 tests and the unchanged Balancer suite as the refactor regression net.slither . --config-file slither.config.json: no medium+ findings (the new_spotPricetuple-destructureunused-returnis waived per the CLAUDE.md convention).Fork tests (gated, need an RPC) were not run locally.
🤖 Generated with Claude Code
Summary by CodeRabbit