// SPDX-License-Identifier: MIT pragma solidity 0.8.26; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; interface IV2Pair is IERC20 { function token0() external view returns (address); function getReserves() external view returns (uint112, uint112, uint32); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function mint(address) external returns (uint256); function burn(address) external returns (uint256, uint256); } interface IV2Factory { function getPair(address, address) external view returns (address); function createPair(address, address) external returns (address); } interface IAgentIdRegistry { function balanceOf(address) external view returns (uint256); function supportsInterface(bytes4) external view returns (bool); } interface IV2Router { function factory() external view returns (address); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256, uint256, address[] calldata, address, uint256 ) external; } /// @notice Only the canonical CRL/USDT pool is taxed. Ordinary LP additions/removals /// after launch are also pool transfers and pay this tax unless they are a strictly /// controlled launch/refund/buyback/tax-settlement operation. contract Roll is ERC20 { uint256 public constant INITIAL_SUPPLY = 1_000_000_000_000_000 * 1e18; uint256 public constant TAX_BPS = 50; address public immutable launch; address public pair; address public taxVault; bool public tradingOpen; bool private refundUnwind; error NotLaunch(); error TradingClosed(); error AlreadyConfigured(); constructor(address launch_) ERC20("Roll", "CRL") { launch = launch_; _mint(launch_, INITIAL_SUPPLY); } modifier onlyLaunch() { if (msg.sender != launch) revert NotLaunch(); _; } function configure(address pair_, address vault_) external onlyLaunch { if (pair != address(0) || pair_ == address(0) || vault_ == address(0)) revert AlreadyConfigured(); pair = pair_; taxVault = vault_; } function openTrading() external onlyLaunch { tradingOpen = true; } function setRefundUnwind(bool active) external onlyLaunch { refundUnwind = active; } function burnHeld(uint256 amount) external onlyLaunch { _burn(launch, amount); } function burnRefund(address account, uint256 amount) external onlyLaunch { if (tradingOpen) revert AlreadyConfigured(); _burn(account, amount); } function _update(address from, address to, uint256 amount) internal override { if (from == address(0) || to == address(0) || amount == 0) { super._update(from, to, amount); return; } if (!tradingOpen) { // Pair-to-launch is permitted only inside the failed-sale unwind. if (from != launch && !(refundUnwind && from == pair && to == launch)) revert TradingClosed(); } else if ((from == pair || to == pair) && from != launch && to != launch && from != taxVault && to != taxVault) { uint256 fee = Math.mulDiv(amount, TAX_BPS, 10_000); if (fee != 0) super._update(from, taxVault, fee); amount -= fee; } super._update(from, to, amount); } } library PoolMath { uint256 internal constant Q112 = 2 ** 112; uint256 internal constant FEE_FACTOR = 9_975; // PancakeSwap V2: 0.25%. function reserves(IV2Pair pair, address input) internal view returns (uint256 rIn, uint256 rOut) { (uint112 r0, uint112 r1,) = pair.getReserves(); return pair.token0() == input ? (uint256(r0), uint256(r1)) : (uint256(r1), uint256(r0)); } function amountOut(uint256 amount, uint256 rIn, uint256 rOut) internal pure returns (uint256) { uint256 effective = amount * FEE_FACTOR; return Math.mulDiv(effective, rOut, rIn * 10_000 + effective); } function impactOK(uint256 amount, uint256 reserve) internal pure returns (bool) { // Average execution impact, excluding the 0.25% DEX fee, <= 8%. return reserve != 0 && amount * FEE_FACTOR * 9_200 <= reserve * 10_000 * 800; } function maxInput(uint256 reserve) internal pure returns (uint256) { return Math.mulDiv(reserve, 10_000 * 800, FEE_FACTOR * 9_200); } function cumulative(IV2Pair pair, address tokenIn) internal view returns (uint256 value) { bool inputIs0 = pair.token0() == tokenIn; value = inputIs0 ? pair.price0CumulativeLast() : pair.price1CumulativeLast(); (uint112 r0, uint112 r1, uint32 timestampLast) = pair.getReserves(); uint32 elapsed; unchecked { elapsed = uint32(block.timestamp) - timestampLast; } if (elapsed != 0 && r0 != 0 && r1 != 0) { uint256 p = inputIs0 ? (uint256(r1) << 112) / r0 : (uint256(r0) << 112) / r1; unchecked { value += p * elapsed; } } } } /// @notice Permissionless settlement; no keeper can redirect proceeds or lower /// the protocol's historical-price minimum. No automatic call from token transfers. contract RollTaxVault is ReentrancyGuard { using SafeERC20 for IERC20; IERC20 public immutable token; IERC20 public immutable usdt; IV2Pair public immutable pair; IV2Router public immutable router; address public immutable launch; address public immutable treasury; uint256 public constant MIN_SETTLEMENT = 10 * 1e18; uint256 public constant ORACLE_PERIOD = 300; uint256 public constant ORACLE_MAX_WINDOW = 3_600; uint256 public constant ORACLE_MAX_AGE = 600; uint256 public lastObservationTime; uint256 public lastCumulative; uint256 public averagePriceX112; uint256 public lastOracleTime; uint256 public lastSettlementTime; bool public active; error NotReady(); error PriceProtection(); event OracleUpdated(uint256 averagePriceX112, uint256 timestamp); event TaxesSettled(uint256 crlIn, uint256 usdtOut); constructor(address token_, address usdt_, address pair_, address router_, address treasury_) { launch = msg.sender; token = IERC20(token_); usdt = IERC20(usdt_); pair = IV2Pair(pair_); router = IV2Router(router_); treasury = treasury_; IERC20(token_).forceApprove(router_, type(uint256).max); } function activate() external { if (msg.sender != launch || active) revert NotReady(); active = true; lastObservationTime = block.timestamp; lastCumulative = PoolMath.cumulative(pair, address(token)); } function updateOracle() external { if (!active) revert NotReady(); uint256 elapsed = block.timestamp - lastObservationTime; if (elapsed < ORACLE_PERIOD) revert NotReady(); uint256 current = PoolMath.cumulative(pair, address(token)); if (elapsed > ORACLE_MAX_WINDOW) { averagePriceX112 = 0; lastOracleTime = 0; } else { uint256 difference; unchecked { difference = current - lastCumulative; } averagePriceX112 = difference / elapsed; lastOracleTime = block.timestamp; } lastCumulative = current; lastObservationTime = block.timestamp; emit OracleUpdated(averagePriceX112, block.timestamp); } function settlementQuote() public view returns (uint256 amount, uint256 quotedOut, uint256 minimumOut) { if (!active || averagePriceX112 == 0 || block.timestamp - lastOracleTime > ORACLE_MAX_AGE || block.timestamp < lastSettlementTime + 60) revert NotReady(); (uint256 rToken, uint256 rUsdt) = PoolMath.reserves(pair, address(token)); if (rToken == 0 || rUsdt == 0) revert NotReady(); uint256 spot = Math.mulDiv(rUsdt, PoolMath.Q112, rToken); if (spot < Math.mulDiv(averagePriceX112, 9_200, 10_000) || spot > Math.mulDiv(averagePriceX112, 10_800, 10_000)) revert PriceProtection(); amount = Math.min(token.balanceOf(address(this)), PoolMath.maxInput(rToken)); uint256 historicalValue = Math.mulDiv(amount, averagePriceX112, PoolMath.Q112); if (historicalValue < MIN_SETTLEMENT) revert NotReady(); quotedOut = PoolMath.amountOut(amount, rToken, rUsdt); // Historical minimum is deliberately stricter than allowing 8% price drift // plus another 8% execution impact. Trade waits if either bound fails. minimumOut = Math.mulDiv(historicalValue, 9_975 * 9_200, 100_000_000); if (minimumOut == 0 || quotedOut < minimumOut) revert PriceProtection(); } function settle(uint256 deadline) external nonReentrant returns (uint256 received) { if (deadline < block.timestamp || deadline > block.timestamp + 120) revert NotReady(); (uint256 amount,, uint256 minimumOut) = settlementQuote(); lastSettlementTime = block.timestamp; uint256 beforeBalance = usdt.balanceOf(address(this)); address[] memory path = new address[](2); path[0] = address(token); path[1] = address(usdt); router.swapExactTokensForTokensSupportingFeeOnTransferTokens(amount, minimumOut, path, address(this), deadline); received = usdt.balanceOf(address(this)) - beforeBalance; if (received < minimumOut) revert PriceProtection(); usdt.safeTransfer(treasury, received); emit TaxesSettled(amount, received); } } contract ComputeRoll is ReentrancyGuard { using SafeERC20 for IERC20; // Fixed BSC SPACE ID Agent ID registry; no admin bypass or registry setter. address public constant AGENT_ID_REGISTRY = 0x60B9262456dE011F7d15a54CdD8c48bAaa8B022F; uint256 public constant TOKENS_PER_SHARE = 10_000_000_000 * 1e18; uint256 public constant COLD_SHARES = 10_000; uint256 public constant TOTAL_SHARES = 90_000; uint256 public constant WALLET_LIMIT = 20; uint256 public constant STAGE_SIZE = 1_000; uint256 public constant UNIT_USDT = 1e18; IERC20 public immutable usdt; IV2Router public immutable router; IV2Pair public immutable pair; Roll public immutable token; RollTaxVault public immutable taxVault; address public immutable treasury; uint256 public immutable startsAt; uint256 public immutable endsAt; uint256 public sold; bool public launched; bool public failed; uint256[81] public stagePrice; mapping(address => uint256) public mintedShares; mapping(address => uint256) public refundableShares; uint256 public totalRefunded; error InvalidConfiguration(); error SaleClosed(); error ShareLimit(); error PriceChanged(); error PriceProtection(); error RefundUnavailable(); error AgentIdRequired(); event Minted(address indexed account, uint256 shares, uint256 usdtPaid, uint256 totalSold); event Launched(uint256 timestamp, uint256 lpToTreasury); event BuybackBurned(uint256 usdtSpent, uint256 crlBurned); event SaleFailed(uint256 usdtRecovered, uint256 crlBurned); event Refunded(address indexed account, uint256 shares, uint256 usdtReturned); constructor(address usdt_, address router_, address treasury_, uint256 startTimestamp) { if (usdt_.code.length == 0 || router_.code.length == 0 || treasury_ == address(0) || IERC20Metadata(usdt_).decimals() != 18) revert InvalidConfiguration(); if (AGENT_ID_REGISTRY.code.length == 0 || !IAgentIdRegistry(AGENT_ID_REGISTRY).supportsInterface(0x80ac58cd)) revert InvalidConfiguration(); treasury = treasury_; usdt = IERC20(usdt_); router = IV2Router(router_); startsAt = startTimestamp == 0 ? block.timestamp : startTimestamp; if (startsAt < block.timestamp) revert InvalidConfiguration(); endsAt = startsAt + 7 days; Roll created = new Roll(address(this)); token = created; IV2Factory factory = IV2Factory(IV2Router(router_).factory()); address pool = factory.getPair(address(created), usdt_); if (pool == address(0)) pool = factory.createPair(address(created), usdt_); // The CRL address is new; a pre-created pair must have no LP supply. if (IV2Pair(pool).totalSupply() != 0) revert InvalidConfiguration(); pair = IV2Pair(pool); RollTaxVault vault = new RollTaxVault(address(created), usdt_, pool, router_, treasury_); taxVault = vault; created.configure(pool, address(vault)); IERC20(usdt_).forceApprove(router_, type(uint256).max); stagePrice[0] = UNIT_USDT; for (uint256 i = 1; i <= 80; ++i) stagePrice[i] = stagePrice[i - 1] * 11 / 10; } /// @notice Eligibility follows the actual caller's current on-chain ownership, /// not the wallet app, tx.origin, an NFT approval or a supplied beneficiary. /// Registry failure reverts (fail closed). Refunds and transfers do not use it. function hasAgentId(address account) public view returns (bool) { return account != address(0) && IAgentIdRegistry(AGENT_ID_REGISTRY).balanceOf(account) > 0; } function quoteMint(uint256 shares) public view returns (uint256 total, uint256 cold, uint256 post) { if (shares == 0 || shares > WALLET_LIMIT || sold + shares > TOTAL_SHARES) revert ShareLimit(); for (uint256 i; i < shares; ++i) { uint256 index = sold + i; if (index < COLD_SHARES) { total += UNIT_USDT; ++cold; } else { total += stagePrice[1 + (index - COLD_SHARES) / STAGE_SIZE]; ++post; } } } function buybackQuote(uint256 usdtAmount) external view returns (uint256 output, bool impactAllowed) { (uint256 ru, uint256 rt) = PoolMath.reserves(pair, address(usdt)); return (PoolMath.amountOut(usdtAmount, ru, rt), PoolMath.impactOK(usdtAmount, ru)); } function mint(uint256 shares, uint256 maxUSDT, uint256 minimumBuybackOut, uint256 deadline) external nonReentrant { if (failed || block.timestamp < startsAt || (!launched && block.timestamp >= endsAt)) revert SaleClosed(); if (!hasAgentId(msg.sender)) revert AgentIdRequired(); if (mintedShares[msg.sender] + shares > WALLET_LIMIT) revert ShareLimit(); if (deadline < block.timestamp || deadline > block.timestamp + 120) revert PriceProtection(); (uint256 cost, uint256 cold, uint256 post) = quoteMint(shares); if (cost > maxUSDT) revert PriceChanged(); uint256 beforeBalance = usdt.balanceOf(address(this)); usdt.safeTransferFrom(msg.sender, address(this), cost); if (usdt.balanceOf(address(this)) - beforeBalance != cost) revert InvalidConfiguration(); mintedShares[msg.sender] += shares; refundableShares[msg.sender] += cold; // Every cold share adds its exact USDT and CRL amounts to the SAME pair. // Direct pair minting avoids router ratio selection leaving user funds idle. for (uint256 i; i < cold; ++i) { usdt.safeTransfer(address(pair), UNIT_USDT); IERC20(address(token)).safeTransfer(address(pair), TOKENS_PER_SHARE); pair.mint(address(this)); ++sold; if (sold == COLD_SHARES) _launch(); } if (post != 0) { uint256 postCost = cost - cold * UNIT_USDT; uint256 buyback = postCost / 2; _buyback(buyback, minimumBuybackOut, deadline); usdt.safeTransfer(treasury, postCost - buyback); sold += post; } IERC20(address(token)).safeTransfer(msg.sender, shares * TOKENS_PER_SHARE); emit Minted(msg.sender, shares, cost, sold); } function _launch() private { launched = true; token.openTrading(); taxVault.activate(); uint256 lp = pair.balanceOf(address(this)); IERC20(address(pair)).safeTransfer(treasury, lp); emit Launched(block.timestamp, lp); } function _buyback(uint256 amount, uint256 minimumOut, uint256 deadline) private { (uint256 ru, uint256 rt) = PoolMath.reserves(pair, address(usdt)); if (!PoolMath.impactOK(amount, ru) || minimumOut == 0) revert PriceProtection(); uint256 currentQuote = PoolMath.amountOut(amount, ru, rt); if (minimumOut < Math.mulDiv(currentQuote, 9_200, 10_000)) revert PriceProtection(); address[] memory path = new address[](2); path[0] = address(usdt); path[1] = address(token); uint256 beforeBalance = token.balanceOf(address(this)); router.swapExactTokensForTokensSupportingFeeOnTransferTokens(amount, minimumOut, path, address(this), deadline); uint256 acquired = token.balanceOf(address(this)) - beforeBalance; if (acquired < minimumOut) revert PriceProtection(); token.burnHeld(acquired); emit BuybackBurned(amount, acquired); } function finalizeFailure() external nonReentrant { if (launched || failed || block.timestamp < endsAt) revert SaleClosed(); failed = true; uint256 beforeUSDT = usdt.balanceOf(address(this)); uint256 lp = pair.balanceOf(address(this)); if (lp != 0) { token.setRefundUnwind(true); IERC20(address(pair)).safeTransfer(address(pair), lp); pair.burn(address(this)); token.setRefundUnwind(false); } uint256 remaining = token.balanceOf(address(this)); token.burnHeld(remaining); emit SaleFailed(usdt.balanceOf(address(this)) - beforeUSDT, remaining); } function claimRefund(uint256 shares) external nonReentrant { if (!failed || shares == 0 || shares > refundableShares[msg.sender]) revert RefundUnavailable(); uint256 amount = shares * UNIT_USDT; if (usdt.balanceOf(address(this)) < amount) revert RefundUnavailable(); refundableShares[msg.sender] -= shares; totalRefunded += shares; token.burnRefund(msg.sender, shares * TOKENS_PER_SHARE); usdt.safeTransfer(msg.sender, amount); emit Refunded(msg.sender, shares, amount); } }