Skip to content
Verified contractExactMIT

SSCPublicSaleV1

Address0xebb892da6dad7705bc52481ea1117c7537a1372f
Balance

0.002175 ETH

 

Transactions

35

 

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
paris
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,339,646
Creation transaction
0x7653e9d6de…c990e49e85

contracts/SSCPublicSaleV1.sol

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";

interface AggregatorV3Interface {
    function decimals() external view returns (uint8);
    function latestRoundData() external view returns (
        uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound
    );
}

/**
 * @title  SSCPublicSaleV1
 * @notice Public sale 1.2B SSC (15% supply), paid in ETH (priced through Chainlink
 *         ETH/USD). Holds the SSC itself and doubles as the staking vault.
 *
 *         - Price: $0.010 at t0, +$0.002 every 2 weeks, flat at $0.030 (week 20+).
 *         - Duration: at most SALE_DURATION from t0; ends earlier on sell-out.
 *         - Per address: min $10 per buy, max $10,000 cumulative.
 *         - Purchase bonus by transaction value: <$1k 0%, ≥$1k 5%, ≥$2.5k 7.5%,
 *           ≥$5k 10%. Paid ONLY from bonusReserve (Marketing SSC deposited via
 *           fundBonus), never from the allocation or the reward pool; it vests in
 *           the same lot as the purchase. If the reserve runs short the buy is
 *           still filled with whatever bonus is left (minSscOut protects the buyer).
 *         - Every lot vests per second over 360 days from the purchase.
 *         - The buy that would overshoot the allocation is filled partially and
 *           the excess ETH refunded, so the allocation can actually sell out.
 *         - Unsold allocation is NOT burned: once the sale ends it (and leftover
 *           bonusReserve) is released into the staking reward pool.
 *
 *         SSC BOOKKEEPING — every SSC in the contract is in exactly one bucket
 *         (see sscBreakdown):
 *           principal owed to lots | unsold allocation (sale only) | bonusReserve
 *           (sale only) | reward already accrued to stakers | free reward.
 *         Anything not explicitly allocated is reward reserve. Reward is topped up
 *         by a plain SSC transfer — no deposit call needed.
 *         - The temporary SSC/ETH pool locks every DEX buy here as a 360-day lot
 *           (lockFromDex). Those lots are backed by SSC the pool sends in and do NOT
 *           count against the allocation or the per-address cap. The pool shares
 *           this contract's affiliate graph and commission ledger.
 *
 *         STAKING (SSCStakingV3 concept, per-tier APR): every lot — sale, DEX or
 *         stake — is staked in one of 4 tiers (30/90/180/360 days). Each tier has
 *         its own, independent owner-set APR (no multipliers); 0 = no new stakes
 *         and no further accrual. All APRs start at 0 and can only be set once the
 *         sale has ended. Lowering an APR never touches reward already accrued. Sale and DEX
 *         lots vest 360 days and sit in SALE_LOT_TIER (360d), earning its APR.
 *         Auto-halving across tiers: if the free reward pool cannot fund one
 *         REWARD_PERIOD at the set APRs, every tier is scaled down by the same factor.
 *
 *         Affiliate: ONE level (direct referrer only), 5% of the purchase's ETH,
 *         recorded and pull-based (claimCommissionEth). No commission to self, and
 *         none to a referrer that holds no lot of its own (an empty wallet cannot
 *         be an affiliate); the link is kept, so commission starts once they buy.
 */
