// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {ERC4626} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol"; import {IUnlockCallback} from "v4-core/src/interfaces/callback/IUnlockCallback.sol"; import {IHooks} from "v4-core/src/interfaces/IHooks.sol"; import {PoolKey} from "v4-core/src/types/PoolKey.sol"; import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol"; import {Currency} from "v4-core/src/types/Currency.sol"; import {SwapParams} from "v4-core/src/types/PoolOperation.sol"; import {TickMath} from "v4-core/src/libraries/TickMath.sol"; import {TransientStateLibrary} from "v4-core/src/libraries/TransientStateLibrary.sol"; import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol"; import {XBurn} from "./XBurn.sol"; import {BurnToken} from "./BurnToken.sol"; /// @dev Minimal view interface needed to read the V4 pool from BurnHook (avoids importing the entire BurnHook). interface IBurnHookPool { function poolManager() external view returns (IPoolManager); function poolKey() external view returns (Currency currency0, Currency currency1, uint24 fee, int24 tickSpacing, IHooks hooks); } /// @title WrappedXBurn /// @notice Wraps xBURN into an ERC4626-compliant yield-bearing vault. /// /// Design: /// - asset() = xBURN /// - shares (wxBURN) ↔ xBURN ratio moves with totalAssets() / totalSupply() /// - totalAssets() = amount of xBURN held by the vault /// /// Value-accrual paths (two of them, both raise totalAssets → per-share NAV rises, all wxBURN holders benefit proportionally): /// A) Donation-style `compound(burnAmount)`: anyone donates BURN to the vault → vault calls `xBurn.enter()` to convert it into xBURN. /// B) Self-dividend compounding `compoundFromDividend(minBurnOut)`: harvest the vault's dividend WETH → take a 0.5% /// bounty for the caller → swap the rest for BURN through the protocol's own V4 pool, then enter(). The bounty makes it profitable for any bot to call, /// so gas is paid by the market, and it only triggers once enough has accrued (no gas wasted on dust). Slippage is enforced at 2% against the on-chain spot price. /// /// Underlying dividend (WETH) handling: /// - The vault holds xBURN, so underlying dividends accrue to the vault on its full position. /// - The keeper only needs to periodically call `compoundFromDividend(minBurnOut)` in one step: internally it first harvests (burning 1 wei of xBURN /// to trigger the underlying _settle, which collects pending WETH into the vault), then swaps for BURN through the protocol pool and enters, flowing the WETH back into NAV /// (the whole step is atomic; if the swap fails, the harvest is rolled back along with it, and the WETH stays safely in XBurn). /// - Note: WETH is not counted in NAV; only after compoundFromDividend/compound converts it back into xBURN does it show up as growth; /// standard 4626 operations deposit/withdraw/redeem never touch the WETH held in the vault. /// /// Compounding is optional: the vault can simply hold the position → wxBURN holders redeem to recover the underlying xBURN /// and then claim the underlying WETH themselves. But in that case NAV does not grow, and wxBURN serves only as a "standardized wrapper." /// /// ⚠️ Deployment note: if someone transfers xBURN directly to the vault before the first deposit, /// it inflates the sharePrice, and new entrants get burned by the artificially inflated exchange rate (the classic 4626 inflation attack). /// Production recommendation: right after deployment, have the deployer make a dust deposit (≥1e6 wei xBURN) to seed the vault. contract WrappedXBurn is ERC4626, ReentrancyGuard, IUnlockCallback { using SafeERC20 for IERC20; using TransientStateLibrary for IPoolManager; using StateLibrary for IPoolManager; using PoolIdLibrary for PoolKey; XBurn public immutable xBurnContract; BurnToken public immutable burnToken; IERC20 public immutable dividendToken; // keeper self-incentive + slippage protection parameters uint256 public constant KEEPER_BOUNTY_BPS = 50; // caller bounty 0.5% (skimmed from the harvested WETH) uint256 public constant MAX_SLIPPAGE_BPS = 200; // max swap slippage 2% (enforced on-chain against the spot price) uint256 public constant HOOK_FEE_BPS = 100; // BurnHook takes 1% WETH on every swap (deterministic, factored into the expected output) uint256 private constant BPS = 10_000; error NotPoolManager(); error NoDividend(); error Slippage(); event Compounded(address indexed caller, uint256 burnIn, uint256 xBurnGained); event CompoundedFromDividend( address indexed caller, uint256 wethSwapped, uint256 burnOut, uint256 xBurnGained, uint256 bounty ); constructor(XBurn _xBurn) ERC4626(IERC20(address(_xBurn))) ERC20("Wrapped xBURN", "wxBURN") { require(address(_xBurn) != address(0), "zero xBurn"); xBurnContract = _xBurn; burnToken = _xBurn.burn(); dividendToken = _xBurn.dividendToken(); } // ============ 4626 plumbing ============ /// @notice NAV basis: the amount of xBURN held by the vault. /// @dev Underlying pending WETH is not counted in totalAssets, to avoid NAV jumping in real time; /// WETH only shows up as xBURN growth after it has been flowed back via compound(). function totalAssets() public view override returns (uint256) { return xBurnContract.balanceOf(address(this)); } // ============ Compounding / dividend handling ============ /// @notice Anyone donates BURN → the vault calls xBurn.enter() to convert it into an underlying xBURN position. /// This directly raises totalAssets, and the per-share NAV rises in step. function compound(uint256 burnAmount) external returns (uint256 xBurnGained) { require(burnAmount > 0, "zero burn"); IERC20 burn_ = IERC20(address(burnToken)); burn_.safeTransferFrom(msg.sender, address(this), burnAmount); // reset approval to avoid possible non-standard ERC20 residue burn_.forceApprove(address(xBurnContract), burnAmount); uint256 before = xBurnContract.balanceOf(address(this)); xBurnContract.enter(burnAmount); xBurnGained = xBurnContract.balanceOf(address(this)) - before; emit Compounded(msg.sender, burnAmount, xBurnGained); } // ============ Compound from vault's own dividend (harvest + WETH → BURN via the protocol's own V4 pool) ============ /// @notice One-click compounding (self-incentivized): first collect the dividend WETH accrued by the underlying xBURN into the vault, take a 0.5% bounty for the caller, /// swap the rest into BURN through the protocol's own V4 BURN/WETH pool, and enter() it into more underlying xBURN → NAV rises. /// @dev The bounty makes this call profitable for any keeper/bot (someone will only call when bounty > gas) → gas is paid by the market, /// and it naturally only triggers once enough has accrued, never wasting gas on dust. /// Slippage protection **does not rely on the caller**: in unlockCallback it computes the minimum acceptable BURN out from the pool's current spot price /// (after deducting the known 1% hook fee, then leaving 2% slippage), enforced on-chain; the caller's `minBurnOut` only serves as an additional, stricter floor. /// Note: spot-price protection blocks normal slippage and obviously bad fills, but it is not a full TWAP oracle; since this call's amount is /// scattered dividends and can only route through the protocol pool, the room for front-running arbitrage is small and acceptable. /// Fully atomic throughout: if any step reverts, the bounty/harvest/swap are all rolled back, and the WETH stays safely in XBurn. /// @param minBurnOut caller's optional additional floor (pass 0 to use only the on-chain spot protection) function compoundFromDividend(uint256 minBurnOut) external nonReentrant returns (uint256 burnOut, uint256 xBurnGained, uint256 bounty) { _harvest(); uint256 wethAmount = dividendToken.balanceOf(address(this)); if (wethAmount == 0) revert NoDividend(); // keeper bounty: skim 0.5% of the harvested WETH for the caller (self-incentive, gas borne by the market) bounty = wethAmount * KEEPER_BOUNTY_BPS / BPS; uint256 wethToSwap = wethAmount - bounty; if (bounty > 0) dividendToken.safeTransfer(msg.sender, bounty); (IPoolManager pm,) = _poolInfo(); // unlock → unlockCallback performs the swap + settle/take (including spot-price slippage enforcement) burnOut = abi.decode(pm.unlock(abi.encode(wethToSwap, minBurnOut)), (uint256)); // use the swapped BURN to enter() into underlying xBURN, directly raising totalAssets / NAV IERC20 burn_ = IERC20(address(burnToken)); burn_.forceApprove(address(xBurnContract), burnOut); uint256 before = xBurnContract.balanceOf(address(this)); xBurnContract.enter(burnOut); xBurnGained = xBurnContract.balanceOf(address(this)) - before; emit CompoundedFromDividend(msg.sender, wethToSwap, burnOut, xBurnGained, bounty); } /// @notice The V4 PoolManager's unlock callback; should only be triggered by the PoolManager within the compoundFromDividend flow. function unlockCallback(bytes calldata data) external override returns (bytes memory) { (IPoolManager pm, PoolKey memory key) = _poolInfo(); if (msg.sender != address(pm)) revert NotPoolManager(); (uint256 wethToSwap, uint256 callerMinOut) = abi.decode(data, (uint256, uint256)); Currency wethCur = Currency.wrap(address(dividendToken)); Currency burnCur = Currency.wrap(address(burnToken)); bool burnIsToken0 = address(burnToken) < address(dividendToken); // WETH → BURN: zeroForOne = (currency0 is WETH) = (WETH address < BURN address) bool zeroForOne = !burnIsToken0; // compute the minimum acceptable BURN out on-chain from the spot price (deduct 1% hook fee + leave 2% slippage); take whichever is stricter against the caller's floor uint256 minOut = _spotMinBurnOut(pm, key, wethToSwap, burnIsToken0); if (callerMinOut > minOut) minOut = callerMinOut; pm.swap( key, SwapParams({ zeroForOne: zeroForOne, amountSpecified: -int256(wethToSwap), // negative = exact input sqrtPriceLimitX96: zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1 }), "" ); // settle precisely using the transient currencyDelta (automatically accounts for the hook's 1% fee) int256 wethDelta = pm.currencyDelta(address(this), wethCur); // <0 = vault owes int256 burnDelta = pm.currencyDelta(address(this), burnCur); // >0 = vault can take if (wethDelta < 0) { pm.sync(wethCur); IERC20(address(dividendToken)).safeTransfer(address(pm), uint256(-wethDelta)); pm.settle(); } if (burnDelta <= 0) revert Slippage(); uint256 outAmt = uint256(burnDelta); if (outAmt < minOut) revert Slippage(); pm.take(burnCur, address(this), outAmt); return abi.encode(outAmt); } /// @dev Collect the vault's pending dividend WETH accrued in XBurn into the vault. /// claim(1) burns 1 wei of xBURN to trigger xBurn._update→_settle, pushing all of the vault's pending WETH over. /// Only burns when there is genuinely pending WETH, to avoid pointless dust. function _harvest() internal { if ( xBurnContract.balanceOf(address(this)) > 0 && xBurnContract.pendingDividend(address(this)) > 0 ) { xBurnContract.claim(1); } } /// @dev Compute the minimum acceptable output for swapping `wethIn` WETH into BURN at the pool's current spot price: /// first deduct the 1% WETH that BurnHook deterministically takes on this swap, then convert the remainder at the spot price, and finally leave 2% slippage. /// sqrtPriceX96 represents sqrt(token1/token0)·2^96. WETH→BURN: /// · burnIsToken0: BURN/WETH = 2^192 / P^2 → out = wethEff·2^192/P^2 /// · otherwise : BURN/WETH = P^2 / 2^192 → out = wethEff·P^2/2^192 /// Chain two Math.mulDiv(·,2^96,·) calls to avoid overflow of P^2 (which can reach 2^320). function _spotMinBurnOut(IPoolManager pm, PoolKey memory key, uint256 wethIn, bool burnIsToken0) internal view returns (uint256) { (uint160 sqrtPriceX96,,,) = pm.getSlot0(key.toId()); uint256 p = uint256(sqrtPriceX96); uint256 q96 = 1 << 96; uint256 wethEff = wethIn * (BPS - HOOK_FEE_BPS) / BPS; // deduct 1% hook fee uint256 expectedOut = burnIsToken0 ? Math.mulDiv(Math.mulDiv(wethEff, q96, p), q96, p) // wethEff·2^192/P^2 : Math.mulDiv(Math.mulDiv(wethEff, p, q96), p, q96); // wethEff·P^2/2^192 return expectedOut * (BPS - MAX_SLIPPAGE_BPS) / BPS; // leave 2% slippage } /// @dev Read the V4 PoolManager and the BURN/WETH PoolKey via xBURN → hook. /// Read lazily (not in the constructor) to remain compatible with unit tests that use a mock hook. function _poolInfo() internal view returns (IPoolManager pm, PoolKey memory key) { IBurnHookPool h = IBurnHookPool(xBurnContract.hook()); pm = h.poolManager(); (Currency c0, Currency c1, uint24 fee, int24 ts, IHooks hooks) = h.poolKey(); key = PoolKey({currency0: c0, currency1: c1, fee: fee, tickSpacing: ts, hooks: hooks}); } // ============ Inflation-attack mitigation ============ /// @dev Add 3 extra decimals to shares to reduce the effectiveness of the attack that inflates sharePrice via a direct transfer before the first dust deposit. /// OZ 4626 defaults to 0; we raise it to 3 (about a 1000x buffer), close to the common configuration for USDC vaults. function _decimalsOffset() internal pure override returns (uint8) { return 3; } }