Skip to content
Verified contractExactMIT

StakingContract

Address0xe86d49ceb18c0261bc7a7562d0983df9faa43d16
Balance

0 ETH

 

Transactions

233

 

Compiler

solc 0.8.33

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.33+commit.64118f21
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,988,527
Creation transaction
0x1ad4c6e9bd…fa96dc68ef

src/Staking.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 {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IPositionManager} from "./interfaces/IPositionManager.sol";
import {IStaking} from "./interfaces/IStaking.sol";

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

/// @title StakingContract
/// @notice Multi-pool ERC-20 staking with:
///   - Per-pool APR (owner-settable, reward checkpoint on every change)
///   - 0.5 % Deposit fee on stake; split between referrer (default 20 %) and treasury
///   - Referral claim bonus (default 10 % of claimed reward) paid from treasury, NOT deducted from user
///   - Withdraw unlock queue: user requests unlock → 6-hour countdown → withdraw
///     Unlocked tokens earn NO reward from the moment of unlock request
///   - All staked principal lives in the PositionManager; rewards pulled from its reserve
///   - Rich view functions for frontend analytics
contract StakingContract is IStaking, Ownable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    // ═══════════════════════════════════════════════════════════════════════════
    //  CONSTANTS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @dev Precision multiplier for the reward-per-token accumulator.
    uint256 public constant PRECISION = 1e18;

    /// @dev Denominator for all basis-point rates (10 000 = 100 %).
    uint256 public constant DENOMINATOR = 10_000;

    /// @dev Deposit fee charged on every stake: 0.5 % = 50 bps.
    uint256 public constant DEPOSIT_FEE_RATE = 50;

    /// @dev Maximum APR the owner may set: 3 000 % expressed in bps.
    uint256 public constant MAX_APR = 3_000_000;

    /// @dev Maximum referral rate (stake fee split or claim bonus): 50 % = 5 000 bps.
    uint256 public constant MAX_REFERRAL_RATE = 5_000;

    uint256 private constant SECONDS_PER_YEAR = 365 days;

    // ═══════════════════════════════════════════════════════════════════════════
    //  MUTABLE GLOBALS  (owner-settable)
    // ═══════════════════════════════════════════════════════════════════════════

    IPositionManager public positionManager;

    /// @notice Recipient of the treasury portion of the deposit fee (depositFee − referralFee).
    ///         Defaults to address(0); if unset, treasury fee is sent to the owner.
    address public depositFeeAddress;

    /// @notice Percentage of the Deposite fee that goes to the referrer (bps, default 20 %).
    uint256 public referralFeeRate = 2_000;

    /// @notice Percentage of a claim amount sent as bonus to the referrer from treasury (bps, default 10 %).
    ///         This is NOT deducted from the user's claim — it comes from the pool treasury.
    uint256 public referralClaimRate = 1_000;

    /// @notice Time a user must wait after requesting unlock before withdrawing (default 6 h).
    uint256 public withdrawLockPeriod = 6 hours;

    // ═══════════════════════════════════════════════════════════════════════════
    //  STRUCTS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @dev Full on-chain state of a staking pool.
    struct PoolInfo {
        address token;                  // ERC-20 token for this pool
        uint256 totalEffectiveStaked;   // Σ (stakedAmount − unlockedAmount) — earns rewards
        uint256 totalUnlocked;          // Σ unlockedAmount — in unlock queue, no reward
        uint256 rewardPerTokenStored;   // Accumulated reward per token × PRECISION
        uint256 lastUpdateTime;         // Timestamp of last rewardPerTokenStored update
        uint256 currentApr;             // Active APR in bps (10 000 = 100 %)
        uint256 maxStake;               // Optional max stake of pool (0 = no limit)
        // Lifetime analytics
        uint256 totalFeesCollected;     // Gross Deposite fees collected ever
        uint256 totalReferralStakeFees; // Of totalFeesCollected, portion paid to referrers on stake
        uint256 totalReferralClaimFees; // Treasury outflow for referral claim bonuses
        uint256 totalRewardsPaid;       // Lifetime user rewards paid
        uint256 pendingReward;          // Rewards accrued since last checkpoint, not yet in rewardPerTokenStored
        bool    active;                 // False = no new stakes; existing stakers unaffected
    }

    /// @dev Per-user state for a specific pool.
    struct UserInfo {
        uint256 stakedAmount;        // Principal in the pool (gross after fee; includes unlockedAmount)
        uint256 unlockedAmount;      // Subset of stakedAmount currently in the unlock queue
        uint256 unlockRequestTime;   // Timestamp when the current unlock was requested (0 if none)
        uint256 rewardPerTokenPaid;  // rewardPerTokenStored snapshot at last settlement
        uint256 pendingReward;       // Accrued but unclaimed reward tokens
        address referrer;            // Referrer (set once on first stake with a referrer)
        // Lifetime analytics per user per pool
        uint256 totalDeposited;      // Lifetime net principal deposited (after fee)
        uint256 totalWithdrawn;      // Lifetime principal withdrawn
        uint256 totalRewardsClaimed; // Lifetime rewards claimed
        uint256 totalReferralEarned; // Lifetime earnings as a referrer (stake + claim bonuses)
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //  STORAGE
    // ═══════════════════════════════════════════════════════════════════════════

    PoolInfo[] public pools;

    /// @notice Total number of unique addresses that have ever staked (never decremented).
    uint256 public totalInvestors;

    /// @dev Tracks whether an address has ever staked (to avoid double-counting).
    mapping(address => bool) private _isInvestor;

    /// @dev token → poolId + 1 (0 means not listed). Prevents duplicate pools per token.
    mapping(address => uint256) private _tokenPoolId;

    /// @dev poolId → user → UserInfo
    mapping(uint256 => mapping(address => UserInfo)) public userInfo;

    /// @dev poolId → referrer → stake-fee earnings (subset of UserInfo.totalReferralEarned)
    mapping(uint256 => mapping(address => uint256)) public referrerStakeFeeEarned;

    /// @dev poolId → referrer → claim-bonus earnings (subset of UserInfo.totalReferralEarned)
    mapping(uint256 => mapping(address => uint256)) public referrerClaimBonusEarned;

    /// @dev Per-referrer rate overrides. When set, these take precedence over the global rates.
    struct ReferrerConfig {
        uint256 feeRate;      // custom stake referral fee rate (bps of deposit fee)
        uint256 claimRate;    // custom claim bonus rate (bps of reward)
        bool    hasFeeRate;   // true = use feeRate, false = use global referralFeeRate
        bool    hasClaimRate; // true = use claimRate, false = use global referralClaimRate
    }
    mapping(address => ReferrerConfig) public referrerConfig;

    // ═══════════════════════════════════════════════════════════════════════════
    //  EVENTS
    // ═══════════════════════════════════════════════════════════════════════════

    event PoolAdded(uint256 indexed poolId, address indexed token, uint256 apr);
    event PoolActiveChanged(uint256 indexed poolId, bool active);
    event APRUpdated(uint256 indexed poolId, uint256 oldAPR, uint256 newAPR);
    event ReferralFeeRateUpdated(uint256 oldRate, uint256 newRate);
    event ReferralClaimRateUpdated(uint256 oldRate, uint256 newRate);
    event ReferrerFeeRateSet(address indexed referrer, uint256 rate);
    event ReferrerFeeRateCleared(address indexed referrer);
    event ReferrerClaimRateSet(address indexed referrer, uint256 rate);
    event ReferrerClaimRateCleared(address indexed referrer);
    event WithdrawLockPeriodUpdated(uint256 oldPeriod, uint256 newPeriod);
    event PositionManagerUpdated(address indexed previous, address indexed next);
    event DepositFeeAddressUpdated(address indexed previous, address indexed next);
    event MaxStakeSet(uint256 indexed poolId, uint256 maxStake);
    event Staked(
        uint256 indexed poolId,
        address indexed user,
        uint256 netAmount,
        uint256 depositFee,
        address referrer,
        uint256 referralFee
    );
    event UnlockRequested(
        uint256 indexed poolId,
        address indexed user,
        uint256 amount,
        uint256 availableAt
    );
    event UnlockCancelled(uint256 indexed poolId, address indexed user, uint256 amount);
    /// @dev Emitted on every withdraw (amount=0 = pure reward claim, amount>0 = principal + reward).
    event Withdrawn(
        uint256 indexed poolId,
        address indexed user,
        uint256 amount
    );
    /// @dev Emitted on reward claims triggered by any action (stake, requestUnlock, cancelUnlock, withdraw). amount=0 for pure claim actions; >0 when claim is part of a withdraw.
    event RewardClaimed(
        uint256 indexed poolId,
        address indexed user,
        uint256 rewardClaimed,
        address referrer,
        uint256 referralClaimBonus
    );

    // ═══════════════════════════════════════════════════════════════════════════
    //  MODIFIERS
    // ═══════════════════════════════════════════════════════════════════════════

    modifier poolExists(uint256 poolId) {
        require(poolId < pools.length, "StakingContract: invalid pool ID");
        _;
    }

    modifier validPool(uint256 poolId) {
        require(poolId < pools.length, "StakingContract: invalid pool ID");
        require(pools[poolId].active, "StakingContract: pool not active");
        _;
    }

    /// @dev Checkpoints the pool's rewardPerToken and settles pending rewards for `user`
    ///      before executing the body. Uses the user's effective staked balance (stakedAmount − unlockedAmount).
    modifier updateReward(uint256 poolId, address user) {
        _checkpointPool(poolId);
        if (user != address(0)) {
            _settleUser(poolId, user);
        }
        _;
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //  CONSTRUCTOR
    // ═══════════════════════════════════════════════════════════════════════════

    constructor(address _positionManager) Ownable(msg.sender) {
        require(_positionManager != address(0), "StakingContract: zero PM address");
        positionManager = IPositionManager(_positionManager);
        depositFeeAddress = msg.sender;
    }

    receive() external payable {}

    // ═══════════════════════════════════════════════════════════════════════════
    //  OWNER ADMINISTRATION
    // ═══════════════════════════════════════════════════════════════════════════

    // ─── Pool management ────────────────────────────────────────────────────

    /// @notice Add a new staking pool.
    /// @param token  ERC-20 token address.
    /// @param apr    Initial APR in basis points (10 000 = 100 %).
    /// @return poolId  Index of the newly created pool.
    function addPool(address token, uint256 apr) external onlyOwner returns (uint256 poolId) {
        require(token != address(0), "StakingContract: zero token");
        require(token.code.length > 0, "StakingContract: token is not a contract");
        require(apr <= MAX_APR, "StakingContract: APR exceeds max");
        require(_tokenPoolId[token] == 0, "StakingContract: token already listed");

        poolId = pools.length;
        pools.push(
            PoolInfo({
                token:                  token,
                totalEffectiveStaked:   0,
                totalUnlocked:          0,
                rewardPerTokenStored:   0,
                pendingReward:          0,
                lastUpdateTime:         block.timestamp,
                currentApr:             apr,
                maxStake:               0,
                totalFeesCollected:     0,
                totalReferralStakeFees: 0,
                totalReferralClaimFees: 0,
                totalRewardsPaid:       0,
                active:                 true
            })
        );
        _tokenPoolId[token] = poolId + 1; // store as 1-indexed so 0 means "not listed"
        emit PoolAdded(poolId, token, apr);
    }

    /// @notice Returns true when `token` is registered as a staking pool token.
    function isPoolToken(address token) external view returns (bool) {
        return _tokenPoolId[token] != 0;
    }

    /// @notice Returns the pool ID assigned to `token`.
    function getPoolId(address token) external view returns (uint256) {
        uint256 id = _tokenPoolId[token];
        require(id != 0, "StakingContract: unsupported token");
        return id - 1;
    }

    /// @notice Enable or disable staking in a pool. Existing stakers are unaffected.
    function setPoolActive(uint256 poolId, bool active) external onlyOwner poolExists(poolId) {
        pools[poolId].active = active;
        emit PoolActiveChanged(poolId, active);
    }

    /// @notice Update the APR for a pool.
    ///         Checkpoints the reward accumulator first so historical rewards use the old rate.
    /// @param newAPR  New APR in basis points.
    function setAPR(uint256 poolId, uint256 newAPR) external onlyOwner poolExists(poolId) {
        require(newAPR <= MAX_APR, "StakingContract: APR exceeds max");
        _checkpointPool(poolId); // lock in rewards at old APR
        uint256 oldAPR = pools[poolId].currentApr;
        pools[poolId].currentApr = newAPR;
        emit APRUpdated(poolId, oldAPR, newAPR);
    }

    // ─── Global rate settings ────────────────────────────────────────────────

    /// @notice Set the fraction of the Deposite fee that goes to the referrer on stake.
    /// @param rate  Basis points (e.g. 2 000 = 20 %).
    function setReferralFeeRate(uint256 rate) external onlyOwner {
        require(rate <= MAX_REFERRAL_RATE, "StakingContract: rate > 50%");
        uint256 old = referralFeeRate;
        referralFeeRate = rate;
        emit ReferralFeeRateUpdated(old, rate);
    }

    /// @notice Set the fraction of a claim amount paid as bonus to the referrer (from treasury).
    /// @param rate  Basis points (e.g. 1 000 = 10 %).
    function setReferralClaimRate(uint256 rate) external onlyOwner {
        require(rate <= MAX_REFERRAL_RATE, "StakingContract: rate > 50%");
        uint256 old = referralClaimRate;
        referralClaimRate = rate;
        emit ReferralClaimRateUpdated(old, rate);
    }

    /// @notice Change the unlock lock period (default 6 hours, min 1 minute, max 30 days).
    function setWithdrawLockPeriod(uint256 period) external onlyOwner {
        require(period >= 1 minutes, "StakingContract: lock period too short");
        require(period <= 7 days, "StakingContract: lock period exceeds 7 days");
        uint256 old = withdrawLockPeriod;
        withdrawLockPeriod = period;
        emit WithdrawLockPeriodUpdated(old, period);
    }

    // ─── Per-referrer custom rates ────────────────────────────────────────────

    /// @notice Give a specific referrer a custom stake-fee rate.
    ///         Overrides the global `referralFeeRate` for this referrer only.
    /// @param referrer  The referrer address.
    /// @param rate      Rate in bps (e.g. 3 000 = 30 %). Must be ≤ DENOMINATOR.
    function setReferrerFeeRate(address referrer, uint256 rate) external onlyOwner {
        require(referrer != address(0), "StakingContract: zero referrer");
        require(rate <= MAX_REFERRAL_RATE, "StakingContract: rate > 50%");
        referrerConfig[referrer].feeRate    = rate;
        referrerConfig[referrer].hasFeeRate = true;
        emit ReferrerFeeRateSet(referrer, rate);
    }

    /// @notice Remove a referrer's custom stake-fee rate (revert to global).
    function clearReferrerFeeRate(address referrer) external onlyOwner {
        referrerConfig[referrer].hasFeeRate = false;
        emit ReferrerFeeRateCleared(referrer);
    }

    /// @notice Give a specific referrer a custom claim-bonus rate.
    ///         Overrides the global `referralClaimRate` for this referrer only.
    /// @param referrer  The referrer address.
    /// @param rate      Rate in bps (e.g. 1 500 = 15 %). Must be ≤ DENOMINATOR.
    function setReferrerClaimRate(address referrer, uint256 rate) external onlyOwner {
        require(referrer != address(0), "StakingContract: zero referrer");
        require(rate <= MAX_REFERRAL_RATE, "StakingContract: rate > 50%");
        referrerConfig[referrer].claimRate    = rate;
        referrerConfig[referrer].hasClaimRate = true;
        emit ReferrerClaimRateSet(referrer, rate);
    }

    /// @notice Remove a referrer's custom claim-bonus rate (revert to global).
    function clearReferrerClaimRate(address referrer) external onlyOwner {
        referrerConfig[referrer].hasClaimRate = false;
        emit ReferrerClaimRateCleared(referrer);
    }

    /// @notice Replace the PositionManager (e.g. for upgrades).
    function setPositionManager(address newPM) external onlyOwner {
        require(newPM != address(0), "StakingContract: zero address");
        emit PositionManagerUpdated(address(positionManager), newPM);
        positionManager = IPositionManager(newPM);
    }

    /// @notice Set the recipient address for the treasury portion of deposit fees.
    ///         Pass address(0) to revert to sending fees to the owner.
    function setDepositFeeAddress(address addr) external onlyOwner {
        emit DepositFeeAddressUpdated(depositFeeAddress, addr);
        depositFeeAddress = addr;
    }

    /// @notice Set a max stake for the pool. 0 means no limit.
    function setMaxStake(uint256 poolId, uint256 maxStake) external onlyOwner poolExists(poolId) {
        pools[poolId].maxStake = maxStake;
        emit MaxStakeSet(poolId, maxStake);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //  USER ACTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Stake `amount` tokens into `poolId`.
    ///
    ///  Fee flow on stake:
    ///    depositFee  = amount × 0.5 %
    ///    referralFee  = depositFee × referralFeeRate   → sent to referrer immediately
    ///    treasuryFee  = depositFee − referralFee       → held in pool treasury
    ///    netAmount    = amount − depositFee            → forwarded to PositionManager
    ///
    /// @param poolId    Target pool.
    /// @param amount    Gross token amount (before fee).
    /// @param referrer  Referrer address (address(0) for none). Stored once on first stake.
    function stake(
        uint256 poolId,
        uint256 amount,
        address referrer
    ) public payable nonReentrant validPool(poolId) updateReward(poolId, msg.sender) {
        require(amount > 0, "StakingContract: zero amount");
        require(referrer != msg.sender, "StakingContract: self-referral");

        PoolInfo storage pool = pools[poolId];
        UserInfo storage user = userInfo[poolId][msg.sender];

        // Persist referrer on first interaction
        if (user.referrer == address(0) && referrer != address(0)) {
            user.referrer = referrer;
        }

        // ── Auto-claim pending rewards before adding new stake (MasterChef pattern) ──
        _claimRewardsForPool(poolId, msg.sender);

        if (msg.value > 0) {
            require(poolId == 0, "StakingContract: only pool 0 accepts ETH");
            amount = msg.value;
            IWETH(pool.token).deposit{value: amount}();
        } else {
            // Pull tokens from the caller
            IERC20(pool.token).safeTransferFrom(msg.sender, address(this), amount);
        }

        // ── Deposite fee (0.5 %) ─────────────────────────────────────────────
        uint256 depositFee = (amount * DEPOSIT_FEE_RATE) / DENOMINATOR;
        uint256 netAmount   = amount - depositFee;

        // ── Referral portion of Deposite fee ─────────────────────────────────
        address activeReferrer = user.referrer;
        uint256 refFee         = 0;
        uint256 effectiveFeeRate = activeReferrer != address(0) ? _referralFeeRate(activeReferrer) : 0;
        if (activeReferrer != address(0) && effectiveFeeRate > 0) {
            refFee = (depositFee * effectiveFeeRate) / DENOMINATOR;
            IERC20(pool.token).safeTransfer(activeReferrer, refFee);

            referrerStakeFeeEarned[poolId][activeReferrer] += refFee;
            userInfo[poolId][activeReferrer].totalReferralEarned += refFee;
            pool.totalReferralStakeFees += refFee;
        }

        // ── Treasury portion of deposit fee → depositFeeAddress (or owner) ───
        uint256 treasuryFee = depositFee - refFee;
        pool.totalFeesCollected += depositFee;

        // ── Forward net principal to PositionManager ─────────────────────────
        IERC20(pool.token).safeTransfer(address(positionManager), netAmount);
        positionManager.recordDeposit(poolId, pool.token, netAmount);

        // ── Forward treasury fee to configured fee recipient ─────────────────
        if (treasuryFee > 0) {
            address feeRecipient = depositFeeAddress != address(0) ? depositFeeAddress : owner();
            IERC20(pool.token).safeTransfer(feeRecipient, treasuryFee);
        }

        // ── Update state ──────────────────────────────────────────────────────
        user.stakedAmount            += netAmount;
        user.totalDeposited          += netAmount;
        pool.totalEffectiveStaked    += netAmount;

        if(pool.maxStake > 0) {
            require(pool.totalEffectiveStaked <= pool.maxStake, "StakingContract: stake exceeds max");
        }

        // ── Count unique investors (one-time, never decremented) ──────────────
        if (!_isInvestor[msg.sender]) {
            _isInvestor[msg.sender] = true;
            ++totalInvestors;
        }

        emit Staked(poolId, msg.sender, netAmount, depositFee, activeReferrer, refFee);
    }

    /// @notice Begin (or extend) the unlock countdown for `amount` tokens.
    ///
    ///  - Rewards immediately stop accruing on the newly unlocked amount.
    ///  - If an unlock is already in progress, the new amount is added to it
    ///    and the 6-hour countdown resets to now.
    ///  - Pending rewards are NOT settled here; they are paid on withdraw.
    ///
    /// @param poolId  Target pool.
    /// @param amount  Additional amount to unlock (must be ≤ remaining effective staked balance).
    function requestUnlock(
        uint256 poolId,
        uint256 amount
    ) external nonReentrant validPool(poolId) updateReward(poolId, msg.sender) {
        require(amount > 0, "StakingContract: zero amount");

        _claimRewardsForPool(poolId, msg.sender);

        UserInfo storage user = userInfo[poolId][msg.sender];
        uint256 effectiveStaked = user.stakedAmount - user.unlockedAmount;
        require(amount <= effectiveStaked, "StakingContract: amount exceeds effective staked");

        PoolInfo storage pool = pools[poolId];

        // Add to any existing unlock; reset countdown to now
        user.unlockedAmount      += amount;
        user.unlockRequestTime    = block.timestamp;
        pool.totalEffectiveStaked -= amount;
        pool.totalUnlocked        += amount;

        emit UnlockRequested(poolId, msg.sender, user.unlockedAmount, block.timestamp + withdrawLockPeriod);
    }

    /// @notice Cancel the active unlock request (only before the lock period has elapsed).
    ///         Tokens are returned to the reward-earning bucket.
    function cancelUnlock(
        uint256 poolId
    ) external nonReentrant poolExists(poolId) updateReward(poolId, msg.sender) {
        UserInfo storage user = userInfo[poolId][msg.sender];
        require(user.unlockedAmount > 0, "StakingContract: no active unlock");
        require(
            block.timestamp < user.unlockRequestTime + withdrawLockPeriod,
            "StakingContract: lock elapsed; use withdraw"
        );

        PoolInfo storage pool = pools[poolId];
        uint256 amount = user.unlockedAmount;

        user.unlockedAmount     = 0;
        user.unlockRequestTime  = 0;
        pool.totalEffectiveStaked += amount;
        pool.totalUnlocked        -= amount;

        emit UnlockCancelled(poolId, msg.sender, amount);
    }

    /// @notice Withdraw `amount` tokens from the pool.
    ///
    ///  `amount` is the total the user wants to receive.  Pending rewards are consumed first
    ///  (no lock required); any shortfall is drawn from the unlocked principal (lock required).
    ///  Remaining pending reward that is not taken out compounds into the staked balance.
    ///
    ///  Examples (pending = 100, unlocked principal = 500, lock elapsed):
    ///    withdraw(40)   → user gets 40 (all from reward), 60 reward compounds into stake
    ///    withdraw(100)  → user gets 100 (all reward), 0 compounds
    ///    withdraw(300)  → user gets 300 (100 reward + 200 principal), pending = 0
    ///    withdraw(0)    → user gets nothing, 100 reward compounds into stake
    function withdraw(
        uint256 poolId,
        uint256 amount
    ) external nonReentrant poolExists(poolId) {
        require(amount > 0, "StakingContract: zero amount");
        UserInfo storage user = userInfo[poolId][msg.sender];
        PoolInfo storage pool = pools[poolId];

        // Settle rewards accrued up to now
        _checkpointPool(poolId);
        _settleUser(poolId, msg.sender);
        _claimRewardsForPool(poolId, msg.sender);

        uint256 principalOut = amount;

        if (principalOut > 0) {
            require(user.unlockedAmount >= principalOut, "StakingContract: amount exceeds unlocked");
            require(
                block.timestamp >= user.unlockRequestTime + withdrawLockPeriod,
                "StakingContract: lock period not elapsed"
            );
        }

        if (principalOut > 0) {
            user.stakedAmount   -= principalOut;
            user.unlockedAmount -= principalOut;
            user.totalWithdrawn += principalOut;
            pool.totalUnlocked  -= principalOut;
        }
        if (poolId == 0) {
            // Special handling for ETH withdrawals from pool 0: unwrap WETH and send as ETH
            positionManager.withdraw(pool.token, principalOut, address(this));
            IWETH(pool.token).withdraw(principalOut);
            (bool sent, ) = msg.sender.call{value: principalOut}("");
            require(sent, "StakingContract: failed to send ETH");
        } else {
            // ── Pull from PM and distribute ───────────────────────────────────────
            if (amount > 0) positionManager.withdraw(pool.token, amount, msg.sender);
        }
        emit Withdrawn(poolId, msg.sender, principalOut);
    }

    /// @notice Returns the pool ID assigned to `token` (alias for getPoolId).
    function getPoolIdByToken(address token) external view returns (uint256) {
        uint256 id = _tokenPoolId[token];
        require(id != 0, "StakingContract: unsupported token");
        return id - 1;
    }

    /// @notice Claim compounded rewards across all pools for msg.sender.
    function claimAllRewards() external nonReentrant {
        uint256 len = pools.length;
        for (uint256 i = 0; i < len; ) {
            _checkpointPool(i);
            _settleUser(i, msg.sender);
            _claimRewardsForPool(i, msg.sender);
            unchecked { ++i; }
        }
    }

    /// @notice Update reward accumulators for all pools. This is gas-intensive, so it is not done automatically on any user action.
    function updatePools() external nonReentrant {
        uint256 len = pools.length;
        for (uint256 i = 0; i < len; ) {
            _checkpointPool(i);
            unchecked { ++i; }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //  INTERNAL HELPERS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @dev Update pool.rewardPerTokenStored and pool.lastUpdateTime to now.
    function _checkpointPool(uint256 poolId) internal {
        PoolInfo storage pool = pools[poolId];
        uint256 rpt = _rewardPerToken(poolId);
        pool.pendingReward += (pool.totalEffectiveStaked * (rpt - pool.rewardPerTokenStored)) / PRECISION;
        pool.rewardPerTokenStored = rpt;
        pool.lastUpdateTime = block.timestamp;
    }

    /// @dev Settle pending rewards for `user` in `poolId` using their current effective balance.
    ///      Must be called AFTER _checkpointPool so rewardPerTokenStored is current.
    function _settleUser(uint256 poolId, address user) internal {
        PoolInfo storage pool = pools[poolId];
        UserInfo storage u    = userInfo[poolId][user];
        uint256 effectiveStaked = u.stakedAmount - u.unlockedAmount;
        u.pendingReward += (effectiveStaked * (pool.rewardPerTokenStored - u.rewardPerTokenPaid)) / PRECISION;
        u.rewardPerTokenPaid = pool.rewardPerTokenStored;
    }

    /// @dev Execute a reward claim for `user` in `poolId`.
    ///      Assumes _checkpointPool and _settleUser have already been called.
    function _claimRewardsForPool(uint256 poolId, address user) internal {
        UserInfo storage u    = userInfo[poolId][user];
        PoolInfo  storage pool = pools[poolId];

        uint256 reward = u.pendingReward;
        if (reward == 0) return;

        u.pendingReward             = 0;
        u.totalRewardsClaimed       += reward;
        pool.totalRewardsPaid       += reward;
        pool.pendingReward           = pool.pendingReward > reward ? pool.pendingReward - reward : 0;
        u.stakedAmount              += reward;
        pool.totalEffectiveStaked   += reward;


        // ── Referral claim bonus (from PM fee reserve, not deducted from user) ─
        address activeReferrer = u.referrer;
        uint256 claimBonus     = 0;
        uint256 effectiveClaimRate = activeReferrer != address(0) ? _referralClaimRate(activeReferrer) : 0;
        if (activeReferrer != address(0) && effectiveClaimRate > 0) {
            claimBonus = (reward * effectiveClaimRate) / DENOMINATOR;
            if (claimBonus > 0) {
                pool.totalReferralClaimFees += claimBonus;
                referrerClaimBonusEarned[poolId][activeReferrer] += claimBonus;
                userInfo[poolId][activeReferrer].totalReferralEarned += claimBonus;
            }
        }

        if (claimBonus > 0) positionManager.withdraw(pool.token, claimBonus, activeReferrer);
        positionManager.recordDeposit(poolId, pool.token, reward);

        emit RewardClaimed(poolId, user, reward, activeReferrer, claimBonus);
    }

    /// @dev Pure reward-per-token calculation (does not write state).
    ///      Increases linearly with time and APR. Freezes when totalEffectiveStaked == 0.
    ///
    ///  Formula (per-second increment):
    ///    Δ = (timeDelta × currentAPR × PRECISION) / (SECONDS_PER_YEAR × DENOMINATOR)
    ///
    ///  User reward = effectiveStaked × (rewardPerToken − rewardPerTokenPaid) / PRECISION
    /// @dev Returns the effective stake referral fee rate for `referrer`:
    ///      custom override if set, otherwise the global `referralFeeRate`.
    function _referralFeeRate(address referrer) internal view returns (uint256) {
        ReferrerConfig storage cfg = referrerConfig[referrer];
        return cfg.hasFeeRate ? cfg.feeRate : referralFeeRate;
    }

    /// @dev Returns the effective claim bonus rate for `referrer`:
    ///      custom override if set, otherwise the global `referralClaimRate`.
    function _referralClaimRate(address referrer) internal view returns (uint256) {
        ReferrerConfig storage cfg = referrerConfig[referrer];
        return cfg.hasClaimRate ? cfg.claimRate : referralClaimRate;
    }

    function _rewardPerToken(uint256 poolId) internal view returns (uint256) {
        PoolInfo storage pool = pools[poolId];
        if (pool.totalEffectiveStaked == 0) {
            return pool.rewardPerTokenStored;
        }
        uint256 timeDelta = block.timestamp - pool.lastUpdateTime;
        return pool.rewardPerTokenStored
            + (timeDelta * pool.currentApr * PRECISION)
            / (SECONDS_PER_YEAR * DENOMINATOR);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //  VIEW FUNCTIONS — POOL
    // ═══════════════════════════════════════════════════════════════════════════

    struct PoolView {
        uint256 poolId;
        address token;
        uint256 totalStaked;            // totalEffectiveStaked + totalUnlocked
        uint256 effectiveStaked;        // currently earning rewards
        uint256 totalUnlocked;          // in unlock queue (no reward)
        uint256 currentApr;             // bps — 10 000 = 100 %
        uint256 rewardPerToken;         // live accumulator value
        uint256 rewardRatePerSecond;    // tokens/sec emitted at current APR & TVL (×PRECISION)
        uint256 totalFeesCollected;
        uint256 totalReferralStakeFees;
        uint256 totalReferralClaimFees;
        uint256 totalRewardsPaid;
        uint256 pendingReward;
        uint256 maxStake;
        bool    active;
    }

    /// @notice Total number of pools (active + inactive).
    function getPoolCount() external view returns (uint256) {
        return pools.length;
    }

    /// @notice Returns true if `token` already has a pool.
    function isTokenListed(address token) external view returns (bool) {
        return _tokenPoolId[token] != 0;
    }

    /// @inheritdoc IStaking
    function getTotalUnlocked(address token) external view returns (uint256) {
        uint256 stored = _tokenPoolId[token];
        if (stored == 0) return 0;
        return pools[stored - 1].totalUnlocked;
    }

    /// @notice Full analytics view for a single pool.
    function getPoolInfo(uint256 poolId) external view poolExists(poolId) returns (PoolView memory) {
        return _buildPoolView(poolId);
    }

    /// @notice Full analytics view for every pool.
    function getAllPools() external view returns (PoolView[] memory views) {
        uint256 len = pools.length;
        views = new PoolView[](len);
        for (uint256 i = 0; i < len; ) {
            views[i] = _buildPoolView(i);
            unchecked { ++i; }
        }
    }

    /// @notice Full analytics view for every active pool.
    function getActivePools() external view returns (PoolView[] memory views) {
        uint256 len    = pools.length;
        uint256 count  = 0;
        for (uint256 i = 0; i < len; ) {
            if (pools[i].active) ++count;
            unchecked { ++i; }
        }
        views = new PoolView[](count);
        uint256 j = 0;
        for (uint256 i = 0; i < len; ) {
            if (pools[i].active) {
                views[j] = _buildPoolView(i);
                unchecked { ++j; }
            }
            unchecked { ++i; }
        }
    }

    /// @notice Total principal (effective + unlocked) staked in a pool.
    function getPoolTVL(uint256 poolId) external view poolExists(poolId) returns (uint256) {
        return pools[poolId].totalEffectiveStaked + pools[poolId].totalUnlocked;
    }

    /// @notice Aggregate TVL across all pools that use `token`.
    ///         Useful when the same token appears in multiple pools.
    function getTotalTVLByToken(address token) external view returns (uint256 tvl) {
        uint256 len = pools.length;
        for (uint256 i = 0; i < len; ) {
            if (pools[i].token == token) {
                tvl += pools[i].totalEffectiveStaked + pools[i].totalUnlocked;
            }
            unchecked { ++i; }
        }
    }

    /// @notice Current APR for a pool (bps).
    function getPoolAPR(uint256 poolId) external view poolExists(poolId) returns (uint256) {
        return pools[poolId].currentApr;
    }

    /// @notice Current reward per token for a pool (live, not stored).
    function getPoolRewardPerToken(uint256 poolId) external view poolExists(poolId) returns (uint256) {
        return _rewardPerToken(poolId);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //  VIEW FUNCTIONS — USER
    // ═══════════════════════════════════════════════════════════════════════════

    struct UserPoolView {
        uint256 poolId;
        address token;
        uint256 stakedAmount;        // gross principal (including unlocked)
        uint256 unlockedAmount;      // amount in unlock queue
        uint256 effectiveStaked;     // earning rewards
        uint256 unlockRequestTime;   // 0 if no active unlock
        uint256 unlockAvailableAt;   // 0 if no active unlock
        bool    canWithdraw;         // true when lock period elapsed and unlockedAmount > 0
        uint256 timeUntilWithdraw;   // seconds remaining; 0 if canWithdraw or no unlock
        uint256 pendingReward;       // live pending reward (not yet claimed)
        address referrer;
        uint256 totalDeposited;
        uint256 totalWithdrawn;
        uint256 totalRewardsClaimed;
        uint256 totalReferralEarned;
    }

    /// @notice Full analytics view for a user in a specific pool.
    function getUserInfo(uint256 poolId, address user)
        external
        view
        poolExists(poolId)
        returns (UserPoolView memory)
    {
        return _buildUserView(poolId, user);
    }

    /// @notice Full analytics view for a user across all pools.
    function getUserAllPoolsInfo(address user) external view returns (UserPoolView[] memory views) {
        uint256 len = pools.length;
        views = new UserPoolView[](len);
        for (uint256 i = 0; i < len; ) {
            views[i] = _buildUserView(i, user);
            unchecked { ++i; }
        }
    }

    /// @notice Live pending reward for `user` in `poolId`.
    function getPendingReward(uint256 poolId, address user)
        external
        view
        poolExists(poolId)
        returns (uint256)
    {
        return _computePendingReward(poolId, user);
    }

    /// @notice Pending rewards across all pools for `user`.
    /// @return poolIds  Array of pool IDs with non-zero pending reward.
    /// @return amounts  Corresponding reward amounts.
    function getUserPendingRewards(address user)
        external
        view
        returns (uint256[] memory poolIds, uint256[] memory amounts)
    {
        uint256 len   = pools.length;
        uint256 count = 0;
        for (uint256 i = 0; i < len; ) {
            if (_computePendingReward(i, user) > 0) ++count;
            unchecked { ++i; }
        }
        poolIds = new uint256[](count);
        amounts = new uint256[](count);
        uint256 j = 0;
        for (uint256 i = 0; i < len; ) {
            uint256 r = _computePendingReward(i, user);
            if (r > 0) {
                poolIds[j] = i;
                amounts[j] = r;
                unchecked { ++j; }
            }
            unchecked { ++i; }
        }
    }

    /// @notice Sum of all pending rewards for `user` for a given `token` (across pools).
    function getUserTotalPendingRewardByToken(address user, address token)
        external
        view
        returns (uint256 total)
    {
        uint256 len = pools.length;
        for (uint256 i = 0; i < len; ) {
            if (pools[i].token == token) {
                total += _computePendingReward(i, user);
            }
            unchecked { ++i; }
        }
    }

    /// @notice Whether `user` can currently withdraw from the unlock queue of `poolId`.
    function isWithdrawable(uint256 poolId, address user)
        external
        view
        poolExists(poolId)
        returns (bool)
    {
        UserInfo storage u = userInfo[poolId][user];
        return u.unlockedAmount > 0
            && block.timestamp >= u.unlockRequestTime + withdrawLockPeriod;
    }

    /// @notice Principal amount `user` may withdraw right now from `poolId` (0 if lock not elapsed).
    function getWithdrawableAmount(uint256 poolId, address user)
        external
        view
        poolExists(poolId)
        returns (uint256)
    {
        UserInfo storage u = userInfo[poolId][user];
        if (u.unlockedAmount > 0 && block.timestamp >= u.unlockRequestTime + withdrawLockPeriod) {
            return u.unlockedAmount;
        }
        return 0;
    }

    /// @notice Total amount receivable on withdraw: principal + pending rewards.
    ///         Returns 0 if lock period has not elapsed.
    function getWithdrawableTotal(uint256 poolId, address user)
        external
        view
        poolExists(poolId)
        returns (uint256 principal, uint256 reward, uint256 total)
    {
        UserInfo storage u = userInfo[poolId][user];
        if (u.unlockedAmount == 0 || block.timestamp < u.unlockRequestTime + withdrawLockPeriod) {
            return (0, 0, 0);
        }
        principal = u.unlockedAmount;
        reward    = _computePendingReward(poolId, user);
        total     = principal + reward;
    }

    /// @notice Claimable reward for `user` in `poolId` (live, including unsettled accrual).
    function getClaimableReward(uint256 poolId, address user)
        external
        view
        poolExists(poolId)
        returns (uint256)
    {
        return _computePendingReward(poolId, user);
    }

    /// @notice Seconds remaining until `user` can withdraw (0 if already withdrawable or no unlock).
    function getTimeUntilWithdraw(uint256 poolId, address user)
        external
        view
        poolExists(poolId)
        returns (uint256)
    {
        UserInfo storage u = userInfo[poolId][user];
        if (u.unlockedAmount == 0) return 0;
        uint256 availableAt = u.unlockRequestTime + withdrawLockPeriod;
        if (block.timestamp >= availableAt) return 0;
        return availableAt - block.timestamp;
    }

    /// @notice Estimate the reward `user` would earn in `poolId` over `duration` seconds
    ///         at the current APR, based on their current effective staked balance.
    function estimateReward(uint256 poolId, address user, uint256 duration)
        external
        view
        poolExists(poolId)
        returns (uint256)
    {
        UserInfo storage u = userInfo[poolId][user];
        uint256 effective  = u.stakedAmount - u.unlockedAmount;
        if (effective == 0) return 0;
        return (effective * pools[poolId].currentApr * duration) / (SECONDS_PER_YEAR * DENOMINATOR);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //  VIEW FUNCTIONS — REFERRER
    // ═══════════════════════════════════════════════════════════════════════════

    struct ReferrerPoolView {
        uint256 poolId;
        address token;
        uint256 stakeFeeEarned;   // lifetime staking referral fees earned in this pool
        uint256 claimBonusEarned; // lifetime claim bonuses earned in this pool
        uint256 totalEarned;      // stakeFeeEarned + claimBonusEarned
    }

    /// @notice Returns the effective referral rates for `referrer` (custom if set, else global).
    function getReferrerRates(address referrer)
        external
        view
        returns (uint256 feeRate, uint256 claimRate, bool hasCustomFeeRate, bool hasCustomClaimRate)
    {
        ReferrerConfig storage cfg = referrerConfig[referrer];
        feeRate           = cfg.hasFeeRate   ? cfg.feeRate   : referralFeeRate;
        claimRate         = cfg.hasClaimRate ? cfg.claimRate : referralClaimRate;
        hasCustomFeeRate  = cfg.hasFeeRate;
        hasCustomClaimRate = cfg.hasClaimRate;
    }

    /// @notice Referrer earnings in a specific pool.
    function getReferrerPoolInfo(uint256 poolId, address referrer)
        external
        view
        poolExists(poolId)
        returns (ReferrerPoolView memory)
    {
        return ReferrerPoolView({
            poolId:           poolId,
            token:            pools[poolId].token,
            stakeFeeEarned:   referrerStakeFeeEarned[poolId][referrer],
            claimBonusEarned: referrerClaimBonusEarned[poolId][referrer],
            totalEarned:      referrerStakeFeeEarned[poolId][referrer]
                              + referrerClaimBonusEarned[poolId][referrer]
        });
    }

    /// @notice Referrer earnings across all pools.
    function getReferrerAllPoolsInfo(address referrer)
        external
        view
        returns (ReferrerPoolView[] memory views)
    {
        uint256 len = pools.length;
        views = new ReferrerPoolView[](len);
        for (uint256 i = 0; i < len; ) {
            views[i] = ReferrerPoolView({
                poolId:           i,
                token:            pools[i].token,
                stakeFeeEarned:   referrerStakeFeeEarned[i][referrer],
                claimBonusEarned: referrerClaimBonusEarned[i][referrer],
                totalEarned:      referrerStakeFeeEarned[i][referrer]
                                  + referrerClaimBonusEarned[i][referrer]
            });
            unchecked { ++i; }
        }
    }

    /// @notice Total lifetime referral earnings for `referrer` across all pools for a given token.
    function getReferrerTotalEarnedByToken(address referrer, address token)
        external
        view
        returns (uint256 total)
    {
        uint256 len = pools.length;
        for (uint256 i = 0; i < len; ) {
            if (pools[i].token == token) {
                total += referrerStakeFeeEarned[i][referrer]
                       + referrerClaimBonusEarned[i][referrer];
            }
            unchecked { ++i; }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //  INTERNAL VIEW HELPERS
    // ═══════════════════════════════════════════════════════════════════════════

    function _computePendingReward(uint256 poolId, address user) internal view returns (uint256) {
        UserInfo storage u   = userInfo[poolId][user];
        uint256 latestRPT    = _rewardPerToken(poolId);
        uint256 effectiveAmt = u.stakedAmount - u.unlockedAmount;
        return u.pendingReward
            + (effectiveAmt * (latestRPT - u.rewardPerTokenPaid)) / PRECISION;
    }

    function _buildPoolView(uint256 poolId) internal view returns (PoolView memory v) {
        PoolInfo storage p = pools[poolId];
        uint256 rpt        = _rewardPerToken(poolId);
        // rewardRatePerSecond: tokens emitted per second at current APR for current TVL
        // = totalEffectiveStaked × currentAPR / (SECONDS_PER_YEAR × DENOMINATOR)
        uint256 ratePerSec = p.totalEffectiveStaked > 0
            ? (p.totalEffectiveStaked * p.currentApr) / (SECONDS_PER_YEAR * DENOMINATOR)
            : 0;
        uint256 latestRPT    = _rewardPerToken(poolId);
        uint256 pendingReward = p.pendingReward + (p.totalEffectiveStaked * (latestRPT - p.rewardPerTokenStored)) / PRECISION;
        v = PoolView({
            poolId:                poolId,
            token:                 p.token,
            totalStaked:           p.totalEffectiveStaked + p.totalUnlocked,
            effectiveStaked:       p.totalEffectiveStaked,
            totalUnlocked:         p.totalUnlocked,
            currentApr:            p.currentApr,
            rewardPerToken:        rpt,
            rewardRatePerSecond:   ratePerSec,
            totalFeesCollected:    p.totalFeesCollected,
            totalReferralStakeFees: p.totalReferralStakeFees,
            totalReferralClaimFees: p.totalReferralClaimFees,
            totalRewardsPaid:      p.totalRewardsPaid,
            pendingReward:         pendingReward,
            maxStake:              p.maxStake,
            active:                p.active
        });
    }

    function _buildUserView(uint256 poolId, address user) internal view returns (UserPoolView memory v) {
        UserInfo storage u  = userInfo[poolId][user];
        uint256 effective   = u.stakedAmount - u.unlockedAmount;
        bool hasUnlock      = u.unlockedAmount > 0;
        uint256 availableAt = hasUnlock ? u.unlockRequestTime + withdrawLockPeriod : 0;
        bool canWithdraw    = hasUnlock && block.timestamp >= availableAt;
        uint256 timeLeft    = (hasUnlock && !canWithdraw) ? availableAt - block.timestamp : 0;

        v = UserPoolView({
            poolId:              poolId,
            token:               pools[poolId].token,
            stakedAmount:        u.stakedAmount,
            unlockedAmount:      u.unlockedAmount,
            effectiveStaked:     effective,
            unlockRequestTime:   u.unlockRequestTime,
            unlockAvailableAt:   availableAt,
            canWithdraw:         canWithdraw,
            timeUntilWithdraw:   timeLeft,
            pendingReward:       _computePendingReward(poolId, user),
            referrer:            u.referrer,
            totalDeposited:      u.totalDeposited,
            totalWithdrawn:      u.totalWithdrawn,
            totalRewardsClaimed: u.totalRewardsClaimed,
            totalReferralEarned: u.totalReferralEarned
        });
    }

}

lib/openzeppelin-contracts/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);
    }
}

lib/openzeppelin-contracts/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);
}

lib/openzeppelin-contracts/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";

lib/openzeppelin-contracts/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";

lib/openzeppelin-contracts/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);
}

lib/openzeppelin-contracts/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)
        }
    }
}

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

