Skip to content
Verified contractExactMIT

HousingStaking

Address0xf987dd2d9a04bf30d32d984c5372eb8daba3dee3
Balance

0 ETH

 

Transactions

8

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,941,201
Creation transaction
0x7b6b42b585…0beac2fa6a

contracts/HousingStaking.sol

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

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

/**
 * @title  HousingStaking
 * @notice Smart contract for the Russian Housing Programme (RHP) · ZlatnikCoin.
 *
 *         A participant stakes ZLT at a fixed APR. When the balance
 *         (deposit principal + accrued interest) reaches lockedTarget
 *         (default 777 000 000 ZLT), the on-chain flag isHousingEligible
 *         confirms the right to exchange tokens for housing.
 *
 * @dev    Pool solvency Variant B: on entry it is verified that the free
 *         reward pool covers the maximum possible payout to the new
 *         participant. The pool is topped up only by the owner via fundRewardPool().
 *
 *         Security: ReentrancyGuard · Pausable · Ownable · SafeERC20
 *         Standards: OpenZeppelin 5.x · Solidity ^0.8.20
 *
 * @custom:oz-upgrades-unsafe-allow constructor
 */
contract HousingStaking is Ownable, Pausable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    // =========================================================================
    // TYPES
    // =========================================================================

    struct StakeInfo {
        uint256 amount;          // deposit principal (wei)
        uint256 lockedAPR;       // APR locked at entry (basis points)
        uint256 lockedTarget;    // target amount locked at entry (wei)
        uint256 since;           // timestamp of last accrual update
        uint256 accruedRewards;  // accumulated interest (wei)
        bool    isActive;        // position is active
    }

    // =========================================================================
    // STATE
    // =========================================================================

    /// @notice Address of the ZLT token (ERC-20).
    IERC20 public immutable token;

    // Global parameters — changes apply to NEW stakes only
    uint256 public annualRate   = 2_500;                          // 2500 bp = 25.00%
    uint256 public minStake     = 25_000_000  * 1e18;             // 25 000 000 ZLT
    uint256 public maxStake     = 397_824_000 * 1e18;             // 397 824 000 ZLT
    uint256 public targetAmount = 777_000_000 * 1e18;             // 777 000 000 ZLT

    // Limits — protection against admin errors and attacks
    /// @notice Maximum allowed APR: 50 000 bp = 500%. Prevents overflow DoS.
    uint256 public constant MAX_APR       = 50_000;
    /// @notice Minimum allowed APR: 100 bp = 1%. Prevents APR-sandwich attack.
    uint256 public constant MIN_APR       = 100;
    /// @notice Maximum targetAmount: 10 billion ZLT.
    ///         Prevents staking freeze via type(uint256).max target.
    uint256 public constant MAX_TARGET    = 10_000_000_000 * 1e18;

    // Housing slots
    uint256 public totalHousingSlots;   // set by owner; 0 at deployment
    uint256 public occupiedSlots;       // currently occupied (informational counter)

    // Reward pool (split accounting per Variant B)
    uint256 public rewardPool;              // actual tokens in the reward pool
    uint256 public totalPromisedRewards;    // reserved for active stakers (max)
    uint256 public totalStakedPrincipal;    // sum of all deposit principals (for capacity gate)

    // Per-address data
    mapping(address => StakeInfo) public stakes;
    mapping(address => bool)      private _housingEligibleStored;
    mapping(address => bool)      public isWaitlisted;
    mapping(address => bool)      public offerConcluded;  // concluded offer — cannot stake again

    // Enumerable arrays for off-chain view (swap-and-pop, O(1) removal)
    address[] private _waitlistArray;
    address[] private _offerConcludedArray;
    address[] private _stakersArray;

    // 1-based index mappings (0 = not in array)
    mapping(address => uint256) private _waitlistIndex;
    mapping(address => uint256) private _offerConcludedIndex;
    mapping(address => uint256) private _stakersIndex;

    // Wallet address to receive funds upon offer conclusion
    address public housingTreasury;

    // Cooldown: after early unstake (before eligibility), user must wait before re-staking
    uint256 public unstakeCooldown = 1 days;             // configurable by owner
    mapping(address => uint256) public unstakeCooldownUntil; // timestamp when cooldown expires

    // =========================================================================
    // INTERNAL ARRAY HELPERS (swap-and-pop)
    // =========================================================================

    function _arrayAdd(address[] storage arr, mapping(address => uint256) storage idx, address user) private {
        if (idx[user] != 0) return; // already present
        arr.push(user);
        idx[user] = arr.length; // 1-based
    }

    function _arrayRemove(address[] storage arr, mapping(address => uint256) storage idx, address user) private {
        uint256 pos = idx[user];
        if (pos == 0) return; // not present
        uint256 last = arr.length;
        if (pos != last) {
            address tail = arr[last - 1];
            arr[pos - 1] = tail;
            idx[tail] = pos;
        }
        arr.pop();
        idx[user] = 0;
    }

    // =========================================================================
    // EVENTS
    // =========================================================================

    event Staked(
        address indexed user,
        uint256 amount,
        uint256 lockedAPR,
        uint256 timestamp
    );
    event Unstaked(
        address indexed user,
        uint256 amount,
        uint256 rewards,
        uint256 timestamp
    );
    event EmergencyWithdrawn(
        address indexed user,
        uint256 amount,
        uint256 timestamp
    );
    event HousingEligibilityGranted(
        address indexed user,
        uint256 totalBalance,
        uint256 timestamp
    );
    event HousingEligibilityRevoked(
        address indexed user,
        uint256 timestamp
    );
    event SlotOccupied(
        address indexed user,
        uint256 occupiedSlots,
        uint256 totalHousingSlots,
        uint256 timestamp
    );
    event SlotReleased(
        address indexed user,
        uint256 occupiedSlots,
        uint256 totalHousingSlots,
        uint256 timestamp
    );
    event TotalSlotsUpdated(
        uint256 oldValue,
        uint256 newValue,
        uint256 timestamp
    );
    event WaitlistUpdated(
        address indexed user,
        bool status,
        uint256 timestamp
    );
    event APRUpdated(
        uint256 oldRate,
        uint256 newRate,
        uint256 timestamp
    );
    event TargetAmountUpdated(
        uint256 oldAmount,
        uint256 newAmount,
        uint256 timestamp
    );
    event RewardPoolFunded(
        uint256 amount,
        uint256 timestamp
    );
    event EmergencyFundsWithdrawn(
        address indexed to,
        uint256 amount,
        uint256 timestamp
    );
    event MinStakeUpdated(uint256 oldValue, uint256 newValue, uint256 timestamp);
    event MaxStakeUpdated(uint256 oldValue, uint256 newValue, uint256 timestamp);
    event UnstakeCooldownUpdated(
        uint256 oldCooldown,
        uint256 newCooldown,
        uint256 timestamp
    );
    event EarlyUnstaked(
        address indexed user,
        uint256 principal,
        uint256 forfeitedRewards,
        uint256 cooldownUntil,
        uint256 timestamp
    );
    event OfferConcluded(
        address indexed user,
        uint256 amount,
        uint256 timestamp
    );
    event HousingTreasuryUpdated(
        address indexed oldAddr,
        address indexed newAddr,
        uint256 timestamp
    );

    // =========================================================================
    // CONSTRUCTOR
    // =========================================================================

    /**
     * @param tokenAddress ZLT ERC-20 token address. Cannot be zero.
     * @param initialOwner Contract owner (admin).
     */
    constructor(address tokenAddress, address initialOwner) Ownable(initialOwner) {
        require(tokenAddress != address(0), "HS: zero token address");
        token = IERC20(tokenAddress);
    }

    // =========================================================================
    // INTERNAL HELPERS
    // =========================================================================

    /**
     * @dev Calculates new rewards accrued since the last checkpoint.
     *      Result is capped so that (amount + accruedRewards + result)
     *      does not exceed lockedTarget.
     *
     *      Formula (§5 spec):
     *        accrual = amount * lockedAPR * elapsed / (365 * 10_000 * 86_400)
     *
     * @return Amount of new rewards (wei). 0 if cap is reached.
     */
    function _computeNewRewards(StakeInfo storage s) internal view returns (uint256) {
        uint256 totalBalance = s.amount + s.accruedRewards;
        if (totalBalance >= s.lockedTarget) return 0;

        uint256 elapsed = block.timestamp - s.since;
        if (elapsed == 0) return 0;

        uint256 rawReward = (s.amount * s.lockedAPR * elapsed)
            / (365 * 10_000 * 86_400);

        uint256 remaining = s.lockedTarget - totalBalance;
        return rawReward > remaining ? remaining : rawReward;
    }

    /**
     * @dev Applies accrued rewards to the position and updates
     *      the isHousingEligible flag when the threshold is reached.
     */
    function _updateAccrual(address user) internal {
        StakeInfo storage s = stakes[user];
        uint256 newRewards = _computeNewRewards(s);
        if (newRewards > 0) {
            s.accruedRewards += newRewards;
            s.since = block.timestamp;
        }

        uint256 totalBalance = s.amount + s.accruedRewards;
        if (totalBalance >= s.lockedTarget && !_housingEligibleStored[user]) {
            _housingEligibleStored[user] = true;
            emit HousingEligibilityGranted(user, totalBalance, block.timestamp);
        }
    }

    /**
     * @dev Releases the slot, zeroes out StakeInfo, releases the reward reserve,
     *      and revokes eligibility. Called AFTER reading the amount and
     *      decreasing rewardPool (CEI pattern compliance).
     */
    function _releaseStake(address user) internal {
        StakeInfo storage s = stakes[user];

        // Release reserve — free up pool capacity for new participants
        uint256 promised = s.lockedTarget > s.amount
            ? s.lockedTarget - s.amount
            : 0;
        totalPromisedRewards = totalPromisedRewards > promised
            ? totalPromisedRewards - promised
            : 0;

        // Release capacity (proportional slot)
        totalStakedPrincipal = totalStakedPrincipal > s.amount
            ? totalStakedPrincipal - s.amount
            : 0;

        // Zero out StakeInfo
        s.isActive       = false;
        s.amount         = 0;
        s.lockedAPR      = 0;
        s.lockedTarget   = 0;
        s.since          = 0;
        s.accruedRewards = 0;

        // Slot released
        occupiedSlots -= 1;
        emit SlotReleased(user, occupiedSlots, totalHousingSlots, block.timestamp);

        // Revoke eligibility
        if (_housingEligibleStored[user]) {
            _housingEligibleStored[user] = false;
            emit HousingEligibilityRevoked(user, block.timestamp);
        }

        // Remove from waitlist — position closed
        if (isWaitlisted[user]) {
            isWaitlisted[user] = false;
            _arrayRemove(_waitlistArray, _waitlistIndex, user);
            emit WaitlistUpdated(user, false, block.timestamp);
        }

        // Remove from active stakers
        _arrayRemove(_stakersArray, _stakersIndex, user);
    }

    // =========================================================================
    // USER FUNCTIONS
    // =========================================================================

    /**
     * @notice Enter the programme: stake ZLT.
     * @dev    Checks absence of an active position, slot availability,
     *         amount range and sufficient free reward pool (Variant B).
     *         KYC is enforced off-chain at the application layer.
     *         Call approve(staking, amount) before invoking.
     * @param  amount Amount of ZLT (wei). Must be in [minStake, maxStake].
     */
    function stake(uint256 amount) external whenNotPaused nonReentrant {
        require(!stakes[msg.sender].isActive,        "HS: already staking");
        require(!offerConcluded[msg.sender],         "HS: offer already concluded");
        require(
            block.timestamp >= unstakeCooldownUntil[msg.sender],
            "HS: cooldown active"
        );
        require(amount >= minStake,                  "HS: below minimum stake");
        require(amount <= maxStake,                  "HS: above maximum stake");

        // Capacity gate: proportional gate (instead of slot counter)
        // 1 slot = targetAmount. Stake occupies amount/targetAmount fraction of a slot.
        require(
            totalStakedPrincipal + amount <= targetAmount * totalHousingSlots,
            "HS: project capacity full"
        );

        // Variant B: verify free pool covers maximum rewards
        uint256 neededRewards = targetAmount > amount ? targetAmount - amount : 0;
        uint256 freePool = rewardPool > totalPromisedRewards
            ? rewardPool - totalPromisedRewards
            : 0;
        require(freePool >= neededRewards, "HS: insufficient reward pool");

        // Effects (CEI: state changes first, then Interaction)
        stakes[msg.sender] = StakeInfo({
            amount:         amount,
            lockedAPR:      annualRate,
            lockedTarget:   targetAmount,
            since:          block.timestamp,
            accruedRewards: 0,
            isActive:       true
        });

        totalPromisedRewards += neededRewards;
        occupiedSlots        += 1;
        totalStakedPrincipal += amount;

        // Instantly eligible if amount >= targetAmount (edge case)
        if (amount >= targetAmount) {
            _housingEligibleStored[msg.sender] = true;
            emit HousingEligibilityGranted(msg.sender, amount, block.timestamp);
        }

        // Add to active stakers enumeration
        _arrayAdd(_stakersArray, _stakersIndex, msg.sender);

        emit Staked(msg.sender, amount, annualRate, block.timestamp);
        emit SlotOccupied(msg.sender, occupiedSlots, totalHousingSlots, block.timestamp);

        // Interaction (after all state changes)
        token.safeTransferFrom(msg.sender, address(this), amount);
    }

    /**
     * @notice Conclude the offer: transfer the accumulated amount (principal + rewards)
     *         to housingTreasury. Available only to participants with isHousingEligible
     *         and isWaitlisted. After the call offerConcluded[user] = true and
     *         stake() from this address is blocked permanently.
     * @dev    CLAIM-AUDIT-1: the expectedTreasury parameter protects against front-run attack:
     *         if the owner replaces housingTreasury before the user's tx,
     *         the transaction reverts (rather than sending funds to the wrong address).
     * @param  expectedTreasury Address the user expects to see as housingTreasury.
     */
    function claimHousing(address expectedTreasury) external whenNotPaused nonReentrant {
        require(isHousingEligible(msg.sender),        "HS: not eligible");
        require(isWaitlisted[msg.sender],             "HS: not on waitlist");
        require(housingTreasury != address(0),        "HS: treasury not set");
        require(housingTreasury == expectedTreasury,  "HS: treasury mismatch");
        StakeInfo storage s = stakes[msg.sender];
        require(s.isActive,                          "HS: no active stake");

        // Recalculate accrued rewards (apply cap)
        _updateAccrual(msg.sender);

        uint256 principal = s.amount;
        uint256 rewards   = s.accruedRewards; // capped at lockedTarget - principal
        uint256 total     = principal + rewards; // = s.lockedTarget

        require(rewardPool >= rewards, "HS: reward pool insufficient");

        // Effects (CEI)
        rewardPool                 -= rewards;
        offerConcluded[msg.sender]  = true;
        _arrayAdd(_offerConcludedArray, _offerConcludedIndex, msg.sender);
        _releaseStake(msg.sender);  // clears isWaitlisted, eligibility, zeroes out position

        // Interaction: funds go to treasury, not to the user
        token.safeTransfer(housingTreasury, total);
        emit OfferConcluded(msg.sender, total, block.timestamp);
    }

    /**
     * @notice Withdraw deposit principal + all accrued interest.
     *         Permanently revokes housing eligibility for the current session (§3.1.3 of the offer).
     */
    function unstake() external whenNotPaused nonReentrant {
        StakeInfo storage s = stakes[msg.sender];
        require(s.isActive, "HS: no active stake");

        // Recalculate accrued rewards before withdrawal
        _updateAccrual(msg.sender);

        uint256 principal = s.amount;
        bool eligible     = isHousingEligible(msg.sender);

        if (eligible) {
            // Normal exit: eligible participant withdraws deposit + all accrued interest
            uint256 rewards = s.accruedRewards;
            uint256 total   = principal + rewards;

            require(rewardPool >= rewards, "HS: reward pool insufficient");

            // Effects (CEI)
            rewardPool -= rewards;
            _releaseStake(msg.sender);

            // Interaction
            token.safeTransfer(msg.sender, total);

            emit Unstaked(msg.sender, principal, rewards, block.timestamp);
        } else {
            // Early exit: not yet eligible — interest is forfeited, cooldown applied
            uint256 forfeited = s.accruedRewards;
            uint256 cooldownUntil = block.timestamp + unstakeCooldown;

            // Effects (CEI) — rewardPool NOT decreased (forfeited rewards stay)
            // But we must release the totalPromisedRewards reservation
            _releaseStake(msg.sender);
            unstakeCooldownUntil[msg.sender] = cooldownUntil;

            // Interaction — return principal only
            token.safeTransfer(msg.sender, principal);

            emit EarlyUnstaked(msg.sender, principal, forfeited, cooldownUntil, block.timestamp);
        }
    }

    /**
     * @notice Emergency withdrawal — deposit principal only.
     *         Accrued interest is forfeited (remains in the reward pool).
     *         Available only when the contract is paused (§9 spec).
     *         Permanently revokes housing eligibility for the current session.
     */
    function emergencyWithdraw() external whenPaused nonReentrant {
        StakeInfo storage s = stakes[msg.sender];
        require(s.isActive, "HS: no active stake");

        uint256 principal = s.amount;

        // Effects
        _releaseStake(msg.sender);
        // rewardPool is NOT decreased — interest remains in the pool
        // Clear any active cooldown so the user is not trapped after emergency exit
        unstakeCooldownUntil[msg.sender] = 0;

        // Interaction
        token.safeTransfer(msg.sender, principal);

        emit EmergencyWithdrawn(msg.sender, principal, block.timestamp);
    }

    /**
     * @notice Public view of stake state (§8.2.4 of the offer).
     *         Returns the real balance at the current moment without writing to state.
     *
     * @param  user Participant address.
     * @return stakedAmount   Deposit principal (wei).
     * @return accruedRewards Accumulated interest including unwritten pending (wei).
     * @return totalBalance   Total balance (wei).
     * @return lockedAPR      Locked APR in basis points.
     * @return lockedTarget   Locked target amount (wei).
     * @return isEligible     Housing eligibility flag.
     * @return waitlisted     Waitlist flag.
     * @return since          Timestamp of last accrual update.
     */
    function getStakeInfo(address user) external view returns (
        uint256 stakedAmount,
        uint256 accruedRewards,
        uint256 totalBalance,
        uint256 lockedAPR,
        uint256 lockedTarget,
        bool    isEligible,
        bool    waitlisted,
        uint256 since
    ) {
        StakeInfo storage s = stakes[user];
        uint256 pending      = s.isActive ? _computeNewRewards(s) : 0;
        uint256 totalAccrued = s.accruedRewards + pending;

        // Delegate check to isHousingEligible() — single source of truth.
        bool eligible = isHousingEligible(user);

        return (
            s.amount,
            totalAccrued,
            s.amount + totalAccrued,
            s.lockedAPR,
            s.lockedTarget,
            eligible,
            isWaitlisted[user],
            s.since
        );
    }

    /**
     * @notice Shows the solvency state of the reward pool.
     * @return poolBalance  Total tokens in the reward pool (wei).
     * @return promised     Reserved for active stakes (wei).
     * @return freeCapacity Free capacity for new participants (wei).
     */
    function getPoolSolvency() external view returns (
        uint256 poolBalance,
        uint256 promised,
        uint256 freeCapacity
    ) {
        uint256 free = rewardPool > totalPromisedRewards
            ? rewardPool - totalPromisedRewards
            : 0;
        return (rewardPool, totalPromisedRewards, free);
    }

    /**
     * @notice Total programme capacity = targetAmount × totalHousingSlots.
     * @return Maximum ZLT volume the programme can accept.
     */
    function totalProjectCap() external view returns (uint256) {
        return targetAmount * totalHousingSlots;
    }

    /**
     * @notice Returns all addresses currently in the waitlist.
     * @return Array of waitlisted addresses.
     */
    function getWaitlist() external view returns (address[] memory) {
        return _waitlistArray;
    }

    /**
     * @notice Returns all addresses that have concluded an offer.
     * @return Array of offerConcluded addresses.
     */
    function getOfferConcluded() external view returns (address[] memory) {
        return _offerConcludedArray;
    }

    /**
     * @notice Returns all addresses with an active stake.
     * @return Array of active staker addresses.
     */
    function getActiveStakers() external view returns (address[] memory) {
        return _stakersArray;
    }

    /**
     * @notice Current utilisation = sum of all active deposit principals.
     * @return Used capacity in ZLT.
     */
    function usedCapacity() external view returns (uint256) {
        return totalStakedPrincipal;
    }

    /**
     * @notice Number of full slots (equal to targetAmount) still available.
     *         Fractional slots are not counted (floor division).
     * @return Number of free full slots.
     */
    function availableSlots() external view returns (uint256) {
        uint256 cap  = targetAmount * totalHousingSlots;
        if (totalStakedPrincipal >= cap) return 0;
        return (cap - totalStakedPrincipal) / targetAmount;
    }

    /**
     * @notice Checks whether a stake of the given size will pass the capacity gate.
     *         Returns true if totalStakedPrincipal + amount ≤ totalProjectCap().
     * @dev    Use instead of availableSlots() > 0 for an exact check:
     *         availableSlots() returns 0 even when the remainder < targetAmount
     *         but a stake with amount ∈ [minStake, remainder] would still pass.
     * @param  amount Planned stake size (in wei).
     * @return true if the capacity gate will accept the given amount.
     */
    function canStake(uint256 amount) external view returns (bool) {
        return totalStakedPrincipal + amount <= targetAmount * totalHousingSlots;
    }

    /**
     * @notice Checks a participant's housing eligibility in real time.
     *         Returns true if the accumulated balance (principal + accrued interest,
     *         including not-yet-written pending rewards) >= lockedTarget.
     * @dev    Single eligibility check point. Replaces direct mapping reads.
     *         If the flag was already set by a transaction — returns true immediately.
     *         Otherwise calculates real-time without writing to state.
     *         ABI-compatible with the previous version (public mapping → public function).
     * @param  user Participant address.
     * @return true if housing eligibility is confirmed.
     */
    function isHousingEligible(address user) public view returns (bool) {
        // Fast path: flag already set by a transaction
        if (_housingEligibleStored[user]) return true;
        // Slow path: real-time calculation without writing to state
        StakeInfo storage s = stakes[user];
        if (!s.isActive || s.lockedTarget == 0) return false;
        uint256 pending = _computeNewRewards(s);
        return s.amount + s.accruedRewards + pending >= s.lockedTarget;
    }

    // =========================================================================
    // ADMIN FUNCTIONS (onlyOwner)
    // =========================================================================

    /**
     * @notice Set the global APR in basis points.
     *         Applies to new stakes only.
     * @param  newRate New APR (bp). Must be > 0.
     */
    function setAnnualRate(uint256 newRate) external onlyOwner {
        require(newRate >= MIN_APR,   "HS: rate below minimum");
        require(newRate <= MAX_APR,   "HS: rate exceeds maximum");
        emit APRUpdated(annualRate, newRate, block.timestamp);
        annualRate = newRate;
    }

    /**
     * @notice Set the minimum stake amount.
     * @param  newMin New minStake (wei). Must be > 0 and <= maxStake.
     */
    function setMinStake(uint256 newMin) external onlyOwner {
        require(newMin > 0,         "HS: minStake must be > 0");
        require(newMin <= maxStake, "HS: minStake > maxStake");
        emit MinStakeUpdated(minStake, newMin, block.timestamp);
        minStake = newMin;
    }

    /**
     * @notice Set the maximum stake amount.
     * @param  newMax New maxStake (wei). Must be >= minStake and <= targetAmount.
     */
    function setMaxStake(uint256 newMax) external onlyOwner {
        require(newMax >= minStake,     "HS: maxStake < minStake");
        require(newMax <= targetAmount, "HS: maxStake exceeds targetAmount");
        emit MaxStakeUpdated(maxStake, newMax, block.timestamp);
        maxStake = newMax;
    }

    /**
     * @notice Set the target accumulation amount.
     *         Applies to new stakes only.
     * @param  newTarget New target (wei). Must be > 0 and >= maxStake.
     */
    function setTargetAmount(uint256 newTarget) external onlyOwner {
        require(newTarget > 0,           "HS: target must be > 0");
        require(newTarget <= MAX_TARGET, "HS: target exceeds maximum");
        require(newTarget >= maxStake,   "HS: targetAmount below maxStake");
        emit TargetAmountUpdated(targetAmount, newTarget, block.timestamp);
        targetAmount = newTarget;
    }

    /**
     * @notice Set the cooldown period applied after early unstake (before eligibility).
     * @param  newCooldown Duration in seconds. 0 disables cooldown.
     *                     Max 2 years (63_072_000 s) to prevent admin lock-in.
     */
    function setUnstakeCooldown(uint256 newCooldown) external onlyOwner {
        require(newCooldown <= 730 days, "HS: cooldown too long");
        emit UnstakeCooldownUpdated(unstakeCooldown, newCooldown, block.timestamp);
        unstakeCooldown = newCooldown;
    }

    /**
     * @notice Returns how many seconds remain in a user's cooldown (0 if none).
     */
    function cooldownRemaining(address user) external view returns (uint256) {
        uint256 until = unstakeCooldownUntil[user];
        if (block.timestamp >= until) return 0;
        return until - block.timestamp;
    }

    /**
     * @notice Set the number of housing objects (slots).
     *         Cannot be reduced below current utilisation: the new capacity
     *         (n × targetAmount) must accommodate all active deposits.
     *         n = 0 is only allowed when no deposits are active.
     * @param  n New slot count.
     */
    function setTotalHousingSlots(uint256 n) external onlyOwner {
        // Overflow-guard first: targetAmount * n multiplication is safe
        require(n == 0 || targetAmount == 0 || n <= type(uint256).max / targetAmount, "HS: slots overflow");
        // Capacity-guard: new capacity must accommodate all active deposits
        require(
            n == 0 ? totalStakedPrincipal == 0 : totalStakedPrincipal <= targetAmount * n,
            "HS: capacity below current stake"
        );
        emit TotalSlotsUpdated(totalHousingSlots, n, block.timestamp);
        totalHousingSlots = n;
    }

    /**
     * @notice Add a participant to the waitlist.
     * @param  user Address. Cannot be zero.
     */
    function addToWaitlist(address user) external onlyOwner {
        require(user != address(0), "HS: zero address");
        isWaitlisted[user] = true;
        _arrayAdd(_waitlistArray, _waitlistIndex, user);
        emit WaitlistUpdated(user, true, block.timestamp);
    }

    /**
     * @notice Remove a participant from the waitlist.
     * @param  user Address. Cannot be zero.
     */
    function removeFromWaitlist(address user) external onlyOwner {
        require(user != address(0), "HS: zero address");
        isWaitlisted[user] = false;
        _arrayRemove(_waitlistArray, _waitlistIndex, user);
        emit WaitlistUpdated(user, false, block.timestamp);
    }

    /**
     * @notice Set the wallet address to receive funds upon offer conclusion.
     * @param  treasury Wallet address. Cannot be zero.
     */
    function setHousingTreasury(address treasury) external onlyOwner {
        require(treasury != address(0),    "HS: zero address");
        require(treasury != address(this), "HS: treasury cannot be self");
        emit HousingTreasuryUpdated(housingTreasury, treasury, block.timestamp);
        housingTreasury = treasury;
    }

    /**
     * @notice Reset the offerConcluded flag for an address (legal offer cancellation).
     * @dev    Use only when a legal basis exists (e.g. contract termination).
     *         Allows the address to participate in the programme again.
     * @param  user Participant address.
     */
    function resetOfferConcluded(address user) external onlyOwner {
        require(user != address(0), "HS: zero address");
        offerConcluded[user] = false;
        _arrayRemove(_offerConcludedArray, _offerConcludedIndex, user);
    }

    /**
     * @notice Fund the reward pool. Call approve(staking, amount) before invoking.
     * @param  amount Amount of ZLT (wei). Must be > 0.
     */
    function fundRewardPool(uint256 amount) external onlyOwner {
        require(amount > 0, "HS: amount must be > 0");
        token.safeTransferFrom(msg.sender, address(this), amount);
        rewardPool += amount;
        emit RewardPoolFunded(amount, block.timestamp);
    }

    /// @notice Pause the contract. emergencyWithdraw remains available.
    function pause() external onlyOwner {
        _pause();
    }

    /// @notice Unpause the contract.
    function unpause() external onlyOwner {
        _unpause();
    }

    /**
     * @notice Emergency token withdrawal. ONLY when paused.
     *         Decreases the accounting rewardPool.
     * @param  to     Recipient address.
     * @param  amount Amount of ZLT (wei).
     */
    function withdrawEmergencyFunds(address to, uint256 amount)
        external
        onlyOwner
        whenPaused
    {
        require(to     != address(0), "HS: zero address");
        require(amount > 0,           "HS: amount must be > 0");

        // Allow withdrawal ONLY from the free pool.
        // Reserved rewards (totalPromisedRewards) are untouchable —
        // otherwise owner could steal user deposits.
        uint256 freePool = rewardPool > totalPromisedRewards
            ? rewardPool - totalPromisedRewards
            : 0;
        require(amount <= freePool, "HS: would steal promised rewards");

        rewardPool -= amount;

        token.safeTransfer(to, amount);
        emit EmergencyFundsWithdrawn(to, amount, block.timestamp);
    }
}

@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/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
{
  "viaIR": true,
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.