// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol"; import {PoolId} from "v4-core/src/types/PoolId.sol"; import {StateLibrary} from "v4-core/src/libraries/StateLibrary.sol"; import {BurnToken} from "./BurnToken.sol"; import {IBurnToken} from "./interfaces/IBurnToken.sol"; import {BurnHook} from "./BurnHook.sol"; import {XBurn} from "./XBurn.sol"; /// @dev Minimal views the Lens needs from the periphery, used to validate `setPeriphery`. interface IWrappedXBurnView { function asset() external view returns (address); function xBurnContract() external view returns (address); } interface IBurnSwapRouterView { function hook() external view returns (address); function burn() external view returns (address); } /// @title BurnHookLens /// @notice Read-only aggregator for agents and frontends: one `eth_call` returns the whole protocol /// state, a wallet's position, or a "can this wallet mint right now, and if not why" answer. /// @dev Holds no funds and has no effect on the core contracts — it only reads them. /// The core contracts do not know about the Lens, so it can be (re)deployed at any time. /// /// Address discovery: BurnToken is the root. `hook = burn.bonder()`, `xBurn = hook.xBurn()`. /// WrappedXBurn and BurnSwapRouter are deployed separately after finalize and are not /// referenced by any core contract, so they are registered here ONCE via `setPeriphery` /// (validated against the core, then the admin role is cleared for good). contract BurnHookLens { using StateLibrary for IPoolManager; address internal constant DEAD = 0x000000000000000000000000000000000000dEaD; BurnToken public immutable burn; BurnHook public immutable hook; /// @notice Set once via `setPeriphery`; address(0) until then. address public wxBurn; address public router; /// @notice May call `setPeriphery` exactly once; address(0) afterwards. address public admin; error NotAdmin(); error BonderNotSet(); error NotFinalized(); error BadWxBurn(); error BadRouter(); event PeripherySet(address indexed wxBurn, address indexed router); // ============ Return types ============ struct Addresses { address burnToken; address burnHook; address xBurn; // address(0) before finalize address wxBurn; // address(0) until setPeriphery address router; // address(0) until setPeriphery address wrappedNative; // WBNB on BSC address agentId; // address(0) = no Agent ID gate address dev; address poolManager; } struct Constants { uint256 mintPrice; uint256 mintAmount; uint256 maxMints; uint256 maxMintsPerWallet; uint256 mintDuration; uint256 blockDelay; uint256 minMintsToInvite; uint256 directRewardBps; uint256 indirectRewardBps; uint256 devRewardBps; uint256 lpReserve; uint256 totalSupplyCap; } struct ProtocolState { uint8 phase; // IBurnToken.Phase: 0 PENDING, 1 MINTING, 2 MINT_SUCCESS, 3 BONDED, 4 TRADING, 5 MINT_FAILED uint256 blockNumber; uint256 timestamp; // mint uint256 mintCount; uint256 mintsRemaining; uint256 mintDeadline; // unix seconds; 0 before startMint uint256 timeRemaining; // seconds; 0 unless MINTING uint256 nativeRaised; // wei uint256 totalReferralReward; // wei reserved for referrers (unclaimed) uint256 devReward; // wei reserved for DEV (unclaimed) // pool bool finalized; uint256 tradingStartBlock; // bondedBlock + BLOCK_DELAY; 0 before finalize uint160 sqrtPriceX96; // 0 before finalize uint128 poolLiquidity; // 0 before finalize uint256 nativePerBurn; // spot price: wei of wrapped native per 1e18 BURN (before the 1% hook fee); 0 before finalize // supply uint256 burnTotalSupply; uint256 burnBurned; // BURN held by DEAD // xBURN / wxBURN uint256 xBurnTotalSupply; uint256 dividendPool; // wrapped native held by xBURN, not yet paid out uint256 wxBurnTotalAssets; // xBURN held by the vault uint256 wxBurnTotalSupply; uint256 vaultPendingDividend; // wrapped native the vault could harvest via compoundFromDividend } /// @dev `code` values returned by `mintStatus`. uint8 public constant MINT_OK = 0; uint8 public constant MINT_NOT_MINTING = 1; uint8 public constant MINT_SOLD_OUT = 2; uint8 public constant MINT_AGENT_ID_REQUIRED = 3; uint8 public constant MINT_WALLET_LIMIT = 4; uint8 public constant MINT_INVITER_REQUIRED = 5; uint8 public constant MINT_SELF_INVITE = 6; uint8 public constant MINT_INVITER_NOT_QUALIFIED = 7; uint8 public constant MINT_INSUFFICIENT_BALANCE = 8; struct MintStatus { bool canMint; uint8 code; // one of the MINT_* constants string reason; // human/agent readable name of `code` uint256 value; // exact msg.value to send (MINT_PRICE) address inviterToPass; // the argument to pass to mint(): address(0) when no inviter is needed bool inviterNeeded; // true only for a wallet's first mint when it is not the first minter uint256 walletMintsUsed; uint256 walletMintsLeft; // min(per-wallet remaining, global remaining) } struct Position { uint256 nativeBalance; uint256 burnBalance; uint256 xBurnBalance; uint256 wxBurnBalance; uint256 wxBurnAsXBurn; // xBURN redeemable for the wxBURN balance uint256 pendingDividend; // wrapped native claimable from xBURN via claim() uint256 referralReward; // wei accrued as a referrer bool referralClaimable; // true once the mint has succeeded and referralReward > 0 uint256 mintsOf; address inviter; bool hasAgentId; bool canInvite; uint256 refundableBurn; // BURN that can be refunded now (multiple of MINT_AMOUNT); 0 unless MINT_FAILED uint256 refundableNative; // wei returned for refundableBurn } // ============ Setup ============ /// @param _burn the BurnToken (protocol root). Its bonder (the hook) must already be set. constructor(address _burn) { burn = BurnToken(payable(_burn)); address bonder = burn.bonder(); if (bonder == address(0)) revert BonderNotSet(); hook = BurnHook(payable(bonder)); admin = msg.sender; } /// @notice Register WrappedXBurn and BurnSwapRouter. Callable once by the admin, after finalize. /// Both are checked against the core contracts; afterwards the admin role is cleared. function setPeriphery(address _wxBurn, address _router) external { if (msg.sender != admin) revert NotAdmin(); address x = address(hook.xBurn()); if (x == address(0)) revert NotFinalized(); if ( _wxBurn.code.length == 0 || IWrappedXBurnView(_wxBurn).asset() != x || IWrappedXBurnView(_wxBurn).xBurnContract() != x ) revert BadWxBurn(); if ( _router.code.length == 0 || IBurnSwapRouterView(_router).hook() != address(hook) || IBurnSwapRouterView(_router).burn() != address(burn) ) revert BadRouter(); wxBurn = _wxBurn; router = _router; admin = address(0); emit PeripherySet(_wxBurn, _router); } // ============ Views ============ function addresses() public view returns (Addresses memory a) { a.burnToken = address(burn); a.burnHook = address(hook); a.xBurn = address(hook.xBurn()); a.wxBurn = wxBurn; a.router = router; a.wrappedNative = address(hook.wrappedNative()); a.agentId = burn.AGENT_ID(); a.dev = burn.DEV(); a.poolManager = address(hook.poolManager()); } function constants() external view returns (Constants memory c) { c.mintPrice = burn.MINT_PRICE(); c.mintAmount = burn.MINT_AMOUNT(); c.maxMints = burn.MAX_MINTS(); c.maxMintsPerWallet = burn.MAX_MINTS_PER_WALLET(); c.mintDuration = burn.MINT_DURATION(); c.blockDelay = burn.BLOCK_DELAY(); c.minMintsToInvite = burn.MIN_MINTS_TO_INVITE(); c.directRewardBps = burn.DIRECT_REWARD_BPS(); c.indirectRewardBps = burn.INDIRECT_REWARD_BPS(); c.devRewardBps = burn.DEV_REWARD_BPS(); c.lpReserve = burn.LP_RESERVE(); c.totalSupplyCap = burn.TOTAL_SUPPLY(); } function protocolState() external view returns (ProtocolState memory s) { s.phase = uint8(burn.currentPhase()); s.blockNumber = block.number; s.timestamp = block.timestamp; s.mintCount = burn.mintCount(); s.mintsRemaining = burn.mintsRemaining(); s.mintDeadline = burn.mintDeadline(); s.timeRemaining = burn.timeRemaining(); s.nativeRaised = burn.ethRaised(); s.totalReferralReward = burn.totalReferralReward(); s.devReward = burn.devReward(); s.burnTotalSupply = burn.totalSupply(); s.burnBurned = burn.balanceOf(DEAD); s.finalized = hook.finalized(); if (s.finalized) { s.tradingStartBlock = burn.bondedBlock() + burn.BLOCK_DELAY(); IPoolManager pm = hook.poolManager(); PoolId id = hook.poolId(); (s.sqrtPriceX96,,,) = pm.getSlot0(id); s.poolLiquidity = pm.getLiquidity(id); s.nativePerBurn = _nativePerBurn(s.sqrtPriceX96); XBurn x = hook.xBurn(); s.xBurnTotalSupply = x.totalSupply(); s.dividendPool = x.dividendPool(); address w = wxBurn; if (w != address(0)) { s.wxBurnTotalAssets = IERC4626(w).totalAssets(); s.wxBurnTotalSupply = IERC20(w).totalSupply(); s.vaultPendingDividend = x.pendingDividend(w) + x.dividendToken().balanceOf(w); } } } /// @notice Would `user.mint(inviter)` succeed right now? Mirrors BurnToken.mint's checks in order. /// @param inviter the referrer the user intends to pass; ignored when no inviter is needed. function mintStatus(address user, address inviter) external view returns (MintStatus memory m) { uint256 perWallet = burn.MAX_MINTS_PER_WALLET(); m.value = burn.MINT_PRICE(); m.walletMintsUsed = burn.mintsOf(user); uint256 walletLeft = m.walletMintsUsed >= perWallet ? 0 : perWallet - m.walletMintsUsed; m.walletMintsLeft = Math.min(walletLeft, burn.mintsRemaining()); uint256 count = burn.mintCount(); // An inviter is required only for a wallet's first mint, unless it is (or becomes) the first minter. m.inviterNeeded = count != 0 && user != burn.firstMinter() && burn.inviter(user) == address(0); m.inviterToPass = m.inviterNeeded ? inviter : address(0); if (burn.currentPhase() != IBurnToken.Phase.MINTING) { m.code = MINT_NOT_MINTING; } else if (!burn.hasAgentId(user)) { m.code = MINT_AGENT_ID_REQUIRED; } else if (walletLeft == 0) { m.code = MINT_WALLET_LIMIT; } else if (burn.mintsRemaining() == 0) { m.code = MINT_SOLD_OUT; } else if (m.inviterNeeded && inviter == address(0)) { m.code = MINT_INVITER_REQUIRED; } else if (m.inviterNeeded && inviter == user) { m.code = MINT_SELF_INVITE; } else if (m.inviterNeeded && !burn.canInvite(inviter)) { m.code = MINT_INVITER_NOT_QUALIFIED; } else if (user.balance < m.value) { m.code = MINT_INSUFFICIENT_BALANCE; } else { m.code = MINT_OK; } m.canMint = m.code == MINT_OK; m.reason = _mintReason(m.code); } function position(address user) external view returns (Position memory p) { IBurnToken.Phase phase = burn.currentPhase(); p.nativeBalance = user.balance; p.burnBalance = burn.balanceOf(user); p.mintsOf = burn.mintsOf(user); p.inviter = burn.inviter(user); p.hasAgentId = burn.hasAgentId(user); p.canInvite = burn.canInvite(user); p.referralReward = burn.referralReward(user); p.referralClaimable = p.referralReward > 0 && (phase == IBurnToken.Phase.MINT_SUCCESS || phase == IBurnToken.Phase.BONDED || phase == IBurnToken.Phase.TRADING); if (phase == IBurnToken.Phase.MINT_FAILED) { uint256 unit = burn.MINT_AMOUNT(); uint256 units = p.burnBalance / unit; p.refundableBurn = units * unit; p.refundableNative = units * burn.MINT_PRICE(); } XBurn x = hook.xBurn(); if (address(x) != address(0)) { p.xBurnBalance = x.balanceOf(user); p.pendingDividend = x.pendingDividend(user); } address w = wxBurn; if (w != address(0)) { p.wxBurnBalance = IERC20(w).balanceOf(user); p.wxBurnAsXBurn = IERC4626(w).convertToAssets(p.wxBurnBalance); } } // ============ Internals ============ /// @dev sqrtPriceX96 = sqrt(token1/token0)·2^96. Returns wei of wrapped native per 1e18 BURN. function _nativePerBurn(uint160 sqrtPriceX96) internal view returns (uint256) { if (sqrtPriceX96 == 0) return 0; uint256 p = uint256(sqrtPriceX96); uint256 q96 = 1 << 96; bool burnIsToken0 = address(burn) < address(hook.wrappedNative()); return burnIsToken0 ? Math.mulDiv(Math.mulDiv(1e18, p, q96), p, q96) // native/BURN = P^2 / 2^192 : Math.mulDiv(Math.mulDiv(1e18, q96, p), q96, p); // native/BURN = 2^192 / P^2 } function _mintReason(uint8 code) internal pure returns (string memory) { if (code == MINT_OK) return "OK"; if (code == MINT_NOT_MINTING) return "NOT_MINTING"; if (code == MINT_SOLD_OUT) return "SOLD_OUT"; if (code == MINT_AGENT_ID_REQUIRED) return "AGENT_ID_REQUIRED"; if (code == MINT_WALLET_LIMIT) return "WALLET_LIMIT"; if (code == MINT_INVITER_REQUIRED) return "INVITER_REQUIRED"; if (code == MINT_SELF_INVITE) return "SELF_INVITE"; if (code == MINT_INVITER_NOT_QUALIFIED) return "INVITER_NOT_QUALIFIED"; return "INSUFFICIENT_BALANCE"; } }