lib/openzeppelin-contracts/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
        }
    }
}

lib/openzeppelin-contracts/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);
}

src/interfaces/IPositionManager.sol

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

/// @title IPositionManager
/// @notice Interface consumed by StakingContract.
///         Implementations hold staked principal and act as a liquidity
///         custodian that can deploy tokens into Uniswap V3 LP positions.
interface IPositionManager {
    // ─── Write functions (called by StakingContract) ──────────────────────────

    /// @notice Record that `amount` tokens have been deposited into `poolId`.
    ///         The staking contract transfers the tokens before calling this.
    /// @param poolId  Pool the deposit belongs to.
    /// @param token   ERC-20 token address.
    /// @param amount  Net principal (after deposit fee) to account for.
    function recordDeposit(uint256 poolId, address token, uint256 amount) external;

    /// @notice Withdraw `amount` of `token` and send it to `to`.
    ///         Automatically pulls back LP liquidity if in-contract balance is insufficient.
    /// @param token   ERC-20 token address.
    /// @param amount  Amount to withdraw.
    /// @param to      Recipient address.
    function withdraw(address token, uint256 amount, address to) external;
}

src/interfaces/IStaking.sol

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

/// @title IStaking
/// @notice Minimal staking interface used by PositionManager for pool-token validation.
interface IStaking {
    /// @notice Returns true if `token` is registered as a staking pool token.
    /// @param token ERC-20 token address.
    function isPoolToken(address token) external view returns (bool);

    /// @notice Returns the pool ID for a listed staking token.
    /// @param token ERC-20 token address.
    /// @return poolId The pool index.
    function getPoolId(address token) external view returns (uint256);

    /// @notice Returns the total amount of `token` currently queued for
    ///         withdrawal across all users (i.e. sum of all unlockedAmount
    ///         values in the pool for `token`).
    /// @param token ERC-20 token address.
    function getTotalUnlocked(address token) external view returns (uint256);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.