// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol"; import {Hooks} from "v4-core/src/libraries/Hooks.sol"; import {IHooks} from "v4-core/src/interfaces/IHooks.sol"; import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol"; import {ModifyLiquidityParams, SwapParams} from "v4-core/src/types/PoolOperation.sol"; import {PoolKey} from "v4-core/src/types/PoolKey.sol"; import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol"; import {Currency, CurrencyLibrary} from "v4-core/src/types/Currency.sol"; import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol"; import {BeforeSwapDelta, BeforeSwapDeltaLibrary, toBeforeSwapDelta} from "v4-core/src/types/BeforeSwapDelta.sol"; import {LPFeeLibrary} from "v4-core/src/libraries/LPFeeLibrary.sol"; import {TickMath} from "v4-core/src/libraries/TickMath.sol"; import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {IPositionManager} from "v4-periphery/src/interfaces/IPositionManager.sol"; import {Actions} from "v4-periphery/src/libraries/Actions.sol"; import {LiquidityAmounts} from "v4-periphery/src/libraries/LiquidityAmounts.sol"; import {IWETH9} from "v4-periphery/src/interfaces/external/IWETH9.sol"; import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol"; import {BurnToken} from "./BurnToken.sol"; import {IBurnToken} from "./interfaces/IBurnToken.sol"; import {XBurn} from "./XBurn.sol"; /// @title BurnHook /// @notice The core hook of the entire protocol, responsible for: /// 1. finalize() automatic pool creation (BURN/WETH or BURN/WBNB, 1% fee, full-range, LP burn) /// 2. Trading launch delay check /// 3. swap fee skimming (1% of the paired token) and injecting it into the XBurn dividend pool /// 4. Locking down LP add permission (only allowing the contract itself to create the pool) contract BurnHook is BaseHook, ReentrancyGuard { using PoolIdLibrary for PoolKey; using StateLibrary for IPoolManager; using CurrencyLibrary for Currency; using SafeERC20 for IERC20; // ============ Constants ============ uint24 public constant POOL_FEE = 0; // 0% LP fee — the 1% protocol dividend is entirely skimmed by the hook inside before/afterSwap int24 public constant TICK_SPACING = 200; // Used only for full-range LP; tickSpacing and fee are decoupled in V4, so keeping 200 has no effect address public constant DEAD = 0x000000000000000000000000000000000000dEaD; // ============ Immutables ============ BurnToken public immutable burn; IWETH9 public immutable wrappedNative; // WETH or WBNB address public immutable positionManager; IAllowanceTransfer public immutable permit2; // ============ State ============ XBurn public xBurn; // Deployed during finalize PoolKey public poolKey; PoolId public poolId; bool public finalized; bool internal _bondingInProgress; // Used to bypass the beforeAddLiquidity check // ============ Errors ============ error NotBurnToken(); error AlreadyFinalized(); error NotSuccess(); error LiquidityLocked(); error TradingNotOpen(); error InitNotAllowed(); // ============ Events ============ event Finalized(address indexed pool, uint256 ethToLP, uint256 burnToLP, address indexed xBurnAddr); event FeeCollected(uint256 amount); event LPBurned(uint256 tokenId); // tokenId is only an on-chain index; the LP NFT is minted directly → DEAD // ============ Constructor ============ constructor( IPoolManager _manager, address _burn, address _wrappedNative, address _positionManager, address _permit2 ) BaseHook(_manager) { require( _burn != address(0) && _wrappedNative != address(0) && _positionManager != address(0) && _permit2 != address(0), "zero addr" ); burn = BurnToken(payable(_burn)); wrappedNative = IWETH9(_wrappedNative); positionManager = _positionManager; permit2 = IAllowanceTransfer(_permit2); } // ============ Hook Permissions ============ function getHookPermissions() public pure override returns (Hooks.Permissions memory) { return Hooks.Permissions({ beforeInitialize: true, afterInitialize: false, beforeAddLiquidity: true, afterAddLiquidity: false, beforeRemoveLiquidity: false, afterRemoveLiquidity: false, beforeSwap: true, afterSwap: true, beforeDonate: false, afterDonate: false, beforeSwapReturnDelta: true, afterSwapReturnDelta: true, afterAddLiquidityReturnDelta: false, afterRemoveLiquidityReturnDelta: false }); } // ============ Finalize ============ /// @notice Callable by anyone; triggers the automatic pool creation flow /// @dev No caller reward; the originally reserved finalize reward has been removed, and this portion of ETH is entirely merged into the LP function finalize() external nonReentrant { if (finalized) revert AlreadyFinalized(); if (burn.currentPhase() != IBurnToken.Phase.MINT_SUCCESS) revert NotSuccess(); finalized = true; // 1. Trigger the BurnToken state transition, receiving the LP reserve token + ETH (only the referral reward reserve is deducted) (uint256 ethForLP, uint256 burnForLP) = burn.bondingFinalize(); // 2. Deploy the XBurn contract xBurn = new XBurn(address(burn), address(wrappedNative), address(this)); // 3. wrap ETH -> WETH wrappedNative.deposit{value: ethForLP}(); // 4. Construct the PoolKey Currency c0; Currency c1; bool burnIsToken0 = address(burn) < address(wrappedNative); if (burnIsToken0) { c0 = Currency.wrap(address(burn)); c1 = Currency.wrap(address(wrappedNative)); } else { c0 = Currency.wrap(address(wrappedNative)); c1 = Currency.wrap(address(burn)); } PoolKey memory key = PoolKey({ currency0: c0, currency1: c1, fee: POOL_FEE, tickSpacing: TICK_SPACING, hooks: IHooks(address(this)) }); poolKey = key; poolId = key.toId(); // 5. Initialize the pool; sqrtPriceX96 is determined by the current burnForLP / ethForLP uint160 sqrtPriceX96 = _computeSqrtPriceX96(burnForLP, ethForLP, burnIsToken0); _bondingInProgress = true; poolManager.initialize(key, sqrtPriceX96); // 6. Add full-range liquidity (actually done via the PositionManager, with the LP NFT transferred directly to DEAD) // Placeholder used before testnet/audit — real integration must be written against the V4 PositionManager ABI _addFullRangeLiquidityAndBurn(key, burnForLP, ethForLP); _bondingInProgress = false; emit Finalized(address(0), ethForLP, burnForLP, address(xBurn)); } /// @dev Compute the pool's sqrtPriceX96. token0 = burnIsToken0 ? BURN : WETH /// price = token1/token0 ; sqrtPriceX96 = sqrt(price) · 2^96 = sqrt(num · 2^192 / den) /// Use OZ Math.mulDiv to compute ratioX192 within a 512-bit intermediate result, avoiding `num << 192` overflowing uint256 under real amounts. function _computeSqrtPriceX96(uint256 burnAmt, uint256 ethAmt, bool burnIsToken0) internal pure returns (uint160) { (uint256 numerator, uint256 denominator) = burnIsToken0 ? (ethAmt, burnAmt) : (burnAmt, ethAmt); uint256 ratioX192 = Math.mulDiv(numerator, 1 << 192, denominator); return uint160(Math.sqrt(ratioX192)); } /// @dev Add full-range liquidity and permanently burn the LP NFT to DEAD. /// The V4 PositionManager uses a two-layer Permit2 authorization + an Actions command stream. function _addFullRangeLiquidityAndBurn( PoolKey memory key, uint256 burnForLP, uint256 ethForLP ) internal { // ─── ① Two-layer approve: hook → Permit2 → PositionManager ─── IERC20(address(burn)).forceApprove(address(permit2), type(uint256).max); IERC20(address(wrappedNative)).forceApprove(address(permit2), type(uint256).max); permit2.approve(address(burn), positionManager, type(uint160).max, type(uint48).max); permit2.approve(address(wrappedNative), positionManager, type(uint160).max, type(uint48).max); // ─── ② Compute full-range liquidity ─── int24 tickLower = TickMath.minUsableTick(key.tickSpacing); int24 tickUpper = TickMath.maxUsableTick(key.tickSpacing); (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(key.toId()); bool burnIsToken0 = address(burn) < address(wrappedNative); (uint256 amount0Max, uint256 amount1Max) = burnIsToken0 ? (burnForLP, ethForLP) : (ethForLP, burnForLP); uint128 liquidity = LiquidityAmounts.getLiquidityForAmounts( sqrtPriceX96, TickMath.getSqrtPriceAtTick(tickLower), TickMath.getSqrtPriceAtTick(tickUpper), amount0Max, amount1Max ); // ─── ③ Construct the Actions command stream: MINT_POSITION + SETTLE_PAIR ─── bytes memory actions = abi.encodePacked( uint8(Actions.MINT_POSITION), uint8(Actions.SETTLE_PAIR) ); bytes[] memory params = new bytes[](2); params[0] = abi.encode( key, tickLower, tickUpper, liquidity, amount0Max, // amount0Max (slippage cap) amount1Max, // amount1Max (slippage cap) DEAD, // recipient: mint the NFT directly to DEAD, making the LP permanently unwithdrawable bytes("") // hookData ); params[1] = abi.encode(key.currency0, key.currency1); // ─── ④ Call the PositionManager: mint lands directly on DEAD, no intermediate transfer needed ─── // The V4 PositionManager uses OZ _mint (not _safeMint), and DEAD is an EOA, so it passes the ZeroAddress check uint256 tokenId = IPositionManager(positionManager).nextTokenId(); IPositionManager(positionManager).modifyLiquidities( abi.encode(actions, params), block.timestamp ); emit LPBurned(tokenId); } // ============ Hook Callbacks ============ function _beforeInitialize(address sender, PoolKey calldata, uint160) internal view override returns (bytes4) { // Only allow the contract itself (the finalize flow) to initialize the pool if (sender != address(this)) revert InitNotAllowed(); return BaseHook.beforeInitialize.selector; } function _beforeAddLiquidity( address sender, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata ) internal view override returns (bytes4) { // Only allow the finalize flow to add LP (self-call and the bonding flag is true) if (!_bondingInProgress) revert LiquidityLocked(); if (sender != address(this) && sender != positionManager) revert LiquidityLocked(); return BaseHook.beforeAddLiquidity.selector; } function _beforeSwap( address, PoolKey calldata key, SwapParams calldata params, bytes calldata ) internal override returns (bytes4, BeforeSwapDelta, uint24) { // Trading launch delay protection: must be in the TRADING state if (burn.currentPhase() != IBurnToken.Phase.TRADING) revert TradingNotOpen(); // Skim 1% of the "paired token (WETH/WBNB)" as the dividend. // Division of labor (based on "which token the specified side is"): // - specified == WETH → skim in beforeSwap (here) // · buy BURN + exactInput : specified = input WETH // · sell BURN + exactOutput : specified = output WETH // - specified == BURN → skim from unspecified=WETH in afterSwap // · sell BURN + exactInput / buy BURN + exactOutput bool burnIsToken0 = address(burn) < address(wrappedNative); bool isBuyBurn = (params.zeroForOne != burnIsToken0); bool isExactInput = params.amountSpecified < 0; // specified being WETH is equivalent to (buy and exactInput) or (sell and exactOutput), i.e. isBuyBurn == isExactInput if (isBuyBurn != isExactInput) { return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0); } // |amountSpecified| is exactly the precise amount of the specified side (WETH) uint256 wethAbsSpec = isExactInput ? uint256(-params.amountSpecified) : uint256(params.amountSpecified); uint256 feeAmount = wethAbsSpec / 100; if (feeAmount == 0) { return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0); } // 1) take the fee's WETH from the PoolManager to the hook, recording a hook debt of -feeAmount Currency wethCurrency = burnIsToken0 ? key.currency1 : key.currency0; poolManager.take(wethCurrency, address(this), feeAmount); // 2) Transfer to XBurn and notify it to grow the dividend pool IERC20(address(wrappedNative)).safeTransfer(address(xBurn), feeAmount); xBurn.notifyDividend(feeAmount); emit FeeCollected(feeAmount); // 3) specifiedDelta = +feeAmount, with unified sign semantics: // · exactInput (amountSpecified < 0): amountToSwap += fee → -X + fee ∈ (-X, 0], still exactInput, the pool swaps fee less input; hookDelta = +fee specified (WETH); offsets the take debt // · exactOutput (amountSpecified > 0): amountToSwap += fee → X + fee > 0, still exactOutput, the pool produces fee more specified output; hookDelta = +fee specified (WETH); the user nets X (the extra fee is taken by the hook); the user pays extra BURN to offset // Requires beforeSwapReturnDelta = true (already configured in getHookPermissions) int128 deltaSpecified = int128(int256(feeAmount)); return (BaseHook.beforeSwap.selector, toBeforeSwapDelta(deltaSpecified, 0), 0); } function _afterSwap( address, PoolKey calldata key, SwapParams calldata params, BalanceDelta delta, bytes calldata ) internal override returns (bytes4, int128) { // Only handle the two specified=BURN cases (the other two specified=WETH cases already had their fee collected in beforeSwap): // · sell BURN + exactInput (unspecified = WETH output) // · buy BURN + exactOutput (unspecified = WETH input) // The afterSwap int128 return value falls on the unspecified side → which is exactly WETH, so it can offset the take(WETH) debt. bool burnIsToken0 = address(burn) < address(wrappedNative); bool isBuyBurn = (params.zeroForOne != burnIsToken0); bool isExactInput = params.amountSpecified < 0; // The two specified == WETH cases (isBuyBurn == isExactInput) were already handled in beforeSwap if (isBuyBurn == isExactInput) { return (BaseHook.afterSwap.selector, 0); } // WETH net flow direction: >0 means the pool gives the user WETH (sell BURN exactInput), // <0 means the user gives the pool WETH (buy BURN exactOutput) int128 wethDelta = burnIsToken0 ? delta.amount1() : delta.amount0(); uint128 wethAbs = wethDelta > 0 ? uint128(wethDelta) : uint128(-wethDelta); uint128 fee = wethAbs / 100; if (fee == 0) { return (BaseHook.afterSwap.selector, 0); } // 1) take the fee's WETH from the PoolManager, recording a -fee debt Currency wethCurrency = burnIsToken0 ? key.currency1 : key.currency0; poolManager.take(wethCurrency, address(this), fee); // 2) Transfer to XBurn and notify it to grow the dividend pool IERC20(address(wrappedNative)).safeTransfer(address(xBurn), fee); xBurn.notifyDividend(fee); emit FeeCollected(fee); // 3) Return +fee to unspecified (which here is necessarily the WETH side), offsetting the debt from (1). // Requires afterSwapReturnDelta = true (already configured in getHookPermissions) return (BaseHook.afterSwap.selector, int128(fee)); } // ============ Helpers ============ /// @notice Receives the ETH sent by BurnToken during finalize receive() external payable {} }