Repository navigation
feat(contracts): live Balancer V3 swap binding for BuybackBurner (#686) - #898
Conversation
Implements the concrete `BuybackBurnerBalancerV3` subclass with the full
on-chain MEV-defense stack: single-swap `_performSwap` via the Balancer V3
Router (`swapSingleTokenExactIn`), scoped Vault approval (approve the Vault,
call the Router), a governed `slippageBps`/`minBuybackAmount`/`maxBuybackAmount`
band, an on-chain per-epoch USDC liquidity cap, and a fee-aware on-chain TWAP
`minOut` floor backed by a self-maintained cumulative-price accumulator (V3 has
no built-in oracle; permissionless `poke()`, fail-closed `TwapNotReady`). The
effective minimum is `max(twapFloor, keeper minOut)`; the floor nets the pool's
swap fee (read live from the Vault) before the slippage discount.
Activates the previously-inert buyback-and-burn bucket: `BuybackBurner` was
abstract and `executeBuyback` reverted `SwapNotImplemented`, so the FeeRouter
buyback share shipped at 0%. Adds `ActivateBuyback.s.sol` (deploys the subclass,
emits the timelocked governance calldata) — launch surface stays dormant.
- Vendors minimal `IBalancerV3{Router,Vault,WeightedPool}` interfaces.
- 28 tests: swap+burn, TWAP floor/fail-closed/spike-resistance/multi-window,
fee accounting, per-epoch cap accrual+reset, scoped-approval lifecycle,
reversed/3-token/missing-leg pool reads, governance setters, constructor bounds.
- Reconciles ADR 018 (router surface, TWAP mechanism, max(floor,minOut),
scoped approval) and ADR 003 (canonical IBuybackBurner surface).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Gas snapshotGas changes vs baseRun: 27478771169 |
Contracts coverageLine coverage: 89.46% (2020/2258 lines) |
There was a problem hiding this comment.
Code Review
This pull request implements the concrete BuybackBurnerBalancerV3 contract, integrating it with Balancer V3 to execute protocol token buybacks and burns. It updates the architectural decision records (ADRs) to detail the on-chain TWAP floor mechanism, scoped per-swap approvals, and keeper-side coordination. Additionally, it introduces deployment scripts, minimal Balancer V3 interfaces, and comprehensive tests. The feedback suggests adding a check in the permissionless poke() function to verify that the Balancer pool and vault are wired before updating the TWAP accumulator, preventing low-level reverts when they are uninitialized.
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 makes the buyback-and-burn path deployable by adding a concrete BuybackBurner implementation that performs a Balancer V3 single-swap USDC→TOKEN and enforces the on-chain MEV-defense checks described in ADR 018 (TWAP floor, per-epoch cap, and governance bounds). It also adds an operator script to deploy the burner and print the governance calldata needed to activate the FeeRouter buyback bucket, plus comprehensive tests and ADR updates.
Changes:
- Add
BuybackBurnerBalancerV3implementing_performSwapwith scoped Vault approvals, TWAP accumulator + floor, and epoch liquidity cap enforcement. - Add minimal Balancer V3 interfaces (Router/Vault/WeightedPool) and a new activation script that prints timelock-schedulable calldata.
- Add a full test suite covering swap/burn, TWAP behavior, fee-aware floor, epoch cap, approval scoping, pool leg matching robustness, and governance setters; update ADR 018 and ADR 003 accordingly.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| contracts/src/BuybackBurnerBalancerV3.sol | Concrete Balancer V3 buyback burner implementation with TWAP/cap/approval MEV defenses and governance setters. |
| contracts/src/interfaces/IBalancerV3Router.sol | Minimal Router interface used for swapSingleTokenExactIn. |
| contracts/src/interfaces/IBalancerV3Vault.sol | Minimal Vault read interface used for pool tokens, live balances, and swap fee. |
| contracts/src/interfaces/IBalancerV3WeightedPool.sol | Minimal weighted pool interface for normalized weights used in spot/TWAP math. |
| contracts/test/BuybackBurnerBalancerV3.t.sol | New test suite using Vault/Router mocks to validate swap path + defenses + governance. |
| contracts/script/ActivateBuyback.s.sol | Operator runbook script to deploy burner and print governance calldata for activation. |
| adr/018-liquidity-strategy.md | ADR update documenting the shipped swap binding and the on-chain TWAP floor mechanics. |
| adr/003-payments.md | ADR update to the canonical BuybackBurner interface description (including new setters/poke). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
…cimals, docs)
- poke(): revert PoolNotWired() when pool/vault unwired (clear error vs an
opaque ABI-decode revert from the zero-address pool read). [gemini]
- _spotPrice(): nest Math.mulDiv so neither product is formed in plain uint256,
removing the latent pre-multiplication overflow for large pools. [copilot]
- constructor: explicit UnsupportedTokenDecimals revert when USDC decimals() > 18
instead of a generic arithmetic-underflow panic. [copilot]
- IBalancerV3WeightedPool: fix the inverted spot-price formula in the docstring
to TOKEN-per-USDC, matching _spotPrice. [copilot]
- test: correct MockBalancerV3Router docstring ("records", not "asserts") and add
coverage for the decimals guard and the poke-unwired revert.
aderyn flags the constructor decimals read as reentrancy-state-change — a false
positive (a constructor cannot be reentered, the write is to an immutable);
suppressed with a justified aderyn-ignore directive.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Security hardening: `_twapFloor` reads the pool swap fee from the Vault and discounts the floor by `(WAD - feeE18)`. A degenerate `feeE18 == WAD` (100%) collapses the floor to 0 — making the `minOut >= twapFloor` guard vacuous (fail-open) — while `feeE18 > WAD` already reverts via checked underflow. Reject `feeE18 >= WAD` explicitly (real Balancer pools cap the fee well below 100%), same fail-closed posture as the `wUsdc == 0` pool-state guard. Adds `test_executeBuyback_revertsOnDegenerateSwapFee`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
What & why
Closes #686.
BuybackBurnershipped abstract —executeBuybackrevertedSwapNotImplemented, so the FeeRouter buyback bucket ran at 0% and buyback-and-burn (a prod-blocking economic primitive) was inert. This adds the concrete, deployableBuybackBurnerBalancerV3with the full on-chain MEV-defense stack chosen for this PR.The base
BuybackBurner.executeBuybackstays the entry point (keeps itsnonReentrantguard, actual-TOKEN-balance-delta verification, and burn); the subclass overrides only_performSwap. All MEV-stack checks run checks-effects-interactions, before the Router call.Design
Router.swapSingleTokenExactIn; TWAP sub-swap cadence is keeper-side (ADR 018).forceApprove(vault, amountIn)→ swap → reset0. Approve the Vault, call the Router (verified against Balancer V3 docs).minOutfloor — V3 has no built-in oracle and TOKEN has no external feed at launch, so a self-maintained cumulative-price accumulator (Uniswap-V2 style) over pool spot, sampled pre-swap, advanceable via permissionlesspoke(), fail-closedTwapNotReadyuntil it spanstwapMinWindow(floored at 30 min). The floor nets the pool swap fee (read live from the Vault) before the slippage discount; effective minimum =max(twapFloor, keeper minOut).epochLiquidityCapFraction(default 10%, bounded[1%,30%]) of epoch-start in-pool depth, 7-day epochs aligned to FeeRouter/CapacityBond.slippageBps/minBuybackAmount/maxBuybackAmount(withmin <= maxinvariant),setKeeperrole rotation,setSwapRouter.DeployProtocolunchanged (bucket dormant, shares[9000,0,1000]); newActivateBuyback.s.soldeploys the subclass and prints the two timelocked governance calls (setSharesAndDestinations([6000,3000,1000], …),setKeeper). The script holds no role.Tests
28 cases: swap+burn+event, TWAP floor /
TwapNotReady/ single-block spike resistance / multi-window anchor slide, fee accounting, per-epoch cap accrual+reset across epochs, scoped-approval set-then-zero, reversed / 3-token / missing-leg pool reads (address-matched, not index), all governance setters' access-control + bounds, constructor reverts (zero router, cap-fraction, twap-window, inverted band), pause.Reviews incorporated
Multi-agent review (code/tests/comments/silent-failure/types) + a Solidity security pass. Fixed: swap-fee-unaware floor (would self-DoS near
maxBuybackAmount),twapMinWindowlower bound,_poolStatewUsdc==0guard,min<=maxinvariant, comment accuracy. Documented residuals: per-epoch cap uses instantaneous depth (bounded griefing, covered by the private-RPC keeper mandate);deadline=block.timestamprelies on private-RPC + the floor.ADR reconciliation
ADR 018 (router surface, self-maintained TWAP mechanism,
max(floor,minOut), scoped approval) and ADR 003 (canonicalIBuybackBurnersurface). Source of truth per workspace CLAUDE.md.Verification
forge fmt --check·FOUNDRY_PROFILE=ci forge build --sizes --deny warnings(runtime margin ~15.8 KB) ·forge test(567 total) · solhint (0 errors) · slither (no medium+) · aderyn (no High) · pre-commit — all green.Follow-ups (deferred, non-blocking)
EpochCap/TwapState) to clear the non-fatal solhintmax-states-countwarning and tighten invariants.Configfield right-sizing /BpsUDVT for compile-time unit safety (the node: type-encode the seed-leech cap units (Bytes/Percent newtypes) to close the config→LeechCaps confusion seam #894 instinct in Solidity).🤖 Generated with Claude Code