🔥
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/BurnHook.sol
Uniswap V4 hook: finalize, pool creation + LP burn, trading gate, 1% fee per swap
376 linessolc 0.8.26 · via-ir · optimizer 200sha256 0be60bf6f9d58750…On-chain 0x785C83dDdD974a424aBC10aB2E9286E60899e8CC · BscScan ↗ · Sourcify (verified source) ↗
1// SPDX-License-Identifier: MIT2pragma solidity ^0.8.26;4import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol";5import {Hooks} from "v4-core/src/libraries/Hooks.sol";6import {IHooks} from "v4-core/src/interfaces/IHooks.sol";7import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";8import {ModifyLiquidityParams, SwapParams} from "v4-core/src/types/PoolOperation.sol";9import {PoolKey} from "v4-core/src/types/PoolKey.sol";10import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";11import {Currency, CurrencyLibrary} from "v4-core/src/types/Currency.sol";12import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";13import {BeforeSwapDelta, BeforeSwapDeltaLibrary, toBeforeSwapDelta} from "v4-core/src/types/BeforeSwapDelta.sol";14import {LPFeeLibrary} from "v4-core/src/libraries/LPFeeLibrary.sol";15import {TickMath} from "v4-core/src/libraries/TickMath.sol";16import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol";17import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";18import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";19import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";20import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";22import {IPositionManager} from "v4-periphery/src/interfaces/IPositionManager.sol";23import {Actions} from "v4-periphery/src/libraries/Actions.sol";24import {LiquidityAmounts} from "v4-periphery/src/libraries/LiquidityAmounts.sol";25import {IWETH9} from "v4-periphery/src/interfaces/external/IWETH9.sol";26import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";28import {BurnToken} from "./BurnToken.sol";29import {IBurnToken} from "./interfaces/IBurnToken.sol";30import {XBurn} from "./XBurn.sol";32/// @title BurnHook33/// @notice The core hook of the entire protocol, responsible for:34/// 1. finalize() automatic pool creation (BURN/WETH or BURN/WBNB, 1% fee, full-range, LP burn)35/// 2. Trading launch delay check36/// 3. swap fee skimming (1% of the paired token) and injecting it into the XBurn dividend pool37/// 4. Locking down LP add permission (only allowing the contract itself to create the pool)38contract BurnHook is BaseHook, ReentrancyGuard {39 using PoolIdLibrary for PoolKey;40 using StateLibrary for IPoolManager;41 using CurrencyLibrary for Currency;42 using SafeERC20 for IERC20;44 // ============ Constants ============46 uint24 public constant POOL_FEE = 0; // 0% LP fee — the 1% protocol dividend is entirely skimmed by the hook inside before/afterSwap47 int24 public constant TICK_SPACING = 200; // Used only for full-range LP; tickSpacing and fee are decoupled in V4, so keeping 200 has no effect48 address public constant DEAD = 0x000000000000000000000000000000000000dEaD;50 // ============ Immutables ============52 BurnToken public immutable burn;53 IWETH9 public immutable wrappedNative; // WETH or WBNB54 address public immutable positionManager;55 IAllowanceTransfer public immutable permit2;57 // ============ State ============59 XBurn public xBurn; // Deployed during finalize60 PoolKey public poolKey;61 PoolId public poolId;62 bool public finalized;64 bool internal _bondingInProgress; // Used to bypass the beforeAddLiquidity check66 // ============ Errors ============68 error NotBurnToken();69 error AlreadyFinalized();70 error NotSuccess();71 error LiquidityLocked();72 error TradingNotOpen();73 error InitNotAllowed();75 // ============ Events ============77 event Finalized(address indexed pool, uint256 ethToLP, uint256 burnToLP, address indexed xBurnAddr);78 event FeeCollected(uint256 amount);79 event LPBurned(uint256 tokenId); // tokenId is only an on-chain index; the LP NFT is minted directly → DEAD81 // ============ Constructor ============83 constructor(84 IPoolManager _manager,85 address _burn,86 address _wrappedNative,87 address _positionManager,88 address _permit289 ) BaseHook(_manager) {90 require(91 _burn != address(0) && _wrappedNative != address(0)92 && _positionManager != address(0) && _permit2 != address(0),93 "zero addr"94 );95 burn = BurnToken(payable(_burn));96 wrappedNative = IWETH9(_wrappedNative);97 positionManager = _positionManager;98 permit2 = IAllowanceTransfer(_permit2);99 }101 // ============ Hook Permissions ============103 function getHookPermissions() public pure override returns (Hooks.Permissions memory) {104 return Hooks.Permissions({105 beforeInitialize: true,106 afterInitialize: false,107 beforeAddLiquidity: true,108 afterAddLiquidity: false,109 beforeRemoveLiquidity: false,110 afterRemoveLiquidity: false,111 beforeSwap: true,112 afterSwap: true,113 beforeDonate: false,114 afterDonate: false,115 beforeSwapReturnDelta: true,116 afterSwapReturnDelta: true,117 afterAddLiquidityReturnDelta: false,118 afterRemoveLiquidityReturnDelta: false119 });120 }122 // ============ Finalize ============124 /// @notice Callable by anyone; triggers the automatic pool creation flow125 /// @dev No caller reward; the originally reserved finalize reward has been removed, and this portion of ETH is entirely merged into the LP126 function finalize() external nonReentrant {127 if (finalized) revert AlreadyFinalized();128 if (burn.currentPhase() != IBurnToken.Phase.MINT_SUCCESS) revert NotSuccess();130 finalized = true;132 // 1. Trigger the BurnToken state transition, receiving the LP reserve token + ETH (only the referral reward reserve is deducted)133 (uint256 ethForLP, uint256 burnForLP) = burn.bondingFinalize();135 // 2. Deploy the XBurn contract136 xBurn = new XBurn(address(burn), address(wrappedNative), address(this));138 // 3. wrap ETH -> WETH139 wrappedNative.deposit{value: ethForLP}();141 // 4. Construct the PoolKey142 Currency c0;143 Currency c1;144 bool burnIsToken0 = address(burn) < address(wrappedNative);145 if (burnIsToken0) {146 c0 = Currency.wrap(address(burn));147 c1 = Currency.wrap(address(wrappedNative));148 } else {149 c0 = Currency.wrap(address(wrappedNative));150 c1 = Currency.wrap(address(burn));151 }153 PoolKey memory key = PoolKey({154 currency0: c0,155 currency1: c1,156 fee: POOL_FEE,157 tickSpacing: TICK_SPACING,158 hooks: IHooks(address(this))159 });160 poolKey = key;161 poolId = key.toId();163 // 5. Initialize the pool; sqrtPriceX96 is determined by the current burnForLP / ethForLP164 uint160 sqrtPriceX96 = _computeSqrtPriceX96(burnForLP, ethForLP, burnIsToken0);166 _bondingInProgress = true;167 poolManager.initialize(key, sqrtPriceX96);169 // 6. Add full-range liquidity (actually done via the PositionManager, with the LP NFT transferred directly to DEAD)170 // Placeholder used before testnet/audit — real integration must be written against the V4 PositionManager ABI171 _addFullRangeLiquidityAndBurn(key, burnForLP, ethForLP);173 _bondingInProgress = false;175 emit Finalized(address(0), ethForLP, burnForLP, address(xBurn));176 }178 /// @dev Compute the pool's sqrtPriceX96. token0 = burnIsToken0 ? BURN : WETH179 /// price = token1/token0 ; sqrtPriceX96 = sqrt(price) · 2^96 = sqrt(num · 2^192 / den)180 /// Use OZ Math.mulDiv to compute ratioX192 within a 512-bit intermediate result, avoiding `num << 192` overflowing uint256 under real amounts.181 function _computeSqrtPriceX96(uint256 burnAmt, uint256 ethAmt, bool burnIsToken0)182 internal183 pure184 returns (uint160)185 {186 (uint256 numerator, uint256 denominator) = burnIsToken0187 ? (ethAmt, burnAmt)188 : (burnAmt, ethAmt);189 uint256 ratioX192 = Math.mulDiv(numerator, 1 << 192, denominator);190 return uint160(Math.sqrt(ratioX192));191 }193 /// @dev Add full-range liquidity and permanently burn the LP NFT to DEAD.194 /// The V4 PositionManager uses a two-layer Permit2 authorization + an Actions command stream.195 function _addFullRangeLiquidityAndBurn(196 PoolKey memory key,197 uint256 burnForLP,198 uint256 ethForLP199 ) internal {200 // ─── ① Two-layer approve: hook → Permit2 → PositionManager ───201 IERC20(address(burn)).forceApprove(address(permit2), type(uint256).max);202 IERC20(address(wrappedNative)).forceApprove(address(permit2), type(uint256).max);203 permit2.approve(address(burn), positionManager, type(uint160).max, type(uint48).max);204 permit2.approve(address(wrappedNative), positionManager, type(uint160).max, type(uint48).max);206 // ─── ② Compute full-range liquidity ───207 int24 tickLower = TickMath.minUsableTick(key.tickSpacing);208 int24 tickUpper = TickMath.maxUsableTick(key.tickSpacing);209 (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(key.toId());211 bool burnIsToken0 = address(burn) < address(wrappedNative);212 (uint256 amount0Max, uint256 amount1Max) = burnIsToken0213 ? (burnForLP, ethForLP)214 : (ethForLP, burnForLP);216 uint128 liquidity = LiquidityAmounts.getLiquidityForAmounts(217 sqrtPriceX96,218 TickMath.getSqrtPriceAtTick(tickLower),219 TickMath.getSqrtPriceAtTick(tickUpper),220 amount0Max,221 amount1Max222 );224 // ─── ③ Construct the Actions command stream: MINT_POSITION + SETTLE_PAIR ───225 bytes memory actions = abi.encodePacked(226 uint8(Actions.MINT_POSITION),227 uint8(Actions.SETTLE_PAIR)228 );229 bytes[] memory params = new bytes[](2);230 params[0] = abi.encode(231 key, tickLower, tickUpper,232 liquidity,233 amount0Max, // amount0Max (slippage cap)234 amount1Max, // amount1Max (slippage cap)235 DEAD, // recipient: mint the NFT directly to DEAD, making the LP permanently unwithdrawable236 bytes("") // hookData237 );238 params[1] = abi.encode(key.currency0, key.currency1);240 // ─── ④ Call the PositionManager: mint lands directly on DEAD, no intermediate transfer needed ───241 // The V4 PositionManager uses OZ _mint (not _safeMint), and DEAD is an EOA, so it passes the ZeroAddress check242 uint256 tokenId = IPositionManager(positionManager).nextTokenId();243 IPositionManager(positionManager).modifyLiquidities(244 abi.encode(actions, params),245 block.timestamp246 );248 emit LPBurned(tokenId);249 }251 // ============ Hook Callbacks ============253 function _beforeInitialize(address sender, PoolKey calldata, uint160)254 internal255 view256 override257 returns (bytes4)258 {259 // Only allow the contract itself (the finalize flow) to initialize the pool260 if (sender != address(this)) revert InitNotAllowed();261 return BaseHook.beforeInitialize.selector;262 }264 function _beforeAddLiquidity(265 address sender,266 PoolKey calldata,267 ModifyLiquidityParams calldata,268 bytes calldata269 ) internal view override returns (bytes4) {270 // Only allow the finalize flow to add LP (self-call and the bonding flag is true)271 if (!_bondingInProgress) revert LiquidityLocked();272 if (sender != address(this) && sender != positionManager) revert LiquidityLocked();273 return BaseHook.beforeAddLiquidity.selector;274 }276 function _beforeSwap(277 address,278 PoolKey calldata key,279 SwapParams calldata params,280 bytes calldata281 ) internal override returns (bytes4, BeforeSwapDelta, uint24) {282 // Trading launch delay protection: must be in the TRADING state283 if (burn.currentPhase() != IBurnToken.Phase.TRADING) revert TradingNotOpen();285 // Skim 1% of the "paired token (WETH/WBNB)" as the dividend.286 // Division of labor (based on "which token the specified side is"):287 // - specified == WETH → skim in beforeSwap (here)288 // · buy BURN + exactInput : specified = input WETH289 // · sell BURN + exactOutput : specified = output WETH290 // - specified == BURN → skim from unspecified=WETH in afterSwap291 // · sell BURN + exactInput / buy BURN + exactOutput292 bool burnIsToken0 = address(burn) < address(wrappedNative);293 bool isBuyBurn = (params.zeroForOne != burnIsToken0);294 bool isExactInput = params.amountSpecified < 0;296 // specified being WETH is equivalent to (buy and exactInput) or (sell and exactOutput), i.e. isBuyBurn == isExactInput297 if (isBuyBurn != isExactInput) {298 return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);299 }301 // |amountSpecified| is exactly the precise amount of the specified side (WETH)302 uint256 wethAbsSpec = isExactInput303 ? uint256(-params.amountSpecified)304 : uint256(params.amountSpecified);305 uint256 feeAmount = wethAbsSpec / 100;306 if (feeAmount == 0) {307 return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);308 }310 // 1) take the fee's WETH from the PoolManager to the hook, recording a hook debt of -feeAmount311 Currency wethCurrency = burnIsToken0 ? key.currency1 : key.currency0;312 poolManager.take(wethCurrency, address(this), feeAmount);314 // 2) Transfer to XBurn and notify it to grow the dividend pool315 IERC20(address(wrappedNative)).safeTransfer(address(xBurn), feeAmount);316 xBurn.notifyDividend(feeAmount);318 emit FeeCollected(feeAmount);320 // 3) specifiedDelta = +feeAmount, with unified sign semantics:321 // · exactInput (amountSpecified < 0): amountToSwap += fee → -X + fee ∈ (-X, 0], still exactInput, the pool swaps fee less input; hookDelta = +fee specified (WETH); offsets the take debt322 // · 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 offset323 // Requires beforeSwapReturnDelta = true (already configured in getHookPermissions)324 int128 deltaSpecified = int128(int256(feeAmount));325 return (BaseHook.beforeSwap.selector, toBeforeSwapDelta(deltaSpecified, 0), 0);326 }328 function _afterSwap(329 address,330 PoolKey calldata key,331 SwapParams calldata params,332 BalanceDelta delta,333 bytes calldata334 ) internal override returns (bytes4, int128) {335 // Only handle the two specified=BURN cases (the other two specified=WETH cases already had their fee collected in beforeSwap):336 // · sell BURN + exactInput (unspecified = WETH output)337 // · buy BURN + exactOutput (unspecified = WETH input)338 // The afterSwap int128 return value falls on the unspecified side → which is exactly WETH, so it can offset the take(WETH) debt.339 bool burnIsToken0 = address(burn) < address(wrappedNative);340 bool isBuyBurn = (params.zeroForOne != burnIsToken0);341 bool isExactInput = params.amountSpecified < 0;343 // The two specified == WETH cases (isBuyBurn == isExactInput) were already handled in beforeSwap344 if (isBuyBurn == isExactInput) {345 return (BaseHook.afterSwap.selector, 0);346 }348 // WETH net flow direction: >0 means the pool gives the user WETH (sell BURN exactInput),349 // <0 means the user gives the pool WETH (buy BURN exactOutput)350 int128 wethDelta = burnIsToken0 ? delta.amount1() : delta.amount0();351 uint128 wethAbs = wethDelta > 0 ? uint128(wethDelta) : uint128(-wethDelta);352 uint128 fee = wethAbs / 100;353 if (fee == 0) {354 return (BaseHook.afterSwap.selector, 0);355 }357 // 1) take the fee's WETH from the PoolManager, recording a -fee debt358 Currency wethCurrency = burnIsToken0 ? key.currency1 : key.currency0;359 poolManager.take(wethCurrency, address(this), fee);361 // 2) Transfer to XBurn and notify it to grow the dividend pool362 IERC20(address(wrappedNative)).safeTransfer(address(xBurn), fee);363 xBurn.notifyDividend(fee);365 emit FeeCollected(fee);367 // 3) Return +fee to unspecified (which here is necessarily the WETH side), offsetting the debt from (1).368 // Requires afterSwapReturnDelta = true (already configured in getHookPermissions)369 return (BaseHook.afterSwap.selector, int128(fee));370 }372 // ============ Helpers ============374 /// @notice Receives the ETH sent by BurnToken during finalize375 receive() external payable {}376}