Skip to content
Verified contractExactMIT

AGIMint

Address0xfa1c769029e15da23c528709def06da28623a3e8
Balance

0 ETH

 

Transactions

5

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,332,968
Creation transaction
0x91e2806abe…d5119367d0

src/AGIMint.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

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 {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {IDexPair, IWETH, DexMath} from "./interfaces/IDex.sol";
import {IAggregatorV3} from "./interfaces/IOracle.sol";
import {AGIToken} from "./AGIToken.sol";

/// @title AGIMint — agent-gated fair mint
/// @notice Agent-gated fair mint. Shares are sold on a rising price ladder. Up to the
///         open threshold each payment parks its liquidity share and mints inventory
///         for the pool; the threshold share opens the official pair, sends the LP to
///         the dead address, and switches trading on. After the pool opens, every mint
///         buys at a small discount to the pool price and pairs its liquidity share
///         into the pool, again burning the LP, while a floor line burns pool inventory
///         to keep the price from falling below a level set by total paid.
///
///         Eligibility is proven by an EIP-712 voucher from the gate signer (the signer
///         checks the caller's Agent-ID off-chain). The voucher binds the caller, the
///         Agent-ID and a nonce, so it cannot be replayed or used by another wallet.
contract AGIMint is ReentrancyGuard {
    using SafeERC20 for IERC20;

    // ------------------------------------------------------------- constants
    uint256 public constant TOTAL_SHARES = 444_000;
    uint256 public constant MAX_SUPPLY = 4_440_000_000 ether; // 4.44B

    uint256 public constant USER_SHARE = 11_000 ether; // minter tokens per share, pre-open (backtest-tuned for the flat-then-step ladder)
    uint256 public constant POOL_SHARE = 6_820 ether; // pool inventory per share, pre-open (backtest-tuned for the flat-then-step ladder)

    // Payment split: 80% to the pool, 20% to the treasury.
    uint256 public constant TREASURY_BPS = 2_000;
    // Post-open mint buys at 99% of the pool price.
    uint256 public constant MINT_PRICE_BPS = 9_900;

    // Floor line = totalPaid * FLOOR_LINE / LINE_DENOM. These three are deploy params
    // (tuned to the token's price scale); see immutables below.
    uint256 public constant RISE_NUM = 1_008; // at most +0.8% per transaction
    uint256 public constant RISE_DEN = 1_000;

    uint256 public constant FREE_PER_ID = 1; // base free shares per Agent-ID (lifted by invites/social)
    // Two SEPARATE free tracks, each 1 per Agent-ID (a WL agent can claim BOTH = 2 free; a non-WL
    // agent can only claim the public one). WL eligibility is attested in the voucher's `wl` flag
    // by the gate signer (the backend only signs wl=true for whitelisted Agent-IDs).
    uint256 public constant WL_FREE_CAP = 500;     // whitelist free shares (total)
    uint256 public constant PUBLIC_FREE_CAP = 500; // public free shares (total)
    uint256 public constant WL_PER_AGENT = 5;      // max WL free per Agent-ID (1 base social-task + invites)
    uint256 public constant PUBLIC_PER_AGENT = 5;  // max public free per Agent-ID (base + social tasks)
    uint256 public constant MAX_PER_TX = 10;
    uint256 public constant REFUND_WINDOW = 30 days; // auto-refund if the pool never opens in 30 days
    address public constant DEAD = 0x000000000000000000000000000000000000dEaD;

    // EIP-712
    bytes32 private constant DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 private constant MINT_TYPEHASH =
        keccak256("Mint(address minter,uint256 agentId,uint256 nonce,uint256 deadline)");
    bytes32 private constant FREE_TYPEHASH =
        keccak256("Free(address minter,uint256 agentId,bool wl,uint256 shares,uint256 nonce,uint256 deadline)");

    // ------------------------------------------------------------- immutables
    AGIToken public immutable token;
    IDexPair public immutable pair;
    address public immutable weth;
    address public immutable gateSigner; // off-chain mint-eligibility signer
    address public immutable treasury;
    uint256 public immutable MAX_PAID_PER_WALLET; // paid shares cap, per wallet
    uint256 public immutable OPEN_AT; // threshold share that opens the pool
    uint256 public immutable OPEN_TOKENS; // pool inventory seeded at open (= OPEN_AT * POOL_SHARE)
    uint256 public immutable mintStart; // unix time the mint opens; mint() and mintFree() revert before it (0 = no time gate)
    uint256 public immutable FLOOR_LINE; // floor-line numerator (tuned to price scale)
    uint256 public immutable LINE_DENOM; // floor-line denominator
    uint256 public immutable POOL_TOKEN_FLOOR; // min pool token reserve kept by floor burns
    // USD pricing oracle (shares are priced in USD, paid in ETH converted at mint time).
    address public immutable ethUsdFeed; // Chainlink ETH/USD aggregator proxy
    address public immutable sequencerFeed; // L2 sequencer uptime feed (0 to skip)
    uint256 public immutable feedHeartbeat; // max age of a fresh answer
    uint256 public immutable feedMin; // sanity floor for the answer
    uint256 public immutable feedMax; // sanity ceiling for the answer
    uint256 public immutable sequencerGrace; // grace period after sequencer restart
    bool private immutable _tokenIs0;

    // ------------------------------------------------------------- state
    uint256 public totalMinted;
    uint256 public totalPaid;
    bool public paused = true;
    bool public seeded;
    bool public renounced;
    uint256 public pendingQuote; // parked quote (WETH) for the opening pool
    uint256 public pendingTokens; // parked token inventory for the opening pool
    uint256 public openedTime;
    uint256 public firstMintTime; // timestamp of the first mint; starts the refund clock

    uint256 public wlFreeSupply;     // WL free shares claimed (cap WL_FREE_CAP)
    uint256 public publicFreeSupply; // public free shares claimed (cap PUBLIC_FREE_CAP)
    mapping(uint256 => uint256) public wlMinted;     // WL free claimed by Agent-ID (cap WL_PER_AGENT)
    mapping(uint256 => uint256) public publicMinted; // public free claimed by Agent-ID (cap PUBLIC_PER_AGENT)
    mapping(address => uint256) public paidMinted; // paid shares taken, by wallet
    mapping(bytes32 => bool) public spentNonce; // mint voucher replay guard
    // Pre-open refund ledger: shares minted and ETH paid, per minter, while the pool is closed.
    // 100% of pre-open payments are escrowed here; if the pool never opens, these are refundable.
    mapping(address => uint256) public refundShares;
    mapping(address => uint256) public refundPaid;

    event Minted(address indexed minter, uint256 indexed agentId, uint256 firstSerial, uint256 shares, uint256 paid);
    event FreeMinted(address indexed minter, uint256 indexed agentId, bool wl, uint256 shares);
    event Opened(uint256 quoteIn, uint256 tokensIn, uint256 lp);
    event PoolBurned(uint256 atShare, uint256 amount);
    event TaxSwapped(uint256 tokensIn, uint256 ethOut);
    event Seeded();
    event PausedSet(bool paused);
    event Renounced();
    event Refunded(address indexed minter, uint256 shares, uint256 amount);

    error NotTreasury();
    error AdminRenounced();
    error Paused();
    error NotSeeded();
    error BadShares();
    error SoldOut();
    error Quota();
    error OverMaxCost();
    error BadPayment();
    error StalePrice();
    error BadSignature();
    error Slippage();
    error BadConfig();
    error Replayed();
    error NotOpen();
    error NotStarted();
    error RefundClosed();
    error NothingToRefund();
    error NothingToSwap();
    error SwappedThisBlock();
    error ZeroAddress();
    error PayoutFailed();

    struct Config {
        address token;
        address weth;
        address gateSigner;
        address treasury;
        uint256 maxPaidPerWallet;
        uint256 openAt;
        uint256 floorLineNum;
        uint256 floorLineDenom;
        uint256 poolTokenFloor;
        address ethUsdFeed;
        address sequencerFeed;
        uint256 feedHeartbeat;
        uint256 feedMin;
        uint256 feedMax;
        uint256 sequencerGrace;
        uint256 mintStart;
    }

    constructor(Config memory c) {
        if (
            c.token == address(0) || c.weth == address(0) || c.gateSigner == address(0)
                || c.treasury == address(0) || c.ethUsdFeed == address(0)
        ) revert ZeroAddress();
        if (c.openAt == 0 || c.openAt > TOTAL_SHARES || c.floorLineDenom == 0) revert BadConfig();
        // free is a SEPARATE $0 track (mintFree), independent of the paid pool-open threshold
        if (c.maxPaidPerWallet == 0) revert BadConfig();
        if (c.feedMin == 0 || c.feedMin >= c.feedMax || c.feedHeartbeat == 0) revert BadConfig();
        token = AGIToken(payable(c.token));
        pair = IDexPair(token.pair());
        weth = c.weth;
        gateSigner = c.gateSigner;
        treasury = c.treasury;
        MAX_PAID_PER_WALLET = c.maxPaidPerWallet;
        OPEN_AT = c.openAt;
        OPEN_TOKENS = c.openAt * POOL_SHARE;
        FLOOR_LINE = c.floorLineNum;
        LINE_DENOM = c.floorLineDenom;
        POOL_TOKEN_FLOOR = c.poolTokenFloor;
        ethUsdFeed = c.ethUsdFeed;
        sequencerFeed = c.sequencerFeed;
        feedHeartbeat = c.feedHeartbeat;
        feedMin = c.feedMin;
        feedMax = c.feedMax;
        sequencerGrace = c.sequencerGrace;
        mintStart = c.mintStart;
        _tokenIs0 = pair.token0() == address(token);
    }

    receive() external payable {
        if (msg.sender != weth) revert BadPayment();
    }

    // ------------------------------------------------------------- views
    /// @notice Price of paid share `n` in whole US cents (these ARE the dollar-cents).
    ///         Flat $1.00 until the pool opens at paid share OPEN_AT, then one step up per
    ///         10,000-share band, reaching $8.04 on the final paid share (444,000). Free shares are a
    ///         separate $0 track (mintFree), so this ladder is paid-position only.
    function priceCents(uint256 n) public view returns (uint256) {
        if (n <= OPEN_AT) return 100; // $1.00 flat while funds accumulate before the pool opens
        uint256 band = (n - 1) / 10_000; // 0 in the flat region, then 1, 2, ... per 10k paid shares
        return 100 + band * 16; // +$0.16 per band; band 44 at share 444,000 => $8.04
    }

    /// @notice Price of share `n` in USD, 18 decimals. priceCents is whole dollar-cents,
    ///         so 100c * 1e16 = 1e18 = $1.00.
    function priceUsd(uint256 n) public view returns (uint256) {
        return priceCents(n) * 1e16;
    }

    /// @notice Total USD cost (18 dec) for the next `shares`.
    function costUsd(uint256 shares) public view returns (uint256 cost) {
        uint256 n = totalMinted;
        for (uint256 i; i < shares; i++) {
            cost += priceUsd(n + 1 + i);
        }
    }

    /// @notice ETH (wei) the next `shares` cost at the current oracle price.
    function quoteEth(uint256 shares) public view returns (uint256) {
        (uint256 px, uint256 unit) = _ethUsd();
        return _costEth(shares, px, unit);
    }

    /// @dev Reads and validates the ETH/USD feed; returns (answer, 10**decimals).
    function _ethUsd() internal view returns (uint256 px, uint256 unit) {
        if (sequencerFeed != address(0)) {
            (, int256 up, uint256 since,,) = IAggregatorV3(sequencerFeed).latestRoundData();
            // up == 0 means the sequencer is live; require a valid round up past the grace period.
            if (up != 0 || since == 0 || block.timestamp - since <= sequencerGrace) revert StalePrice();
        }
        (uint80 roundId, int256 answer,, uint256 updatedAt, uint80 answeredInRound) =
            IAggregatorV3(ethUsdFeed).latestRoundData();
        if (
            answer <= 0 || updatedAt == 0 || answeredInRound < roundId
                || block.timestamp > updatedAt + feedHeartbeat
        ) revert StalePrice();
        px = uint256(answer);
        if (px < feedMin || px > feedMax) revert StalePrice();
        unit = 10 ** IAggregatorV3(ethUsdFeed).decimals();
    }

    /// @dev ETH wei for a USD (18-dec) amount at price `px` scaled by `unit` (= 10**decimals).
    function _ethAt(uint256 usd18, uint256 px, uint256 unit) internal pure returns (uint256) {
        return usd18 * unit / px;
    }

    /// @dev ETH cost summed share-by-share so it matches the per-share settlement exactly.
    function _costEth(uint256 shares, uint256 px, uint256 unit) internal view returns (uint256 cost) {
        uint256 n = totalMinted;
        for (uint256 i; i < shares; i++) {
            cost += _ethAt(priceUsd(n + 1 + i), px, unit);
        }
    }


    function opened() public view returns (bool) {
        return totalMinted >= OPEN_AT;
    }

    function reserves() public view returns (uint256 rQuote, uint256 rToken) {
        (uint112 r0, uint112 r1,) = pair.getReserves();
        (rToken, rQuote) = _tokenIs0 ? (uint256(r0), uint256(r1)) : (uint256(r1), uint256(r0));
    }

    function circulating() public view returns (uint256) {
        return token.totalSupply() - token.balanceOf(address(pair)) - token.balanceOf(DEAD)
            - token.balanceOf(address(this));
    }

    function floorValue() public view returns (uint256) {
        return totalPaid * FLOOR_LINE / LINE_DENOM;
    }

    // ------------------------------------------------------------- treasury admin
    function _onlyTreasury() private view {
        if (msg.sender != treasury) revert NotTreasury();
        if (renounced) revert AdminRenounced();
    }

    function seed() external {
        _onlyTreasury();
        seeded = true;
        emit Seeded();
    }

    function setPaused(bool next) external {
        _onlyTreasury();
        if (!next && !seeded) revert NotSeeded();
        paused = next;
        emit PausedSet(next);
    }

    function setPoolBlocked(address pool, bool blocked) external {
        _onlyTreasury();
        token.setPoolBlocked(pool, blocked);
    }

    /// @notice Gives up pause and pool-blocking for good. Minting keeps running.
    function renounce() external {
        _onlyTreasury();
        if (!seeded) revert NotSeeded();
        renounced = true;
        paused = false;
        token.disableBlocks();
        emit Renounced();
    }


    // ------------------------------------------------------------- mint
    /// @param shares   number of shares to mint (1..MAX_PER_TX)
    /// @param agentId  the caller's Agent-ID, attested by the voucher
    /// @param nonce    voucher nonce (single use)
    /// @param deadline voucher expiry
    /// @param sig      gate-signer EIP-712 signature over Mint(minter,agentId,nonce,deadline)
    /// @param maxCost  max wei the caller will pay
    function mint(
        uint256 shares,
        uint256 agentId,
        uint256 nonce,
        uint256 deadline,
        bytes calldata sig,
        uint256 maxCost,
        uint256 minTokensOut
    ) external payable nonReentrant {
        if (paused) revert Paused();
        if (block.timestamp < mintStart) revert NotStarted();
        if (shares == 0 || shares > MAX_PER_TX) revert BadShares();
        if (totalMinted + shares > TOTAL_SHARES) revert SoldOut();
        if (block.timestamp > deadline) revert BadSignature();

        bytes32 digest = _digest(keccak256(abi.encode(MINT_TYPEHASH, msg.sender, agentId, nonce, deadline)));
        if (spentNonce[digest]) revert Replayed();
        _requireSigner(digest, sig, gateSigner);
        spentNonce[digest] = true;

        // Paid-only ladder. Free shares are a SEPARATE $0 track (mintFree), so paid minting runs
        // in parallel from the first share and never waits for the WL/free pool to sell out.
        if (paidMinted[msg.sender] + shares > MAX_PAID_PER_WALLET) revert Quota();
        paidMinted[msg.sender] += shares;

        // USD-priced, paid in ETH at the current oracle price. `maxCost` is max ETH wei.
        (uint256 px, uint256 unit) = _ethUsd();
        uint256 cost = _costEth(shares, px, unit);
        if (cost > maxCost || msg.value < cost) revert OverMaxCost();

        IWETH(weth).deposit{value: cost}();
        uint256 got = _mintShares(agentId, shares, cost, px, unit);
        if (got < minTokensOut) revert Slippage();

        // Refund surplus ETH last (checks-effects-interactions).
        uint256 surplus = msg.value - cost;
        if (surplus > 0) {
            (bool ok,) = msg.sender.call{value: surplus}("");
            if (!ok) revert PayoutFailed();
        }
    }

    // ------------------------------------------------------------- free mint ($0 giveaway, parallel)
    /// @notice Claim a free share ($0): one per Agent-ID on each track. `wl=true` draws from the
    ///         whitelist track (cap WL_FREE_CAP), `wl=false` from the public track (cap PUBLIC_FREE_CAP).
    ///         A whitelisted agent can claim BOTH (2 free); a non-WL agent only the public one. This
    ///         runs in PARALLEL with paid minting — it never blocks or waits for the ladder. Free
    ///         shares mint USER_SHARE to the agent only (no pool, no escrow, no pool-open effect).
    function mintFree(uint256 agentId, bool wl, uint256 shares, uint256 nonce, uint256 deadline, bytes calldata sig)
        external
        nonReentrant
    {
        if (paused) revert Paused();
        if (block.timestamp < mintStart) revert NotStarted();
        if (shares == 0) revert BadShares();
        if (block.timestamp > deadline) revert BadSignature();
        // The voucher binds `shares` = the allocation this agent EARNED off-chain (social tasks +
        // invites, tracked in Supabase). The contract enforces the hard per-agent and total caps.
        bytes32 digest =
            _digest(keccak256(abi.encode(FREE_TYPEHASH, msg.sender, agentId, wl, shares, nonce, deadline)));
        if (spentNonce[digest]) revert Replayed();
        _requireSigner(digest, sig, gateSigner);
        spentNonce[digest] = true;

        if (wl) {
            if (wlMinted[agentId] + shares > WL_PER_AGENT) revert Quota();
            if (wlFreeSupply + shares > WL_FREE_CAP) revert SoldOut();
            wlMinted[agentId] += shares;
            wlFreeSupply += shares;
        } else {
            if (publicMinted[agentId] + shares > PUBLIC_PER_AGENT) revert Quota();
            if (publicFreeSupply + shares > PUBLIC_FREE_CAP) revert SoldOut();
            publicMinted[agentId] += shares;
            publicFreeSupply += shares;
        }
        token.mint(msg.sender, shares * USER_SHARE); // $0 giveaway; MAX_SUPPLY cap enforced in the token
        emit FreeMinted(msg.sender, agentId, wl, shares);
    }

    // ------------------------------------------------------------- refund
    /// @notice If the pool never opens, every pre-open minter can reclaim 100% of what they
    ///         paid once REFUND_WINDOW has passed since the first mint. The minter's tokens
    ///         and the matching parked pool inventory are burned, the escrowed ETH is
    ///         returned, and the shares are released. Permanently off once the pool opens.
    function refund() external nonReentrant {
        if (opened()) revert RefundClosed();
        if (firstMintTime == 0 || block.timestamp < firstMintTime + REFUND_WINDOW) revert RefundClosed();
        uint256 shares = refundShares[msg.sender];
        uint256 amount = refundPaid[msg.sender];
        if (shares == 0 || amount == 0) revert NothingToRefund();

        // effects
        refundShares[msg.sender] = 0;
        refundPaid[msg.sender] = 0;
        totalMinted -= shares;
        totalPaid -= amount;
        pendingQuote -= amount;
        pendingTokens -= shares * POOL_SHARE;

        // un-mint the minter's stake and the parked pool inventory for these shares
        token.burnFromHolder(msg.sender, shares * USER_SHARE);
        token.burnFromHolder(address(this), shares * POOL_SHARE);

        // return the escrowed ETH (unwrap WETH), interactions last
        IWETH(weth).withdraw(amount);
        (bool ok,) = msg.sender.call{value: amount}("");
        if (!ok) revert PayoutFailed();
        emit Refunded(msg.sender, shares, amount);
    }

    struct Pool {
        uint256 q; // quote reserve (working)
        uint256 t; // token reserve (working)
        uint256 startQ;
        uint256 startT;
        uint256 circ;
        uint256 supply;
        uint256 addQ; // quote to add to the pool this tx
        uint256 addT; // tokens to add to the pool this tx
        uint256 burnT; // pool tokens to burn this tx (floor line)
        uint256 userT; // tokens owed to the minter this tx
    }

    function _mintShares(uint256 agentId, uint256 shares, uint256 cost, uint256 px, uint256 unit)
        private
        returns (uint256 minted)
    {
        if (firstMintTime == 0) firstMintTime = block.timestamp;
        uint256 first = totalMinted + 1;
        uint256 toTreasury;
        uint256 preShares; // pre-open shares this tx (refundable)
        uint256 prePaid; // pre-open ETH this tx (refundable)
        Pool memory p;
        bool live = opened();
        if (live) _loadPool(p);

        for (uint256 n = first; n < first + shares; n++) {
            uint256 pay = _ethAt(priceUsd(n), px, unit);
            totalPaid += pay;
            if (n <= OPEN_AT) {
                // Pre-open: escrow the FULL payment. The treasury cut is deferred to _open()
                // so a launch that never opens can refund 100% of what each minter paid.
                p.userT += USER_SHARE;
                pendingQuote += pay;
                pendingTokens += POOL_SHARE;
                token.mint(address(this), POOL_SHARE);
                preShares += 1;
                prePaid += pay;
                if (n == OPEN_AT) {
                    token.mint(msg.sender, p.userT);
                    minted += p.userT;
                    p.userT = 0;
                    _open();
                    live = true;
                    _loadPool(p);
                }
            } else {
                uint256 cut = pay * TREASURY_BPS / 10_000;
                toTreasury += cut;
                _curveShare(p, n, pay, pay - cut);
            }
        }
        totalMinted = first + shares - 1;
        // Record refundable stake only if the pool did NOT open in this tx. If it opened,
        // the pre-open funds are committed to the pool and refunds are permanently off.
        if (preShares > 0 && !live) {
            refundShares[msg.sender] += preShares;
            refundPaid[msg.sender] += prePaid;
        }

        if (p.userT > 0) {
            token.mint(msg.sender, p.userT);
            minted += p.userT;
        }
        if (live && p.addQ > 0) _settle(p);
        if (toTreasury > 0) IERC20(weth).safeTransfer(treasury, toTreasury);
        emit Minted(msg.sender, agentId, first, shares, cost);
    }

    function _loadPool(Pool memory p) private view {
        (p.q, p.t) = reserves();
        p.startQ = p.q;
        p.startT = p.t;
        p.circ = circulating();
        p.supply = token.totalSupply();
    }

    /// @dev Settles one post-open share against the working pool: mint tokens to the
    ///      buyer at 99% of pool price, pair the liquidity share in at pool price, then
    ///      apply the floor line by reducing the token reserve (burn) toward the target,
    ///      capped so the price rises at most RISE_NUM/RISE_DEN per transaction and never
    ///      below POOL_TOKEN_FLOOR. Equivalent to settling share by share.
    function _curveShare(Pool memory p, uint256 n, uint256 pay, uint256 lpQuote) private {
        uint256 userT = pay * p.t * 10_000 / (p.q * MINT_PRICE_BPS);
        uint256 lpT = (lpQuote * p.t + p.q - 1) / p.q;
        p.supply += userT + lpT;
        if (p.supply > MAX_SUPPLY) revert SoldOut();
        p.userT += userT;
        p.circ += userT;
        p.q += lpQuote;
        p.t += lpT;
        p.addQ += lpQuote;
        p.addT += lpT;

        // Floor line: keep circulating value (priced in quote) at or above the line.
        uint256 line = totalPaid * FLOOR_LINE / LINE_DENOM;
        if (p.circ * p.q / p.t >= line) return;
        uint256 byTarget = p.q * p.circ / line;
        uint256 byRise = (p.q * p.startT * RISE_DEN + p.startQ * RISE_NUM - 1) / (p.startQ * RISE_NUM);
        uint256 next = byTarget > byRise ? byTarget : byRise;
        if (next < POOL_TOKEN_FLOOR) next = POOL_TOKEN_FLOOR;
        if (next >= p.t) return;
        uint256 burn = p.t - next;
        p.t = next;
        p.burnT += burn;
        emit PoolBurned(n, burn);
    }

    function _settle(Pool memory p) private {
        IERC20(weth).safeTransfer(address(pair), p.addQ);
        token.mint(address(pair), p.addT);
        pair.mint(DEAD);
        if (p.burnT > 0) token.burnFromPair(p.burnT);
        pair.sync();
    }

    function _open() private {
        uint256 topUp = OPEN_TOKENS - pendingTokens;
        if (topUp > 0) token.mint(address(this), topUp);
        uint256 escrowed = pendingQuote; // 100% of pre-open payments, held in escrow
        pendingQuote = 0;
        pendingTokens = 0;
        uint256 treasuryCut = escrowed * TREASURY_BPS / 10_000; // the deferred 20%, paid now
        uint256 quoteIn = escrowed - treasuryCut; // 80% seeds the pool
        if (treasuryCut > 0) IERC20(weth).safeTransfer(treasury, treasuryCut);
        // Seed the pool with exactly `quoteIn`. If anyone donated WETH to the empty pair before
        // open, send only the shortfall so the opening price stays authoritative (not inflated by
        // the donation); the escrow we did not need to send then goes to the treasury. (audit L1)
        uint256 donated = IERC20(weth).balanceOf(address(pair));
        uint256 seedQuote = quoteIn > donated ? quoteIn - donated : 0;
        if (seedQuote > 0) IERC20(weth).safeTransfer(address(pair), seedQuote);
        uint256 leftover = quoteIn - seedQuote;
        if (leftover > 0) IERC20(weth).safeTransfer(treasury, leftover);
        IERC20(address(token)).safeTransfer(address(pair), OPEN_TOKENS);
        uint256 lp = pair.mint(DEAD);
        token.enableTrading();
        pair.sync();
        openedTime = block.timestamp;
        emit Opened(quoteIn, OPEN_TOKENS, lp);
    }

    // ------------------------------------------------------------- helpers
    function _digest(bytes32 structHash) private view returns (bytes32) {
        bytes32 domain = keccak256(
            abi.encode(DOMAIN_TYPEHASH, keccak256("AGI Mint"), keccak256("1"), block.chainid, address(this))
        );
        return keccak256(abi.encodePacked("\x19\x01", domain, structHash));
    }

    function _requireSigner(bytes32 digest, bytes calldata sig, address who) private pure {
        (address got, ECDSA.RecoverError err,) = ECDSA.tryRecover(digest, sig);
        if (err != ECDSA.RecoverError.NoError || got != who) revert BadSignature();
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts/contracts/utils/Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(
        bytes32 hash,
        bytes memory signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly ("memory-safe") {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/AGIToken.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IDexFactory, IDexPair, IWETH, DexMath} from "./interfaces/IDex.sol";

interface IMintTreasury {
    function treasury() external view returns (address);
}

/// @title AGIToken  (placeholder "AGI" — confirm name at launch)
/// @notice Fixed-cap ERC-20 minted only by the mint contract up to MAX_SUPPLY. Before trading is
///         enabled only the mint contract can move tokens (escrow/launch phase non-transferable).
///         After launch any wallet / plain contract can receive; rogue pools are refused. The
///         liquidity pair is the OFFICIAL Uniswap V2 pair.
///
///         Trade tax (immutable constants, no setter):
///           BUY  2.5% = 1.0% treasury (accrues here, swept to ETH) + 1.5% BURNED on the spot.
///           SELL 2.5% -> accrues here, swept to ETH for the treasury.
///           wallet<->wallet: 0% (untaxed).
///         No swap ever runs inside a user transfer; the treasury sweep is a separate,
///         permissionless, per-block, pool-capped call. The mint contract burns pool inventory
///         (floor line) via burnFromPair, and un-mints refunded pre-open stakes via burnFromHolder.
contract AGIToken is ERC20 {
    uint256 public constant MAX_SUPPLY = 4_440_000_000 ether; // 4,440,000,000 (4.44B hard cap)

    uint256 public constant BUY_TREASURY_BPS = 100;   // 1.0% buy -> treasury
    uint256 public constant BUY_BURN_BPS = 150;       // 1.5% buy -> burned
    uint256 public constant SELL_TAX_BPS = 250;       // 2.5% sell -> treasury

    uint256 private constant SWAP_FEE_BPS = 30;   // Uniswap V2 fee (0.30%)
    uint256 private constant MAX_SWEEP_BPS = 50;  // <=0.5% of pool token reserve per sweep
    uint256 private constant PROBE_GAS = 20_000;
    address public constant DEAD = 0x000000000000000000000000000000000000dEaD;
    address public constant V4_POOLMANAGER = 0x000000000004444c5dc75cB358380D2e3dE08A90; // Uniswap V4 singleton — never allow pooling there (tax bypass)

    address public immutable quote; // WETH
    address public immutable pair;  // official Uniswap V2 pair (this, WETH)

    address public deployer;
    address public minter;
    address public treasury;
    bool public tradingEnabled;
    bool public blocksDisabled;
    bool private _locked;
    uint256 public lastSweepBlock;
    mapping(address => bool) public blockedPool;

    event TradingEnabled(uint256 at);
    event PoolBlocked(address indexed pool, bool blocked);
    event BlocksDisabled();
    event TaxSwept(uint256 tokensIn, uint256 ethOut);
    event Burned(uint256 amount);

    error NotDeployer();
    error NotMinter();
    error AlreadyInitialized();
    error ZeroAddress();
    error TransfersClosed();
    error PoolRejected();
    error SupplyCap();
    error Reentrancy();
    error SweptThisBlock();
    error NothingToSweep();
    error NotTradingYet();
    error PayoutFailed();

    constructor(address weth_, address factory_) ERC20("AgentID", "AGI") {
        if (weth_ == address(0) || factory_ == address(0)) revert ZeroAddress();
        quote = weth_;
        pair = IDexFactory(factory_).createPair(address(this), weth_);
        deployer = msg.sender;
    }

    /// @notice One-time wiring of the mint contract; clears the deployer afterwards.
    function initialize(address minter_) external {
        if (msg.sender != deployer) revert NotDeployer();
        if (minter != address(0)) revert AlreadyInitialized();
        if (minter_ == address(0)) revert ZeroAddress();
        minter = minter_;
        deployer = address(0);
        address t = IMintTreasury(minter_).treasury();
        if (t == address(0)) revert ZeroAddress();
        treasury = t;
    }

    modifier onlyMinter() {
        if (msg.sender != minter) revert NotMinter();
        _;
    }

    modifier nonReentrant() {
        if (_locked) revert Reentrancy();
        _locked = true;
        _;
        _locked = false;
    }

    function mint(address to, uint256 amount) external onlyMinter {
        if (totalSupply() + amount > MAX_SUPPLY) revert SupplyCap();
        _mint(to, amount);
    }

    function enableTrading() external onlyMinter {
        if (tradingEnabled) return;
        tradingEnabled = true;
        emit TradingEnabled(block.timestamp);
    }

    /// @notice Moves pool inventory to the dead address for the floor-line mechanism. The mint
    ///         contract syncs the pair immediately afterwards. (pair & DEAD: no tax, no guard)
    function burnFromPair(uint256 amount) external onlyMinter {
        super._update(pair, DEAD, amount);
    }

    /// @notice Burns tokens from `holder` (supply down). Only the mint contract, only to un-mint a
    ///         refunded pre-open stake; bypasses the pre-trading transfer lock.
    function burnFromHolder(address holder, uint256 amount) external onlyMinter {
        _burn(holder, amount);
    }

    function setPoolBlocked(address pool, bool blocked) external onlyMinter {
        blockedPool[pool] = blocked;
        emit PoolBlocked(pool, blocked);
    }

    function disableBlocks() external onlyMinter {
        blocksDisabled = true;
        emit BlocksDisabled();
    }

    // ------------------------------------------------------------- pool guard
    function rejects(address to) public view returns (bool) {
        if (to == pair) return false;
        if (to == V4_POOLMANAGER) return true; // block pooling on Uniswap V4 (the V2 probe can't detect the singleton)
        if (blockedPool[to] && !blocksDisabled) return true;
        return _isOtherPair(to);
    }

    function _isOtherPair(address a) private view returns (bool) {
        uint256 size = a.code.length;
        if (size == 0) return false;
        if (size == 23) {
            bytes memory code = a.code;
            if (code[0] == 0xef && code[1] == 0x01 && code[2] == 0x00) return false; // EIP-7702 delegate
        }
        address t0 = _probe(a, 0x0dfe1681); // token0()
        if (t0 == address(this)) return _probe(a, 0xd21220a7) != address(0); // token1()
        if (t0 == address(0)) return false;
        return _probe(a, 0xd21220a7) == address(this);
    }

    function _probe(address a, bytes4 selector) private view returns (address out) {
        (bool ok, bytes memory data) = a.staticcall{gas: PROBE_GAS}(abi.encodeWithSelector(selector));
        if (!ok || data.length != 32) return address(0);
        uint256 word = abi.decode(data, (uint256));
        if (word >> 160 != 0) return address(0);
        out = address(uint160(word));
    }

    // ------------------------------------------------------------- transfers + tax
    function _update(address from, address to, uint256 value) internal override {
        if (from == address(0) || to == address(0)) {
            super._update(from, to, value); // mint / burn
            return;
        }
        address m = minter;
        if (!tradingEnabled) {
            if (from != m) revert TransfersClosed();
            super._update(from, to, value);
            return;
        }
        if (rejects(to)) revert PoolRejected();
        // mint contract and this token move untaxed (seeding, floor, sweeping)
        if (from == m || to == m || from == address(this) || to == address(this)) {
            super._update(from, to, value);
            return;
        }
        if (from == pair) {
            // BUY: 1.0% -> treasury (accrue here), 1.5% -> burned.
            uint256 toTreasury = (value * BUY_TREASURY_BPS) / 10_000;
            uint256 toBurn = (value * BUY_BURN_BPS) / 10_000;
            super._update(from, address(this), toTreasury);
            super._update(from, address(0), toBurn); // burn: supply down
            super._update(from, to, value - toTreasury - toBurn);
            emit Burned(toBurn);
        } else if (to == pair) {
            // SELL: 2.5% -> this contract (treasury path).
            uint256 tax = (value * SELL_TAX_BPS) / 10_000;
            super._update(from, address(this), tax);
            super._update(from, to, value - tax);
        } else {
            super._update(from, to, value); // wallet <-> wallet: untaxed
        }
    }

    // ------------------------------------------------------------- treasury sweep (token -> ETH)
    /// @notice Swap accrued tax tokens held here into ETH and send to the treasury. Permissionless,
    ///         once per block, capped at 0.5% of the pool token reserve per call (can never dump the
    ///         pool). No swap runs inside a user transfer.
    function swapTaxToTreasury() external nonReentrant {
        if (!tradingEnabled) revert NotTradingYet();
        if (lastSweepBlock == block.number) revert SweptThisBlock();

        (uint112 r0, uint112 r1,) = IDexPair(pair).getReserves();
        bool tokenIs0 = IDexPair(pair).token0() == address(this);
        uint256 rTok = tokenIs0 ? uint256(r0) : uint256(r1);
        uint256 rQuote = tokenIs0 ? uint256(r1) : uint256(r0);
        if (rTok == 0 || rQuote == 0) revert NotTradingYet();

        uint256 bal = balanceOf(address(this));
        uint256 cap = (rTok * MAX_SWEEP_BPS) / 10_000;
        uint256 amount = bal > cap ? cap : bal;
        if (amount == 0) revert NothingToSweep();
        lastSweepBlock = block.number;

        super._update(address(this), pair, amount); // untaxed (from == this)
        uint256 out = DexMath.amountOut(amount, rTok, rQuote, SWAP_FEE_BPS);
        (uint256 out0, uint256 out1) = tokenIs0 ? (uint256(0), out) : (out, uint256(0));
        uint256 before = IERC20(quote).balanceOf(address(this));
        IDexPair(pair).swap(out0, out1, address(this), "");
        uint256 wethOut = IERC20(quote).balanceOf(address(this)) - before;
        if (wethOut > 0) {
            IWETH(quote).withdraw(wethOut);
            (bool ok,) = payable(treasury).call{value: wethOut}("");
            if (!ok) revert PayoutFailed();
        }
        emit TaxSwept(amount, wethOut);
    }

    receive() external payable {} // ETH from WETH.withdraw during a sweep
}

src/interfaces/IDex.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

/// @notice Minimal Uniswap-V2 style interfaces. These point at a self-deployed minimal
///         V2 where no suitable DEX exists, or at the native V2 DEX otherwise (same ABI).

interface IDexFactory {
    function createPair(address tokenA, address tokenB) external returns (address pair);
    function getPair(address tokenA, address tokenB) external view returns (address pair);
}

interface IDexPair {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function mint(address to) external returns (uint256 liquidity);
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
    function sync() external;
}

interface IWETH {
    function deposit() external payable;
    function withdraw(uint256 amount) external;
}

/// @dev Constant-product output with a configurable fee (in bps) to match the venue.
library DexMath {
    function amountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut, uint256 feeBps)
        internal
        pure
        returns (uint256)
    {
        uint256 inWithFee = amountIn * (10_000 - feeBps);
        return (inWithFee * reserveOut) / (reserveIn * 10_000 + inWithFee);
    }
}

src/interfaces/IOracle.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

/// @notice Chainlink-compatible aggregator (AggregatorV3Interface subset).
interface IAggregatorV3 {
    function decimals() external view returns (uint8);
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "forge-std/=lib/forge-std/src/",
    "ds-test/=/root/agentvlad/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=/root/agentvlad/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=/root/agentvlad/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.