// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; 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 {Address} from "@openzeppelin/contracts/utils/Address.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 {IWETH9} from "v4-periphery/src/interfaces/external/IWETH9.sol"; import {BurnHook} from "./BurnHook.sol"; /// @title BurnSwapRouter /// @notice Minimal, dedicated exact-input swap router for the protocol's own Uniswap V4 BURN/WETH pool. /// @dev Lets a frontend trade against the hook pool with a plain `approve` + `swap(amountIn, minOut)` /// flow — no Universal Router / Permit2 / command encoding needed. /// /// It reuses the V4 unlock/callback + flash-accounting pattern: pull the input token, `unlock` /// the PoolManager, `swap`, then settle/take the exact amounts read from the transient /// `currencyDelta` (which already accounts for the BurnHook's deterministic 1% WETH fee). /// /// Slippage is the caller's responsibility via `minOut` (the frontend gets a figure from the /// V4 Quoter and applies its tolerance). Pass `deadline` (0 to disable) for stale-tx protection. /// The pool only accepts swaps in the TRADING phase; the hook reverts otherwise. contract BurnSwapRouter is IUnlockCallback, ReentrancyGuard { using SafeERC20 for IERC20; using TransientStateLibrary for IPoolManager; using StateLibrary for IPoolManager; using PoolIdLibrary for PoolKey; using Address for address payable; uint256 private constant BPS = 10_000; uint256 private constant HOOK_FEE_BPS = 100; // BurnHook takes 1% of the WETH leg on every swap IPoolManager public immutable poolManager; BurnHook public immutable hook; address public immutable burn; address public immutable weth; // PoolKey fields cached at deploy (the pool is already created by the time the router is deployed). address public immutable currency0; address public immutable currency1; uint24 public immutable fee; int24 public immutable tickSpacing; error NotPoolManager(); error NotFinalized(); error ZeroAmount(); error ZeroAddress(); error Expired(); error Slippage(); event Swap( address indexed sender, address indexed to, address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut ); constructor(BurnHook _hook) { if (!_hook.finalized()) revert NotFinalized(); hook = _hook; poolManager = _hook.poolManager(); burn = address(_hook.burn()); weth = address(_hook.wrappedNative()); (Currency c0, Currency c1, uint24 f, int24 ts,) = _hook.poolKey(); currency0 = Currency.unwrap(c0); currency1 = Currency.unwrap(c1); fee = f; tickSpacing = ts; } // ============ Public swap entries (exact input) ============ /// @notice Swap an exact amount of WETH for BURN. Caller must `approve` WETH to this router first. function swapExactWethForBurn(uint256 amountIn, uint256 minBurnOut, address to, uint256 deadline) external nonReentrant returns (uint256 burnOut) { address recipient = _prep(to, deadline, amountIn); IERC20(weth).safeTransferFrom(msg.sender, address(this), amountIn); burnOut = _swap(weth, burn, amountIn, minBurnOut); IERC20(burn).safeTransfer(recipient, burnOut); emit Swap(msg.sender, recipient, weth, burn, amountIn, burnOut); } /// @notice Swap an exact amount of BURN for WETH. Caller must `approve` BURN to this router first. function swapExactBurnForWeth(uint256 amountIn, uint256 minWethOut, address to, uint256 deadline) external nonReentrant returns (uint256 wethOut) { address recipient = _prep(to, deadline, amountIn); IERC20(burn).safeTransferFrom(msg.sender, address(this), amountIn); wethOut = _swap(burn, weth, amountIn, minWethOut); IERC20(weth).safeTransfer(recipient, wethOut); emit Swap(msg.sender, recipient, burn, weth, amountIn, wethOut); } /// @notice Swap native ETH for BURN: the router wraps msg.value to WETH, then swaps. function swapExactEthForBurn(uint256 minBurnOut, address to, uint256 deadline) external payable nonReentrant returns (uint256 burnOut) { address recipient = _prep(to, deadline, msg.value); IWETH9(weth).deposit{value: msg.value}(); burnOut = _swap(weth, burn, msg.value, minBurnOut); IERC20(burn).safeTransfer(recipient, burnOut); emit Swap(msg.sender, recipient, weth, burn, msg.value, burnOut); } /// @notice Swap an exact amount of BURN for native ETH: swap to WETH then unwrap. Caller must `approve` BURN first. function swapExactBurnForEth(uint256 amountIn, uint256 minEthOut, address to, uint256 deadline) external nonReentrant returns (uint256 ethOut) { address recipient = _prep(to, deadline, amountIn); IERC20(burn).safeTransferFrom(msg.sender, address(this), amountIn); ethOut = _swap(burn, weth, amountIn, minEthOut); IWETH9(weth).withdraw(ethOut); payable(recipient).sendValue(ethOut); emit Swap(msg.sender, recipient, burn, weth, amountIn, ethOut); } // ============ Quote (display only) ============ /// @notice Spot-price estimate of the exact-input output, after the hook's 1% WETH fee. /// @dev DISPLAY ONLY — ignores price impact, so actual output is lower (more so for large /// swaps relative to liquidity). The frontend derives `minOut` from this with a slippage /// tolerance; on-chain execution is protected by that `minOut`, never by this estimate. /// @param tokenIn must be WETH or BURN /// @param amountIn exact input amount function quoteExactInput(address tokenIn, uint256 amountIn) external view returns (uint256 estOut) { if (amountIn == 0) return 0; require(tokenIn == weth || tokenIn == burn, "bad tokenIn"); address tokenOut = tokenIn == weth ? burn : weth; (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(_poolKey().toId()); uint256 p = uint256(sqrtPriceX96); uint256 q96 = 1 << 96; // 1% hook fee applies to the WETH leg: deduct from input if paying WETH, else from output below. uint256 effIn = tokenIn == weth ? amountIn * (BPS - HOOK_FEE_BPS) / BPS : amountIn; bool inIsToken0 = tokenIn < tokenOut; // lower address is currency0 uint256 gross = inIsToken0 ? Math.mulDiv(Math.mulDiv(effIn, p, q96), p, q96) // out = in · P^2 / 2^192 : Math.mulDiv(Math.mulDiv(effIn, q96, p), q96, p); // out = in · 2^192 / P^2 estOut = tokenOut == weth ? gross * (BPS - HOOK_FEE_BPS) / BPS : gross; } // ============ Internal ============ function _prep(address to, uint256 deadline, uint256 amountIn) internal view returns (address recipient) { if (deadline != 0 && block.timestamp > deadline) revert Expired(); if (amountIn == 0) revert ZeroAmount(); recipient = to == address(0) ? msg.sender : to; } function _swap(address tokenIn, address tokenOut, uint256 amountIn, uint256 minOut) internal returns (uint256 out) { out = abi.decode( poolManager.unlock(abi.encode(tokenIn, tokenOut, amountIn, minOut)), (uint256) ); } /// @notice V4 unlock callback — only reachable inside a swap initiated by this router. function unlockCallback(bytes calldata data) external override returns (bytes memory) { if (msg.sender != address(poolManager)) revert NotPoolManager(); (address tokenIn, address tokenOut, uint256 amountIn, uint256 minOut) = abi.decode(data, (address, address, uint256, uint256)); // zeroForOne = swapping currency0 → currency1 = (tokenIn is currency0) = (tokenIn address is the lower one) bool zeroForOne = tokenIn < tokenOut; poolManager.swap( _poolKey(), SwapParams({ zeroForOne: zeroForOne, amountSpecified: -int256(amountIn), // negative = exact input sqrtPriceLimitX96: zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1 }), "" ); Currency inCur = Currency.wrap(tokenIn); Currency outCur = Currency.wrap(tokenOut); // Settle exactly what the transient ledger says (auto-accounts for the hook's 1% WETH fee). int256 inDelta = poolManager.currencyDelta(address(this), inCur); // < 0 = router owes int256 outDelta = poolManager.currencyDelta(address(this), outCur); // > 0 = router can take if (inDelta < 0) { poolManager.sync(inCur); IERC20(tokenIn).safeTransfer(address(poolManager), uint256(-inDelta)); poolManager.settle(); } if (outDelta <= 0) revert Slippage(); uint256 out = uint256(outDelta); if (out < minOut) revert Slippage(); poolManager.take(outCur, address(this), out); return abi.encode(out); } function _poolKey() internal view returns (PoolKey memory) { return PoolKey({ currency0: Currency.wrap(currency0), currency1: Currency.wrap(currency1), fee: fee, tickSpacing: tickSpacing, hooks: IHooks(address(hook)) }); } /// @dev Only accept ETH from the WETH contract (during unwrap in swapExactBurnForEth). receive() external payable { if (msg.sender != weth) revert ZeroAddress(); } }