contract SSCPublicSaleV1 is Ownable2Step, ReentrancyGuard, Pausable {
    using SafeERC20 for IERC20;

    // ── ALLOCATION & PRICE ──
    uint256 public constant MAX_SALE_SSC   = 1_200_000_000 * 1e18;
    uint256 public constant START_PRICE    = 10_000;           // 6-dec USD per SSC = $0.010
    uint256 public constant PRICE_STEP     = 2_000;            // +$0.002
    uint256 public constant MAX_PRICE      = 30_000;           // $0.030, then flat
    uint256 public constant PRICE_INTERVAL = 2 weeks;
    uint256 public constant SALE_DURATION  = 180 days;         // "6 bulan"
    uint256 public constant MIN_BUY_USD    = 10 * 1e6;
    uint256 public constant MAX_BUY_USD_PER_ADDRESS = 10_000 * 1e6;
    uint256 public constant VEST_DURATION  = 360 days;
    uint256 public constant BONUS_T1_USD = 1_000 * 1e6;    // 5%
    uint256 public constant BONUS_T2_USD = 2_500 * 1e6;    // 7.5%
    uint256 public constant BONUS_T3_USD = 5_000 * 1e6;    // 10%
    uint256 public constant PRICE_STALE_AFTER = 75 minutes;
    uint256 public constant SWEEP_DELAY = 180 days;
    uint8   public constant CCY_ETH = 1;                       // Purchased keeps V2/V3's layout

    // ── STAKING (V3 reward engine) ──
    uint256 public constant REWARD_PERIOD  = 360 days;
    uint256 public constant MAX_REWARD_BPS = 12_000;           // 120%/yr, binds (see V3)
    uint8   public constant NUM_TIERS      = 4;                // 30/90/180/360 days
    uint8   public constant SALE_LOT_TIER  = 3;                // sale & DEX lots = 360-day tier
    uint256 public constant MIN_GIFT       = 1_000 * 1e18;     // lot-spam guard: no dust lots on others

    // ── REFERRAL / COMMISSION ──
    uint256 public constant COMMISSION_BPS   = 500;            // 5%, direct referrer only
    uint256 public constant MAX_UPLINE_BATCH = 200;

    IERC20                public immutable sscToken;
    AggregatorV3Interface public immutable ethUsdFeed;

    address public pool;                    // SSC/ETH pool allowed to call lockFromDex
    bool    public saleOpen;
    bool    public saleEnded;
    uint256 public saleOpenedAt;            // t0 of the price schedule and the 6-month clock
    uint256 public saleClosedAt;

    uint256 public totalRaisedUsd;
    uint256 public totalEthIn;
    uint256 public totalSscSold;            // base only; counts against MAX_SALE_SSC
    uint256 public totalBonusGranted;       // from Marketing stock, outside the allocation
    uint256 public totalSscFromDex;         // DEX buys locked here, outside the allocation
    /// @dev Unclaimed SSC across all lots. A lot is only ever created when the
    ///      balance covers this plus the new lot, and finalize() burns only above it.
    uint256 public totalSscOwed;
    uint256 public totalSscClaimed;
    uint256 public totalUserStaked;         // via stake()/giftStake()
    /// @dev Marketing SSC earmarked for purchase bonuses. Only fundBonus() adds to
    ///      it, so a plain transfer can never be mistaken for bonus stock. Released
    ///      into the reward pool (set to 0) when the sale closes.
    uint256 public bonusReserve;

    // ─ Reward index PER TIER (V3 maths, ×4). rewardPool() is DERIVED from the balance.
    //   One storage slot per tier (audit L-3): apr/eff ≤ 12_000 fit uint16; index =
    //   Σ eff×dt ≤ 12_000 × 2^32 s ≈ 5e13 fits uint64; staked ≤ 8e27 fits uint96. ─
    struct Tier {
        uint16 aprBps;    // owner-set APR; 0 = inactive
        uint16 effBps;    // APR actually in force (after auto-halving)
        uint64 index;     // stored reward index
        uint96 staked;    // principal (amount − claimed) in this tier
    }
    Tier[4] public tiers;
    uint256 public lastRateUpdate;
    uint256 public totalRewardAccrued;      // accrued-but-unpaid (liability)
    uint256 public totalRewardPaid;

    struct Lot {
        uint256 amount;
        uint256 start;
        uint256 end;
        uint256 claimed;
        uint256 rewardAccrued;  // settled reward
        uint256 userIndex;      // position in tiers[tier].index
        uint256 tier;           // SALE_LOT_TIER for sale/DEX lots
    }
    mapping(address => Lot[]) internal _lots;
    mapping(address => uint256) public usdSpent;      // cumulative, for the per-address cap
    mapping(address => address) public referrer;

    mapping(address => uint256) public commissionEthClaimable;
    /// @dev Lifetime totals per affiliate — never decremented by a claim.
    mapping(address => uint256) public commissionEarnedEth;
    uint256 public commissionEthPool;

    error ZeroAddress();
    error ZeroAmount();
    error SaleNotActive();
    error SaleEnded();
    error SaleStillActive();
    error BelowMinBuy();
    error ExceedsMaxBuy();
    error InsufficientBacking();
    error ExceedsWithdrawable();
    error NoEth();
    error Slippage();
    error BadOraclePrice();
    error StaleOraclePrice();
    error IncompleteRound();
    error UseBuyWithEth();
    error NotPool();
    error BadUpline();
    error LengthMismatch();
    error BatchTooLarge();
    error BadLotIndex();
    error NothingVested();
    error NothingToClaim();
    error NoReward();
    error PoolEmpty();        // reward is due but the reward pool is empty
    error BadTier();
    error BadGiftTarget();
    error BelowMinGift();
    error TierDisabled();
    error RateTooHigh();
    error NoSurplus();
    error NoTokenBalance();
    error CannotRescueSsc();
    error EthSendFailed();
    error SweepTooEarly();

    // ─ Event convention (V3): indexed subject, indexed counterparty, amount,
    //   detail, timestamp. Purchased keeps the V2/V3 field layout (sscBonus = 0). ─
    event SaleOpened();
    event SaleClosed();
    event Purchased(
        address indexed buyer, uint8 currency, uint256 paidAmount, uint256 usdValue,
        uint256 sscBase, uint256 sscBonus, uint256 lotIndex, address indexed ref, uint256 timestamp
    );
    event DexLocked(address indexed buyer, address indexed pool, uint256 amount, uint256 lotIndex, uint256 timestamp);
    event Refunded(address indexed buyer, uint256 amount);
    event Claimed(address indexed user, uint256 amount, uint256 lotIndex, uint256 timestamp);
    event Staked(address indexed user, uint256 lotIndex, uint256 amount, uint256 timestamp);
    event Gifted(address indexed to, address indexed from, uint256 amount, uint256 lotIndex, uint256 timestamp);
    event RewardClaimed(address indexed user, address indexed upline, uint256 amount, uint256 lotIndex, uint256 timestamp);
    event TierAprUpdated(uint8 indexed tier, uint256 oldBps, uint256 newBps);
    event EffectiveRateUpdated(uint8 indexed tier, uint256 oldBps, uint256 newBps, uint256 timestamp);
    event RewardWithdrawn(address indexed to, uint256 amount);
    event BonusFunded(address indexed from, uint256 amount);
    event BonusReleased(uint256 amount);
    event PoolUpdated(address indexed oldPool, address indexed newPool);
    event ReferrerLinked(address indexed user, address indexed ref);
    event UplineOverridden(address indexed user, address indexed oldRef, address indexed newRef);
    event CommissionAccrued(address indexed affiliate, address indexed buyer, uint256 amount, uint8 level, uint256 timestamp);
    event CommissionClaimed(address indexed affiliate, uint256 amount, uint256 timestamp);
    event CommissionSwept(address indexed affiliate, address indexed to, uint256 amount, uint256 timestamp);
    event FundsWithdrawn(address indexed token, address indexed to, uint256 amount);
    event EthWithdrawn(address indexed to, uint256 amount);

    constructor(address _sscToken, address _ethUsdFeed, address _initialOwner)
        Ownable(_initialOwner)
    {
        if (_sscToken   == address(0)) revert ZeroAddress();
        if (_ethUsdFeed == address(0)) revert ZeroAddress();
        sscToken   = IERC20(_sscToken);
        ethUsdFeed = AggregatorV3Interface(_ethUsdFeed);
        lastRateUpdate = block.timestamp;
    }

    // ── REWARD INDEX (V3 maths, one index per tier) ──

    /// @dev Accrual since the last update, capped at REWARD_PERIOD → pending ≤ pool.
    function _elapsed() internal view returns (uint256 e) {
        e = block.timestamp - lastRateUpdate;
        if (e > REWARD_PERIOD) e = REWARD_PERIOD;
    }

    function _currentIndex(uint256 t) internal view returns (uint256) {
        Tier storage T = tiers[t];
        return uint256(T.index) + uint256(T.effBps) * _elapsed();
    }

    /// @dev Σ staked_t × effective_t — the reward liability growth rate (×10000).
    function _accrualRate() internal view returns (uint256 sum) {
        for (uint256 t = 0; t < NUM_TIERS; t++) sum += uint256(tiers[t].staked) * tiers[t].effBps;
    }

    function _currentAccrued() internal view returns (uint256) {
        return totalRewardAccrued + _accrualRate() * _elapsed() / (10000 * REWARD_PERIOD);
    }

    /// @dev Unsold allocation stays reserved for buyers while the sale runs; after
    ///      the close it is released into the reward pool.
    function _reservedAllocation() internal view returns (uint256) {
        return saleEnded ? 0 : MAX_SALE_SSC - totalSscSold;
    }

    /// @notice Reward reserve: every SSC NOT allocated to lots, to the unsold
    ///         allocation (during the sale) or to bonusReserve. Includes accrued-but-
    ///         unpaid reward. Grows with any plain SSC transfer into the contract.
    function rewardPool() public view returns (uint256) {
        uint256 bal  = sscToken.balanceOf(address(this));
        uint256 lock = totalSscOwed + _reservedAllocation() + bonusReserve;
        return bal > lock ? bal - lock : 0;
    }

    /// @notice Full bookkeeping of the SSC held here. The five buckets always sum
    ///         to `balance` (unless the contract is under-funded, see shortfall).
    function sscBreakdown() external view returns (
        uint256 balance,
        uint256 principalOwed,        // all lots, vested-unclaimed included
        uint256 unsoldAllocation,     // reserved for buyers; 0 once the sale ends
        uint256 bonusStock,           // Marketing, for purchase bonuses; 0 once the sale ends
        uint256 rewardAccrued,        // already owed to stakers (full, pre-multiplier)
        uint256 rewardFree,           // reward reserve not yet promised to anyone
        uint256 shortfall             // > 0 only if allocations exceed the balance
    ) {
        balance          = sscToken.balanceOf(address(this));
        principalOwed    = totalSscOwed;
        unsoldAllocation = _reservedAllocation();
        bonusStock       = bonusReserve;
        uint256 rp       = rewardPool();
        uint256 acc      = _currentAccrued();
        rewardAccrued    = acc < rp ? acc : rp;
        rewardFree       = rp - rewardAccrued;
        uint256 lock     = principalOwed + unsoldAllocation + bonusStock;
        shortfall        = lock > balance ? lock - balance : 0;
    }

    function _freeReward() internal view returns (uint256) {
        uint256 rp = rewardPool();
        uint256 reserved = _currentAccrued();
        return rp > reserved ? rp - reserved : 0;
    }

    /// @dev Auto-halving across tiers. demand = Σ staked_t × apr_t is what one
    ///      REWARD_PERIOD would cost (×10000). If the free pool cannot cover it,
    ///      every tier is scaled by free/demand, so one period never pays out more
    ///      than the pool holds. With a single active tier this is exactly V3's
    ///      min(ceiling, free/staked).
    function _effectiveBps(uint256 t, uint256 cover, uint256 demand) internal view returns (uint256) {
        uint256 apr = tiers[t].aprBps;
        if (apr == 0) return 0;
        if (demand == 0 || cover >= demand) return apr;
        return apr * cover / demand;
    }

    /// @dev cover = free reward ×10000, demand = Σ staked_t × apr_t. Computed ONCE
    ///      per refresh (one balanceOf) instead of once per tier. (audit L-3)
    function _coverDemand() internal view returns (uint256 cover, uint256 demand) {
        for (uint256 i = 0; i < NUM_TIERS; i++) demand += uint256(tiers[i].staked) * tiers[i].aprBps;
        cover = _freeReward() * 10000;
    }

    function _accrueIndex() internal {
        uint256 dt = _elapsed();
        if (dt != 0) {
            totalRewardAccrued += _accrualRate() * dt / (10000 * REWARD_PERIOD);
            for (uint256 t = 0; t < NUM_TIERS; t++) {
                Tier storage T = tiers[t];
                if (T.effBps != 0) T.index += uint64(uint256(T.effBps) * dt);
            }
        }
        lastRateUpdate = block.timestamp;
    }

    function _refreshRate() internal {
        (uint256 cover, uint256 demand) = _coverDemand();
        for (uint256 t = 0; t < NUM_TIERS; t++) {
            uint256 next = _effectiveBps(t, cover, demand);
            uint256 prev = tiers[t].effBps;
            if (next != prev) {
                tiers[t].effBps = uint16(next);
                emit EffectiveRateUpdated(uint8(t), prev, next, block.timestamp);
            }
        }
    }

    /// @dev Freeze accrual at the old rate → run → set the new rate.
    modifier syncsRate() {
        _accrueIndex();
        _;
        _refreshRate();
    }

    /// @dev Accrue a lot's reward over base (= amount-claimed). Call BEFORE base changes.
    function _settleLot(Lot storage lot) internal {
        uint256 idx  = _currentIndex(lot.tier);
        uint256 base = lot.amount - lot.claimed;
        if (base > 0 && idx > lot.userIndex) {
            lot.rewardAccrued += base * (idx - lot.userIndex) / (10000 * REWARD_PERIOD);
        }
        lot.userIndex = idx;
    }

    function _reduceAccrued(uint256 x) internal {
        totalRewardAccrued = totalRewardAccrued > x ? totalRewardAccrued - x : 0;
    }

    /// @notice Permissionless poke: refresh accrual and rate. Moves no funds.
    function sync() external syncsRate {}

    // ── SCHEDULE ──

    function saleEndsAt() public view returns (uint256) {
        return saleOpenedAt == 0 ? 0 : saleOpenedAt + SALE_DURATION;
    }

    /// @notice True while buying (and DEX lock-up) applies: opened, not closed,
    ///         within 6 months of t0 and not sold out.
    function saleActive() public view returns (bool) {
        return saleOpen && block.timestamp < saleEndsAt() && totalSscSold < MAX_SALE_SSC;
    }

    /// @notice Price now, 6-dec USD per SSC ($0.010 before the sale opens).
    function currentPrice() public view returns (uint256) {
        uint256 t0 = saleOpenedAt;
        if (t0 == 0) return START_PRICE;
        uint256 p = START_PRICE + (block.timestamp - t0) / PRICE_INTERVAL * PRICE_STEP;
        return p > MAX_PRICE ? MAX_PRICE : p;
    }

    // ── BUY ──

    function buyWithETH(address ref, uint256 minSscOut) external payable nonReentrant whenNotPaused syncsRate {
        if (msg.value == 0)  revert NoEth();
        if (!saleActive())   revert SaleNotActive();
        uint256 usd = _ethToUsd(msg.value);
        if (usd < MIN_BUY_USD) revert BelowMinBuy();

        uint256 price = currentPrice();
        uint256 ssc   = usd * 1e18 / price;                    // USD 6-dec / (USD 6-dec per SSC)
        uint256 ethUsed = msg.value;
        uint256 left  = MAX_SALE_SSC - totalSscSold;
        if (ssc > left) {                                      // last buy: fill the rest, refund the excess
            ssc     = left;
            uint256 usdUsed = (left * price + 1e18 - 1) / 1e18;    // round up in the sale's favour
            ethUsed = (msg.value * usdUsed + usd - 1) / usd;
            usd     = usdUsed;
        }
        if (usdSpent[msg.sender] + usd > MAX_BUY_USD_PER_ADDRESS) revert ExceedsMaxBuy();
        uint256 bonus = ssc * bonusBpsOf(usd) / 10000;
        if (bonus > bonusReserve) bonus = bonusReserve;            // fill without (full) bonus rather than revert
        if (ssc + bonus < minSscOut) revert Slippage();

        _linkReferrer(msg.sender, ref);
        // Release the sold SSC from the allocation / bonus buckets BEFORE booking the
        // lot, otherwise _createLot's backing check would count it twice.
        usdSpent[msg.sender] += usd;
        totalRaisedUsd       += usd;
        totalEthIn           += ethUsed;
        totalSscSold         += ssc;
        totalBonusGranted    += bonus;
        bonusReserve         -= bonus;
        uint256 lotIndex = _createLot(msg.sender, ssc + bonus, VEST_DURATION, SALE_LOT_TIER);

        _accrueCommission(msg.sender, ethUsed);
        if (totalSscSold == MAX_SALE_SSC) _close();

        emit Purchased(
            msg.sender, CCY_ETH, ethUsed, usd, ssc, bonus, lotIndex,
            referrer[msg.sender], block.timestamp
        );

        if (ethUsed < msg.value) {
            uint256 refund = msg.value - ethUsed;
            (bool ok, ) = payable(msg.sender).call{value: refund}("");
            if (!ok) revert EthSendFailed();
            emit Refunded(msg.sender, refund);
        }
    }

    modifier onlyPool() {
        if (msg.sender != pool || pool == address(0)) revert NotPool();
        _;
    }

    /// @notice Pool binds the buyer's referrer (same rules as a sale purchase) and
    ///         learns who gets the 5% commission on this DEX buy (0 = nobody).
    function linkReferrerFromPool(address user, address ref) external onlyPool returns (address) {
        _linkReferrer(user, ref);
        return _commissionReferrer(user);
    }

    /// @notice Who would earn commission on `buyer`'s next purchase if `ref` were
    ///         passed: the bound referrer, else `ref` — and only if that address
    ///         already holds a lot. For wallet quotes.
    function commissionReferrer(address buyer, address ref) external view returns (address up) {
        up = referrer[buyer];
        if (up == address(0) && ref != address(0) && ref != buyer) up = ref;
        if (up == address(0) || _lots[up].length == 0) up = address(0);
    }

    function _commissionReferrer(address buyer) internal view returns (address up) {
        up = referrer[buyer];
        if (up == buyer || _lots[up].length == 0) up = address(0);
    }

    /// @notice Called by the pool on every ETH→SSC swap: the pool has ALREADY
    ///         transferred `amount` SSC here; it becomes a 360-day lot for `buyer`.
    ///         msg.value = the buyer's 5% commission, credited to their referrer.
    function lockFromDex(address buyer, uint256 amount)
        external payable onlyPool nonReentrant whenNotPaused syncsRate returns (uint256 lotIndex)
    {
        if (buyer == address(0)) revert ZeroAddress();
        if (amount == 0)         revert ZeroAmount();
        lotIndex = _createLot(buyer, amount, VEST_DURATION, SALE_LOT_TIER);
        totalSscFromDex += amount;
        if (msg.value > 0) {
            address ref = _commissionReferrer(buyer);
            if (ref == address(0)) revert NotPool();               // pool bug: no one to credit
            _credit(ref, buyer, msg.value);
        }
        emit DexLocked(buyer, msg.sender, amount, lotIndex, block.timestamp);
    }

    /// @notice Bonus bps for ONE transaction of `usd` (6-dec), per the published table.
    function bonusBpsOf(uint256 usd) public pure returns (uint256) {
        if (usd >= BONUS_T3_USD) return 1000;
        if (usd >= BONUS_T2_USD) return 750;
        if (usd >= BONUS_T1_USD) return 500;
        return 0;
    }

    /// @dev Backing check covers EVERY reserved bucket, not just principal: the
    ///      unsold allocation, bonusReserve and reward already accrued to stakers.
    ///      So a pool (owner-set, hence not fully trusted) calling lockFromDex
    ///      without having transferred the SSC in cannot mint a lot out of the
    ///      allocation or out of stakers' reward. (audit M-1)
    function _createLot(address u, uint256 amount, uint256 duration, uint256 tier)
        internal returns (uint256)
    {
        uint256 lock = totalSscOwed + amount + _reservedAllocation() + bonusReserve + totalRewardAccrued;
        if (sscToken.balanceOf(address(this)) < lock) revert InsufficientBacking();
        totalSscOwed       += amount;
        tiers[tier].staked += uint96(amount);
        _lots[u].push(Lot({
            amount: amount, start: block.timestamp, end: block.timestamp + duration, claimed: 0,
            rewardAccrued: 0, userIndex: _currentIndex(tier), tier: tier
        }));
        return _lots[u].length - 1;
    }

    // ── STAKE ──

    function tierDuration(uint8 tier) public pure returns (uint256) {
        if (tier == 0) return 30 days;
        if (tier == 1) return 90 days;
        if (tier == 2) return 180 days;
        return 360 days;
    }

    /// @notice Stake SSC → a new lot that vests linearly over the tier's duration
    ///         and earns that tier's APR. Only tiers with APR > 0 are open.
    function stake(uint256 amount, uint8 tier) external nonReentrant whenNotPaused syncsRate returns (uint256 idx) {
        if (tier >= NUM_TIERS)       revert BadTier();
        if (tiers[tier].aprBps == 0) revert TierDisabled();
        if (amount == 0)             revert ZeroAmount();
        sscToken.safeTransferFrom(msg.sender, address(this), amount);
        idx = _createLot(msg.sender, amount, tierDuration(tier), tier);
        totalUserStaked += amount;
        emit Staked(msg.sender, idx, amount, block.timestamp);
    }

    /// @notice Stake on someone else's behalf as a gift. The lot belongs ENTIRELY to
    ///         `to` — the payer keeps no claim on the principal or its rewards.
    /// @dev Unlike stake(), a tier with APR 0 is allowed: the lot just vests and
    ///      starts earning once setAPR() turns that tier on (APR applies to old lots).
    ///      `to` must already have an upline, keeping gifts inside the programme.
    function giftStake(address to, uint256 amount, uint8 tier)
        external nonReentrant whenNotPaused syncsRate returns (uint256 idx)
    {
        if (tier >= NUM_TIERS) revert BadTier();
        if (to == msg.sender || referrer[to] == address(0)) revert BadGiftTarget();
        if (amount < MIN_GIFT) revert BelowMinGift();
        sscToken.safeTransferFrom(msg.sender, address(this), amount);
        idx = _createLot(to, amount, tierDuration(tier), tier);
        totalUserStaked += amount;
        emit Gifted(to, msg.sender, amount, idx, block.timestamp);
    }

    // ── PRINCIPAL CLAIMS ──

    function _vested(Lot storage lot) internal view returns (uint256) {
        if (block.timestamp >= lot.end)   return lot.amount;
        if (block.timestamp <= lot.start) return 0;
        return lot.amount * (block.timestamp - lot.start) / (lot.end - lot.start);
    }

    function _claimOne(address u, uint256 i) internal returns (uint256 c) {
        Lot storage lot = _lots[u][i];
        _settleLot(lot);                         // settle reward BEFORE base drops
        c = _vested(lot) - lot.claimed;
        if (c > 0) {
            lot.claimed += c;
            tiers[lot.tier].staked -= uint96(c);
            emit Claimed(u, c, i, block.timestamp);
        }
    }

    /// @dev O(n) over lots, no prune — indices stay stable. The guaranteed path is
    ///      per-lot (claimIndex). Lots are only ever self-created (buy / DEX buy /
    ///      stake all key on msg.sender), so nobody can spam another address.
    function claim() external nonReentrant syncsRate returns (uint256 amount) {
        uint256 n = _lots[msg.sender].length;
        for (uint256 i = 0; i < n; i++) amount += _claimOne(msg.sender, i);
        if (amount == 0) revert NothingVested();
        _payout(msg.sender, amount);
    }

    function claimIndex(uint256 i) external nonReentrant syncsRate returns (uint256 amount) {
        if (i >= _lots[msg.sender].length) revert BadLotIndex();
        amount = _claimOne(msg.sender, i);
        if (amount == 0) revert NothingVested();
        _payout(msg.sender, amount);
    }

    function _payout(address to, uint256 amount) internal {
        totalSscOwed    -= amount;
        totalSscClaimed += amount;
        sscToken.safeTransfer(to, amount);
    }

    // ── REWARD CLAIMS (V3) ──

    /// @dev Pays min(due, pool) out of the liability.
    function _claimRewardOne(address u, uint256 i, uint256 poolLeft) internal returns (uint256 pay, uint256 used) {
        Lot storage lot = _lots[u][i];
        _settleLot(lot);
        uint256 due = lot.rewardAccrued;
        if (due == 0 || poolLeft == 0) return (0, 0);
        used = due <= poolLeft ? due : poolLeft;
        lot.rewardAccrued = due - used;
        _reduceAccrued(used);
        pay = used;
        if (pay > 0) emit RewardClaimed(u, referrer[u], pay, i, block.timestamp);
    }

    function _claimRewardAll(address u) internal returns (uint256 pay) {
        uint256 poolLeft = rewardPool();
        uint256 n = _lots[u].length;
        for (uint256 i = 0; i < n; i++) {
            (uint256 p, uint256 used) = _claimRewardOne(u, i, poolLeft);
            pay += p; poolLeft -= used;
        }
        totalRewardPaid += pay;
    }

    function claimReward() external nonReentrant syncsRate returns (uint256 pay) {
        pay = _claimRewardAll(msg.sender);
        if (pay == 0) { if (pendingReward(msg.sender) > 0) revert PoolEmpty(); revert NoReward(); }
        sscToken.safeTransfer(msg.sender, pay);
    }

    function claimRewardIndex(uint256 i) external nonReentrant syncsRate returns (uint256 pay) {
        if (i >= _lots[msg.sender].length) revert BadLotIndex();
        (pay, ) = _claimRewardOne(msg.sender, i, rewardPool());
        if (pay == 0) { if (_pendingLot(_lots[msg.sender][i]) > 0) revert PoolEmpty(); revert NoReward(); }
        totalRewardPaid += pay;
        sscToken.safeTransfer(msg.sender, pay);
    }

    /// @notice Vested principal + reward of every lot in one transaction.
    function claimAll() external nonReentrant syncsRate returns (uint256 principalOut, uint256 rewardOut) {
        rewardOut = _claimRewardAll(msg.sender);            // reward first: settles at the old base
        uint256 n = _lots[msg.sender].length;
        for (uint256 i = 0; i < n; i++) principalOut += _claimOne(msg.sender, i);
        if (principalOut == 0 && rewardOut == 0) revert NothingToClaim();
        totalSscOwed    -= principalOut;
        totalSscClaimed += principalOut;
        sscToken.safeTransfer(msg.sender, principalOut + rewardOut);
    }

    // ── AFFILIATE (one level) ──

    /// @dev Bind once, for life. Silent on an invalid ref — a purchase must never
    ///      fail just because the referral code was bad. Self-referral is ignored.
    function _linkReferrer(address user, address ref) internal {
        if (referrer[user] != address(0)) return;
        if (ref == address(0) || ref == user) return;
        referrer[user] = ref;
        emit ReferrerLinked(user, ref);
    }

    /// @notice Owner override for support work. Redirects FUTURE commissions only.
    function setUpline(address user, address ref) public onlyOwner {
        if (user == address(0) || ref == user)   revert BadUpline();
        address old = referrer[user];
        referrer[user] = ref;
        emit UplineOverridden(user, old, ref);
    }

    function setUplinesBatch(address[] calldata users, address[] calldata refs) external onlyOwner {
        if (users.length != refs.length)     revert LengthMismatch();
        if (users.length > MAX_UPLINE_BATCH) revert BatchTooLarge();
        for (uint256 i = 0; i < users.length; i++) setUpline(users[i], refs[i]);
    }

    // ── COMMISSION (recorded, pull-based) ──

    /// @dev 5% of the ETH actually used by the purchase, out of that same ETH.
    ///      Only a referrer that holds a lot earns it.
    function _accrueCommission(address buyer, uint256 amount) internal {
        address ref = _commissionReferrer(buyer);
        if (ref == address(0)) return;
        uint256 amt = amount * COMMISSION_BPS / 10000;
        if (amt != 0) _credit(ref, buyer, amt);
    }

    function _credit(address ref, address buyer, uint256 amt) internal {
        commissionEthClaimable[ref] += amt;
        commissionEthPool           += amt;
        commissionEarnedEth[ref]    += amt;
        emit CommissionAccrued(ref, buyer, amt, 1, block.timestamp);
    }

    function claimCommissionEth() external nonReentrant returns (uint256 amount) {
        amount = commissionEthClaimable[msg.sender];
        if (amount == 0) revert NothingToClaim();
        commissionEthClaimable[msg.sender] = 0;
        commissionEthPool                 -= amount;
        (bool ok, ) = payable(msg.sender).call{value: amount}("");
        if (!ok) revert EthSendFailed();
        emit CommissionClaimed(msg.sender, amount, block.timestamp);
    }

    /// @notice Sweep commission never claimed, only after the sale has been
    ///         closed for SWEEP_DELAY. Lifetime totals are kept.
    function sweepCommission(address affiliate, address payable to) external onlyOwner nonReentrant returns (uint256 amount) {
        if (to == address(0)) revert ZeroAddress();
        if (!saleEnded || block.timestamp < saleClosedAt + SWEEP_DELAY) revert SweepTooEarly();
        amount = commissionEthClaimable[affiliate];
        if (amount == 0) revert NothingToClaim();
        commissionEthClaimable[affiliate] = 0;
        commissionEthPool                -= amount;
        (bool ok, ) = to.call{value: amount}("");
        if (!ok) revert EthSendFailed();
        emit CommissionSwept(affiliate, to, amount, block.timestamp);
    }

    // ── ORACLE ──

    function _ethToUsd(uint256 weiAmount) internal view returns (uint256) {
        (uint80 roundId, int256 price, , uint256 updatedAt, uint80 answeredInRound)
            = ethUsdFeed.latestRoundData();
        if (price <= 0)                                      revert BadOraclePrice();
        if (answeredInRound < roundId)                       revert IncompleteRound();
        if (block.timestamp - updatedAt > PRICE_STALE_AFTER) revert StaleOraclePrice();
        uint8 feedDecimals = ethUsdFeed.decimals();
        return weiAmount * uint256(price) / (10 ** feedDecimals) / 1e12;
    }

    function quoteEth(uint256 weiAmount) external view returns (uint256 usd6) {
        return _ethToUsd(weiAmount);
    }

    /// @notice SSC a buy of `weiAmount` gets right now (before the allocation clamp).
    function quoteSsc(uint256 weiAmount) external view returns (uint256 base, uint256 bonus) {
        uint256 usd = _ethToUsd(weiAmount);
        base  = usd * 1e18 / currentPrice();
        bonus = base * bonusBpsOf(usd) / 10000;
    }

    // ── SALE CONTROL & SETTERS ──

    /// @notice Open once (requires the full allocation on hand). Close is ONE-WAY.
    function setSaleOpen(bool open) external onlyOwner syncsRate {
        if (open == saleOpen) return;
        if (open) {
            if (saleEnded) revert SaleEnded();
            if (sscToken.balanceOf(address(this)) < totalSscOwed + MAX_SALE_SSC + bonusReserve) revert InsufficientBacking();
            saleOpen = true;
            saleOpenedAt = block.timestamp;
            emit SaleOpened();
        } else {
            _close();
        }
    }

    /// @dev Unsold allocation and leftover bonusReserve both fall into the reward
    ///      pool here (the allocation implicitly via _reservedAllocation()).
    function _close() internal {
        saleOpen = false; saleEnded = true; saleClosedAt = block.timestamp;
        uint256 left = bonusReserve;
        if (left > 0) { bonusReserve = 0; emit BonusReleased(left); }
        emit SaleClosed();
    }

    /// @notice Deposit Marketing SSC earmarked for purchase bonuses (needs approve).
    ///         A plain transfer is NOT bonus stock — it is reward.
    function fundBonus(uint256 amount) external onlyOwner nonReentrant {
        if (saleEnded)   revert SaleEnded();
        if (amount == 0) revert ZeroAmount();
        sscToken.safeTransferFrom(msg.sender, address(this), amount);
        bonusReserve += amount;
        emit BonusFunded(msg.sender, amount);
    }

    /// @notice Pool allowed to lock DEX buys and bind referrers. TRUST NOTE: a wrong
    ///         pool cannot mint unbacked lots (see _createLot) but CAN pre-bind a
    ///         referrer for any address that has none yet. Set once, with care.
    function setPool(address p) external onlyOwner {
        emit PoolUpdated(pool, p);
        pool = p;
    }

    /// @notice Set one tier's APR (bps/yr), 0..120%, independent of the other
    ///         tiers. Only after the sale has ended. Applies to EXISTING lots of the
    ///         tier from now on; reward accrued up to this call is settled first
    ///         (syncsRate) and is never reduced. 0 = the tier takes no new stakes
    ///         and its lots stop accruing. Tier 3 also drives every sale/DEX lot.
    ///         Effective APR may be lower (auto-halving).
    function setAPR(uint8 tier, uint256 bps) external onlyOwner syncsRate {
        if (tier >= NUM_TIERS)    revert BadTier();
        if (!saleEnded)           revert SaleStillActive();
        if (bps > MAX_REWARD_BPS) revert RateTooHigh();
        emit TierAprUpdated(tier, tiers[tier].aprBps, bps);
        tiers[tier].aprBps = uint16(bps);
    }

    function pause()   external onlyOwner { _pause(); }
    function unpause() external onlyOwner { _unpause(); }

    function renounceOwnership() public pure override {
        revert("renounce disabled");
    }

    // ── END OF SALE ──

    /// @notice Permissionless close once the 6 months have run out. The unsold
    ///         allocation is released into the reward pool — nothing is burned.
    function finalize() external nonReentrant syncsRate {
        if (saleEnded)         revert SaleEnded();
        if (saleOpenedAt == 0) revert SaleNotActive();         // never opened
        if (saleActive())      revert SaleStillActive();
        _close();
    }

    /// @notice Owner takes reward-pool SURPLUS only (after the sale): never
    ///         principal, never reward already accrued to stakers.
    function withdrawReward(address to, uint256 amount) external onlyOwner nonReentrant syncsRate {
        if (to == address(0)) revert ZeroAddress();
        if (!saleEnded) revert SaleStillActive();
        if (amount == 0 || amount > _freeReward()) revert ExceedsWithdrawable();
        sscToken.safeTransfer(to, amount);
        emit RewardWithdrawn(to, amount);
    }

    // ── OWNER WITHDRAWALS ──

    /// @notice Sweep a foreign ERC20 sent here by mistake. SSC is refused.
    function withdrawFunds(address token, address to) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        if (token == address(sscToken)) revert CannotRescueSsc();
        uint256 bal = IERC20(token).balanceOf(address(this));
        if (bal == 0) revert NoTokenBalance();
        IERC20(token).safeTransfer(to, bal);
        emit FundsWithdrawn(token, to, bal);
    }

    /// @notice Sweeps any ETH beyond the commission pool.
    function withdrawETH(address payable to) external onlyOwner nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        uint256 bal      = address(this).balance;
        uint256 reserved = commissionEthPool;
        if (bal <= reserved) revert NoSurplus();
        uint256 amount = bal - reserved;
        (bool ok, ) = to.call{value: amount}("");
        if (!ok) revert EthSendFailed();
        emit EthWithdrawn(to, amount);
    }

    receive() external payable { revert UseBuyWithEth(); }

    // ── VIEWS ──

    function lotCount(address u) external view returns (uint256) { return _lots[u].length; }

    function getLot(address u, uint256 i) external view returns (
        uint256 amount, uint256 start, uint256 end, uint256 claimed, uint256 claimableNow,
        uint256 rewardNow, uint256 tier
    ) {
        Lot storage l = _lots[u][i];
        return (l.amount, l.start, l.end, l.claimed, _vested(l) - l.claimed, _pendingLot(l), l.tier);
    }

    /// @dev Reward payable now for a lot, before any pool shortfall cap.
    function _pendingLot(Lot storage l) internal view returns (uint256) {
        uint256 due = l.rewardAccrued;
        uint256 idx = _currentIndex(l.tier);
        uint256 base = l.amount - l.claimed;
        if (base > 0 && idx > l.userIndex) due += base * (idx - l.userIndex) / (10000 * REWARD_PERIOD);
        return due;
    }

    function pendingReward(address u) public view returns (uint256 total) {
        Lot[] storage L = _lots[u];
        uint256 n = L.length;
        for (uint256 i = 0; i < n; i++) total += _pendingLot(L[i]);
    }

    /// @notice Per tier: owner-set APR and the APR that would be in force after a
    ///         sync now (auto-halving applied). bps/yr.
    function tierAprs() external view returns (uint256[4] memory setBps, uint256[4] memory effBps) {
        (uint256 cover, uint256 demand) = _coverDemand();
        for (uint256 t = 0; t < NUM_TIERS; t++) {
            setBps[t] = tiers[t].aprBps;
            effBps[t] = _effectiveBps(t, cover, demand);
        }
    }

    function lotsPage(address u, uint256 offset, uint256 limit)
        external view returns (Lot[] memory page, uint256 total)
    {
        Lot[] storage L = _lots[u];
        total = L.length;
        if (offset >= total || limit == 0) return (new Lot[](0), total);
        uint256 end  = offset + limit > total ? total : offset + limit;
        uint256 size = end - offset;
        page = new Lot[](size);
        for (uint256 i = 0; i < size; i++) page[i] = L[offset + i];
    }

    function claimable(address u) public view returns (uint256 total) {
        Lot[] storage L = _lots[u];
        uint256 n = L.length;
        for (uint256 i = 0; i < n; i++) total += _vested(L[i]) - L[i].claimed;
    }

    function positionSummary(address u) external view returns (
        uint256 owed, uint256 claimableNow, uint256 locked, uint256 usdSpentTotal,
        uint256 usdLeft, uint256 numLots, uint256 rewardNow
    ) {
        Lot[] storage L = _lots[u];
        uint256 n = L.length;
        for (uint256 i = 0; i < n; i++) owed += L[i].amount - L[i].claimed;
        claimableNow  = claimable(u);
        locked        = owed - claimableNow;
        usdSpentTotal = usdSpent[u];
        usdLeft       = MAX_BUY_USD_PER_ADDRESS - usdSpentTotal;
        numLots       = n;
        rewardNow     = pendingReward(u);
    }

    function remainingSsc() external view returns (uint256) { return MAX_SALE_SSC - totalSscSold; }
}

@openzeppelin/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/access/Ownable2Step.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

@openzeppelin/contracts/interfaces/IERC1363.sol

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

pragma solidity >=0.6.2;

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);
}

@openzeppelin/contracts/interfaces/IERC165.sol

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

pragma solidity >=0.4.16;

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

@openzeppelin/contracts/interfaces/IERC20.sol

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

pragma solidity >=0.4.16;

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

@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity >=0.4.16;

/**
 * @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);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.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 {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @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 {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 relies 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 relies 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}.
     * Oppositely, 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 `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

@openzeppelin/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;
    }
}

@openzeppelin/contracts/utils/Pausable.sol

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

@openzeppelin/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

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

/**
 * @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].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    // 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;

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

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

@openzeppelin/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

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

pragma solidity >=0.4.16;

/**
 * @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);
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.