🔥
BurnHookBNB Chain
Contract Source
Full source of every core contract, identical to the version deployed and verified on BscScan. All contracts are non-upgradeable with no admin after launch.
src/WrappedXBurn.sol
wxBURN: ERC4626 wrapper of xBURN, auto-compounding, DEX-safe
261 linessolc 0.8.26 · via-ir · optimizer 200sha256 61026d195c1a00e8…Not deployed yet
1// SPDX-License-Identifier: MIT2pragma solidity ^0.8.26;4import {ERC4626} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";5import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";6import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";7import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";8import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";9import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";11import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";12import {IUnlockCallback} from "v4-core/src/interfaces/callback/IUnlockCallback.sol";13import {IHooks} from "v4-core/src/interfaces/IHooks.sol";14import {PoolKey} from "v4-core/src/types/PoolKey.sol";15import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";16import {Currency} from "v4-core/src/types/Currency.sol";17import {SwapParams} from "v4-core/src/types/PoolOperation.sol";18import {TickMath} from "v4-core/src/libraries/TickMath.sol";19import {TransientStateLibrary} from "v4-core/src/libraries/TransientStateLibrary.sol";20import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";22import {XBurn} from "./XBurn.sol";23import {BurnToken} from "./BurnToken.sol";25/// @dev Minimal view interface needed to read the V4 pool from BurnHook (avoids importing the entire BurnHook).26interface IBurnHookPool {27 function poolManager() external view returns (IPoolManager);28 function poolKey()29 external30 view31 returns (Currency currency0, Currency currency1, uint24 fee, int24 tickSpacing, IHooks hooks);32}34/// @title WrappedXBurn35/// @notice Wraps xBURN into an ERC4626-compliant yield-bearing vault.36///37/// Design:38/// - asset() = xBURN39/// - shares (wxBURN) ↔ xBURN ratio moves with totalAssets() / totalSupply()40/// - totalAssets() = amount of xBURN held by the vault41///42/// Value-accrual paths (two of them, both raise totalAssets → per-share NAV rises, all wxBURN holders benefit proportionally):43/// A) Donation-style `compound(burnAmount)`: anyone donates BURN to the vault → vault calls `xBurn.enter()` to convert it into xBURN.44/// B) Self-dividend compounding `compoundFromDividend(minBurnOut)`: harvest the vault's dividend WETH → take a 0.5%45/// 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,46/// 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.47///48/// Underlying dividend (WETH) handling:49/// - The vault holds xBURN, so underlying dividends accrue to the vault on its full position.50/// - The keeper only needs to periodically call `compoundFromDividend(minBurnOut)` in one step: internally it first harvests (burning 1 wei of xBURN51/// 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 NAV52/// (the whole step is atomic; if the swap fails, the harvest is rolled back along with it, and the WETH stays safely in XBurn).53/// - Note: WETH is not counted in NAV; only after compoundFromDividend/compound converts it back into xBURN does it show up as growth;54/// standard 4626 operations deposit/withdraw/redeem never touch the WETH held in the vault.55///56/// Compounding is optional: the vault can simply hold the position → wxBURN holders redeem to recover the underlying xBURN57/// and then claim the underlying WETH themselves. But in that case NAV does not grow, and wxBURN serves only as a "standardized wrapper."58///59/// ⚠️ Deployment note: if someone transfers xBURN directly to the vault before the first deposit,60/// it inflates the sharePrice, and new entrants get burned by the artificially inflated exchange rate (the classic 4626 inflation attack).61/// Production recommendation: right after deployment, have the deployer make a dust deposit (≥1e6 wei xBURN) to seed the vault.62contract WrappedXBurn is ERC4626, ReentrancyGuard, IUnlockCallback {63 using SafeERC20 for IERC20;64 using TransientStateLibrary for IPoolManager;65 using StateLibrary for IPoolManager;66 using PoolIdLibrary for PoolKey;68 XBurn public immutable xBurnContract;69 BurnToken public immutable burnToken;70 IERC20 public immutable dividendToken;72 // keeper self-incentive + slippage protection parameters73 uint256 public constant KEEPER_BOUNTY_BPS = 50; // caller bounty 0.5% (skimmed from the harvested WETH)74 uint256 public constant MAX_SLIPPAGE_BPS = 200; // max swap slippage 2% (enforced on-chain against the spot price)75 uint256 public constant HOOK_FEE_BPS = 100; // BurnHook takes 1% WETH on every swap (deterministic, factored into the expected output)76 uint256 private constant BPS = 10_000;78 error NotPoolManager();79 error NoDividend();80 error Slippage();82 event Compounded(address indexed caller, uint256 burnIn, uint256 xBurnGained);83 event CompoundedFromDividend(84 address indexed caller, uint256 wethSwapped, uint256 burnOut, uint256 xBurnGained, uint256 bounty85 );87 constructor(XBurn _xBurn)88 ERC4626(IERC20(address(_xBurn)))89 ERC20("Wrapped xBURN", "wxBURN")90 {91 require(address(_xBurn) != address(0), "zero xBurn");92 xBurnContract = _xBurn;93 burnToken = _xBurn.burn();94 dividendToken = _xBurn.dividendToken();95 }97 // ============ 4626 plumbing ============99 /// @notice NAV basis: the amount of xBURN held by the vault.100 /// @dev Underlying pending WETH is not counted in totalAssets, to avoid NAV jumping in real time;101 /// WETH only shows up as xBURN growth after it has been flowed back via compound().102 function totalAssets() public view override returns (uint256) {103 return xBurnContract.balanceOf(address(this));104 }106 // ============ Compounding / dividend handling ============108 /// @notice Anyone donates BURN → the vault calls xBurn.enter() to convert it into an underlying xBURN position.109 /// This directly raises totalAssets, and the per-share NAV rises in step.110 function compound(uint256 burnAmount) external returns (uint256 xBurnGained) {111 require(burnAmount > 0, "zero burn");112 IERC20 burn_ = IERC20(address(burnToken));113 burn_.safeTransferFrom(msg.sender, address(this), burnAmount);114 // reset approval to avoid possible non-standard ERC20 residue115 burn_.forceApprove(address(xBurnContract), burnAmount);117 uint256 before = xBurnContract.balanceOf(address(this));118 xBurnContract.enter(burnAmount);119 xBurnGained = xBurnContract.balanceOf(address(this)) - before;121 emit Compounded(msg.sender, burnAmount, xBurnGained);122 }124 // ============ Compound from vault's own dividend (harvest + WETH → BURN via the protocol's own V4 pool) ============126 /// @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,127 /// swap the rest into BURN through the protocol's own V4 BURN/WETH pool, and enter() it into more underlying xBURN → NAV rises.128 /// @dev The bounty makes this call profitable for any keeper/bot (someone will only call when bounty > gas) → gas is paid by the market,129 /// and it naturally only triggers once enough has accrued, never wasting gas on dust.130 /// Slippage protection **does not rely on the caller**: in unlockCallback it computes the minimum acceptable BURN out from the pool's current spot price131 /// (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.132 /// Note: spot-price protection blocks normal slippage and obviously bad fills, but it is not a full TWAP oracle; since this call's amount is133 /// scattered dividends and can only route through the protocol pool, the room for front-running arbitrage is small and acceptable.134 /// Fully atomic throughout: if any step reverts, the bounty/harvest/swap are all rolled back, and the WETH stays safely in XBurn.135 /// @param minBurnOut caller's optional additional floor (pass 0 to use only the on-chain spot protection)136 function compoundFromDividend(uint256 minBurnOut)137 external138 nonReentrant139 returns (uint256 burnOut, uint256 xBurnGained, uint256 bounty)140 {141 _harvest();143 uint256 wethAmount = dividendToken.balanceOf(address(this));144 if (wethAmount == 0) revert NoDividend();146 // keeper bounty: skim 0.5% of the harvested WETH for the caller (self-incentive, gas borne by the market)147 bounty = wethAmount * KEEPER_BOUNTY_BPS / BPS;148 uint256 wethToSwap = wethAmount - bounty;149 if (bounty > 0) dividendToken.safeTransfer(msg.sender, bounty);151 (IPoolManager pm,) = _poolInfo();152 // unlock → unlockCallback performs the swap + settle/take (including spot-price slippage enforcement)153 burnOut = abi.decode(pm.unlock(abi.encode(wethToSwap, minBurnOut)), (uint256));155 // use the swapped BURN to enter() into underlying xBURN, directly raising totalAssets / NAV156 IERC20 burn_ = IERC20(address(burnToken));157 burn_.forceApprove(address(xBurnContract), burnOut);158 uint256 before = xBurnContract.balanceOf(address(this));159 xBurnContract.enter(burnOut);160 xBurnGained = xBurnContract.balanceOf(address(this)) - before;162 emit CompoundedFromDividend(msg.sender, wethToSwap, burnOut, xBurnGained, bounty);163 }165 /// @notice The V4 PoolManager's unlock callback; should only be triggered by the PoolManager within the compoundFromDividend flow.166 function unlockCallback(bytes calldata data) external override returns (bytes memory) {167 (IPoolManager pm, PoolKey memory key) = _poolInfo();168 if (msg.sender != address(pm)) revert NotPoolManager();170 (uint256 wethToSwap, uint256 callerMinOut) = abi.decode(data, (uint256, uint256));172 Currency wethCur = Currency.wrap(address(dividendToken));173 Currency burnCur = Currency.wrap(address(burnToken));174 bool burnIsToken0 = address(burnToken) < address(dividendToken);175 // WETH → BURN: zeroForOne = (currency0 is WETH) = (WETH address < BURN address)176 bool zeroForOne = !burnIsToken0;178 // 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 floor179 uint256 minOut = _spotMinBurnOut(pm, key, wethToSwap, burnIsToken0);180 if (callerMinOut > minOut) minOut = callerMinOut;182 pm.swap(183 key,184 SwapParams({185 zeroForOne: zeroForOne,186 amountSpecified: -int256(wethToSwap), // negative = exact input187 sqrtPriceLimitX96: zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1188 }),189 ""190 );192 // settle precisely using the transient currencyDelta (automatically accounts for the hook's 1% fee)193 int256 wethDelta = pm.currencyDelta(address(this), wethCur); // <0 = vault owes194 int256 burnDelta = pm.currencyDelta(address(this), burnCur); // >0 = vault can take196 if (wethDelta < 0) {197 pm.sync(wethCur);198 IERC20(address(dividendToken)).safeTransfer(address(pm), uint256(-wethDelta));199 pm.settle();200 }202 if (burnDelta <= 0) revert Slippage();203 uint256 outAmt = uint256(burnDelta);204 if (outAmt < minOut) revert Slippage();205 pm.take(burnCur, address(this), outAmt);207 return abi.encode(outAmt);208 }210 /// @dev Collect the vault's pending dividend WETH accrued in XBurn into the vault.211 /// claim(1) burns 1 wei of xBURN to trigger xBurn._update→_settle, pushing all of the vault's pending WETH over.212 /// Only burns when there is genuinely pending WETH, to avoid pointless dust.213 function _harvest() internal {214 if (215 xBurnContract.balanceOf(address(this)) > 0216 && xBurnContract.pendingDividend(address(this)) > 0217 ) {218 xBurnContract.claim(1);219 }220 }222 /// @dev Compute the minimum acceptable output for swapping `wethIn` WETH into BURN at the pool's current spot price:223 /// 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.224 /// sqrtPriceX96 represents sqrt(token1/token0)·2^96. WETH→BURN:225 /// · burnIsToken0: BURN/WETH = 2^192 / P^2 → out = wethEff·2^192/P^2226 /// · otherwise : BURN/WETH = P^2 / 2^192 → out = wethEff·P^2/2^192227 /// Chain two Math.mulDiv(·,2^96,·) calls to avoid overflow of P^2 (which can reach 2^320).228 function _spotMinBurnOut(IPoolManager pm, PoolKey memory key, uint256 wethIn, bool burnIsToken0)229 internal230 view231 returns (uint256)232 {233 (uint160 sqrtPriceX96,,,) = pm.getSlot0(key.toId());234 uint256 p = uint256(sqrtPriceX96);235 uint256 q96 = 1 << 96;236 uint256 wethEff = wethIn * (BPS - HOOK_FEE_BPS) / BPS; // deduct 1% hook fee238 uint256 expectedOut = burnIsToken0239 ? Math.mulDiv(Math.mulDiv(wethEff, q96, p), q96, p) // wethEff·2^192/P^2240 : Math.mulDiv(Math.mulDiv(wethEff, p, q96), p, q96); // wethEff·P^2/2^192242 return expectedOut * (BPS - MAX_SLIPPAGE_BPS) / BPS; // leave 2% slippage243 }245 /// @dev Read the V4 PoolManager and the BURN/WETH PoolKey via xBURN → hook.246 /// Read lazily (not in the constructor) to remain compatible with unit tests that use a mock hook.247 function _poolInfo() internal view returns (IPoolManager pm, PoolKey memory key) {248 IBurnHookPool h = IBurnHookPool(xBurnContract.hook());249 pm = h.poolManager();250 (Currency c0, Currency c1, uint24 fee, int24 ts, IHooks hooks) = h.poolKey();251 key = PoolKey({currency0: c0, currency1: c1, fee: fee, tickSpacing: ts, hooks: hooks});252 }254 // ============ Inflation-attack mitigation ============256 /// @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.257 /// OZ 4626 defaults to 0; we raise it to 3 (about a 1000x buffer), close to the common configuration for USDC vaults.258 function _decimalsOffset() internal pure override returns (uint8) {259 return 3;260 }261}