Skip to content
Verified contractPartialMIT

YashixVaultStaking

Address0x0dbfa206f833a655fa211cc6ad49feb0632c071f
Balance

0 ETH

 

Transactions

76

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,107,712
Creation transaction
0x0af9eaf701…b231631921

YashixVaultStaking.sol

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

/**
 * @title YashixVaultStaking
 * @notice Production release candidate for the YASHIX USDT support vault.
 *
 * Core model
 * - Users deposit USDT into 6M or 12M locked positions.
 * - Rewards are paid in YASH from a fixed reward pool over a fixed duration.
 * - Rewards are shared pro-rata by active position weight.
 * - 6M = 1.00x weight, 12M = 1.25x weight by default.
 * - Claims are available once per day, while unclaimed rewards accumulate.
 * - Rewards stop at the position unlock epoch.
 * - After expiry, users request withdrawal, wait 7 days, then withdraw USDT.
 * - Owner may move USDT to a treasury, but pending withdrawal requests are protected.
 * - Public sync keeps expiry buckets and the global reward index current.
 *
 * Mainnet safety changes vs the early Sepolia prototype
 * - Production timing defaults are baked in (daily claim / 7d withdrawal / 30d extension window).
 * - Plan/timing changes are locked once rewards are activated.
 * - New deposits/extensions cannot create locks beyond rewardEnd.
 * - Public chunked sync avoids permanent bricking after long inactivity.
 * - Reward accounting tracks allocated rewards, allowing safe recovery of truly unallocated YASH after rewardEnd.
 * - Withdrawn positions can still claim already-earned stored YASH.
 * - Constructor validates token addresses have contract code and expected decimals.
 */

interface IERC20Like {
    function balanceOf(address account) external view returns (uint256);
    function allowance(address owner, address spender) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

interface IERC20MetadataLike is IERC20Like {
    function decimals() external view returns (uint8);
}

library SafeTransferLib {
    function safeTransfer(IERC20Like token, address to, uint256 amount) internal {
        (bool ok, bytes memory data) = address(token).call(
            abi.encodeWithSelector(IERC20Like.transfer.selector, to, amount)
        );
        require(ok && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED");
    }

    function safeTransferFrom(IERC20Like token, address from, address to, uint256 amount) internal {
        (bool ok, bytes memory data) = address(token).call(
            abi.encodeWithSelector(IERC20Like.transferFrom.selector, from, to, amount)
        );
        require(ok && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FROM_FAILED");
    }
}

abstract contract SimpleOwnable {
    address public owner;

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

    modifier onlyOwner() {
        require(msg.sender == owner, "NOT_OWNER");
        _;
    }

    constructor(address initialOwner) {
        require(initialOwner != address(0), "OWNER_ZERO");
        owner = initialOwner;
        emit OwnershipTransferred(address(0), initialOwner);
    }

    function transferOwnership(address newOwner) external onlyOwner {
        require(newOwner != address(0), "NEW_OWNER_ZERO");
        emit OwnershipTransferred(owner, newOwner);
        owner = newOwner;
    }
}

abstract contract SimpleReentrancyGuard {
    uint256 private _locked = 1;

    modifier nonReentrant() {
        require(_locked == 1, "REENTRANT_CALL");
        _locked = 2;
        _;
        _locked = 1;
    }
}

contract YashixVaultStaking is SimpleOwnable, SimpleReentrancyGuard {
    using SafeTransferLib for IERC20Like;

    uint256 public constant BPS = 10_000;
    uint256 public constant ACC_PRECISION = 1e30;

    uint8 public constant PLAN_6_MONTHS = 1;
    uint8 public constant PLAN_12_MONTHS = 2;

    // Normal actions can self-sync up to 30 missed daily epochs.
    // Longer inactivity is handled by public syncVault() in chunks.
    uint256 public constant MAX_AUTO_SYNC_EPOCHS = 30;
    uint256 public constant MAX_PUBLIC_SYNC_EPOCHS = 180;

    IERC20Like public immutable usdtToken;
    IERC20Like public immutable yashToken;
    address public treasuryWallet;

    struct Plan {
        uint256 duration;
        uint256 multiplierBps;
        bool enabled;
    }

    struct Position {
        address owner;
        uint8 planId;
        uint256 principal;
        uint256 weight;
        uint256 startTime;
        uint256 unlockTime;
        uint256 rewardDebt;
        uint256 storedRewards;
        uint256 lastClaimTime;
        bool withdrawn;
        bool withdrawalRequested;
        uint256 withdrawRequestTime;
        uint256 withdrawAvailableTime;
        uint256 extensions;
    }

    mapping(uint8 => Plan) public plans;
    mapping(uint256 => Position) public positions;
    mapping(address => uint256[]) private _userPositionIds;
    mapping(address => uint256) public userPrincipalOwed;

    uint256 public nextPositionId;

    // Fixed reward program.
    uint256 public immutable rewardPool;
    uint256 public immutable rewardDuration;
    uint256 public rewardStart;
    uint256 public rewardEnd;
    uint256 public rewardRate;
    bool public rewardsActivated;

    // Global reward accounting.
    uint256 public lastRewardTime;
    uint256 public accRewardPerWeight;
    uint256 public totalActiveWeight;
    uint256 public totalActivePrincipal;
    uint256 public totalPrincipalOwed;
    uint256 public totalRewardsAccrued;
    uint256 public totalRewardsClaimed;

    // Daily expiry buckets.
    uint256 public epochLength = 1 days;
    uint256 public nextEpochToProcess;
    uint256 public lastProcessedEpoch;

    mapping(uint256 => uint256) public scheduledWeightDecrease;
    mapping(uint256 => uint256) public scheduledPrincipalDeactivate;
    mapping(uint256 => uint256) public accRewardPerWeightAtEpoch;
    mapping(uint256 => bool) public epochProcessed;

    // User / treasury settings.
    uint256 public claimCooldown = 1 days;
    uint256 public withdrawalDelay = 7 days;
    uint256 public extensionWindow = 30 days;
    uint256 public minDeposit = 1_000000; // 1 USDT for 6-decimal USDT.
    uint256 public vaultCap;              // 0 = disabled.
    uint256 public walletCap;             // 0 = disabled.

    // Safe launch posture: deposits and treasury withdrawals start paused.
    bool public depositsPaused = true;
    bool public extensionsPaused;
    bool public treasuryWithdrawalsPaused = true;

    uint256 public totalTreasuryWithdrawn;
    uint256 public totalTreasuryRefilled;
    uint256 public totalPendingWithdrawalPrincipal;
    uint256 public totalRecoveredUnallocatedYash;

    event RewardsFunded(address indexed from, uint256 amount);
    event RewardsActivated(uint256 start, uint256 end, uint256 rewardRate);
    event Deposited(address indexed user, uint256 indexed positionId, uint256 amount, uint8 planId, uint256 weight, uint256 unlockTime);
    event RewardsClaimed(address indexed user, uint256 indexed positionId, uint256 amount);
    event PositionExtended(address indexed user, uint256 indexed positionId, uint8 planId, uint256 newWeight, uint256 newUnlockTime);
    event WithdrawalRequested(address indexed user, uint256 indexed positionId, uint256 amount, uint256 availableTime);
    event WithdrawalRequestCancelled(address indexed user, uint256 indexed positionId);
    event Withdrawn(address indexed user, uint256 indexed positionId, uint256 amount);
    event UsdtWithdrawnToTreasury(address indexed treasury, uint256 amount);
    event UsdtRefilled(address indexed from, uint256 amount);
    event TreasuryWalletUpdated(address indexed treasuryWallet);
    event PlanUpdated(uint8 indexed planId, uint256 duration, uint256 multiplierBps, bool enabled);
    event TimingUpdated(uint256 epochLength, uint256 claimCooldown, uint256 withdrawalDelay, uint256 extensionWindow);
    event CapsUpdated(uint256 vaultCap, uint256 walletCap, uint256 minDeposit);
    event PauseSettingsUpdated(bool depositsPaused, bool extensionsPaused, bool treasuryWithdrawalsPaused);
    event EpochProcessed(uint256 indexed epoch, uint256 weightDecrease, uint256 principalDeactivate, uint256 accRewardPerWeight);
    event VaultSynced(address indexed caller, uint256 epochsProcessed, uint256 lastRewardTime, uint256 nextEpochToProcess);
    event UnallocatedYashRecovered(address indexed to, uint256 amount);

    modifier onlyPositionOwner(uint256 positionId) {
        require(positions[positionId].owner == msg.sender, "NOT_POSITION_OWNER");
        _;
    }

    constructor(
        address initialOwner,
        address _usdtToken,
        address _yashToken,
        address _treasuryWallet,
        uint256 _rewardPool,
        uint256 _rewardDuration
    ) SimpleOwnable(initialOwner) {
        require(_usdtToken != address(0) && _usdtToken.code.length > 0, "BAD_USDT");
        require(_yashToken != address(0) && _yashToken.code.length > 0, "BAD_YASH");
        require(_usdtToken != _yashToken, "TOKENS_SAME");
        require(_treasuryWallet != address(0), "TREASURY_ZERO");
        require(_rewardPool > 0, "REWARD_POOL_ZERO");
        require(_rewardDuration > 0, "REWARD_DURATION_ZERO");
        require(IERC20MetadataLike(_usdtToken).decimals() == 6, "USDT_DECIMALS_NOT_6");
        require(IERC20MetadataLike(_yashToken).decimals() == 18, "YASH_DECIMALS_NOT_18");

        usdtToken = IERC20Like(_usdtToken);
        yashToken = IERC20Like(_yashToken);
        treasuryWallet = _treasuryWallet;
        rewardPool = _rewardPool;
        rewardDuration = _rewardDuration;

        plans[PLAN_6_MONTHS] = Plan({duration: 180 days, multiplierBps: 10_000, enabled: true});
        plans[PLAN_12_MONTHS] = Plan({duration: 365 days, multiplierBps: 12_500, enabled: true});
    }

    // ---------------------------------------------------------------------
    // Owner setup / controls
    // ---------------------------------------------------------------------

    function fundRewards(uint256 amount) external onlyOwner nonReentrant {
        require(amount > 0, "AMOUNT_ZERO");
        yashToken.safeTransferFrom(msg.sender, address(this), amount);
        emit RewardsFunded(msg.sender, amount);
    }

    function activateRewards() external onlyOwner {
        require(!rewardsActivated, "ALREADY_ACTIVATED");
        require(yashToken.balanceOf(address(this)) >= rewardPool, "REWARD_POOL_NOT_FUNDED");

        rewardRate = rewardPool / rewardDuration;
        require(rewardRate > 0, "REWARD_RATE_ZERO");

        rewardsActivated = true;
        rewardStart = block.timestamp;
        rewardEnd = block.timestamp + rewardDuration;
        lastRewardTime = rewardStart;
        nextEpochToProcess = _roundUpToEpoch(block.timestamp + 1);

        emit RewardsActivated(rewardStart, rewardEnd, rewardRate);
    }

    /**
     * @notice Pre-activation only. Production defaults are already set.
     * This remains available for a final configuration check before activation.
     */
    function setPlan(uint8 planId, uint256 duration, uint256 multiplierBps, bool enabled) external onlyOwner {
        require(!rewardsActivated, "RULES_LOCKED_AFTER_ACTIVATION");
        require(totalPrincipalOwed == 0, "POSITIONS_EXIST");
        require(planId != 0, "PLAN_ZERO");
        require(duration > 0, "DURATION_ZERO");
        require(multiplierBps >= BPS && multiplierBps <= 50_000, "BAD_MULTIPLIER");

        plans[planId] = Plan({duration: duration, multiplierBps: multiplierBps, enabled: enabled});
        emit PlanUpdated(planId, duration, multiplierBps, enabled);
    }

    /**
     * @notice Pre-activation only. Do not change epochLength after activation.
     */
    function setTiming(
        uint256 _epochLength,
        uint256 _claimCooldown,
        uint256 _withdrawalDelay,
        uint256 _extensionWindow
    ) external onlyOwner {
        require(!rewardsActivated, "RULES_LOCKED_AFTER_ACTIVATION");
        require(totalPrincipalOwed == 0, "POSITIONS_EXIST");
        require(_epochLength > 0, "EPOCH_ZERO");
        require(_claimCooldown > 0, "CLAIM_COOLDOWN_ZERO");
        require(_withdrawalDelay > 0, "WITHDRAW_DELAY_ZERO");

        epochLength = _epochLength;
        claimCooldown = _claimCooldown;
        withdrawalDelay = _withdrawalDelay;
        extensionWindow = _extensionWindow;

        emit TimingUpdated(epochLength, claimCooldown, withdrawalDelay, extensionWindow);
    }

    function setCaps(uint256 _vaultCap, uint256 _walletCap, uint256 _minDeposit) external onlyOwner {
        require(_minDeposit > 0, "MIN_DEPOSIT_ZERO");
        vaultCap = _vaultCap;
        walletCap = _walletCap;
        minDeposit = _minDeposit;
        emit CapsUpdated(vaultCap, walletCap, minDeposit);
    }

    function setPauseSettings(
        bool _depositsPaused,
        bool _extensionsPaused,
        bool _treasuryWithdrawalsPaused
    ) external onlyOwner {
        depositsPaused = _depositsPaused;
        extensionsPaused = _extensionsPaused;
        treasuryWithdrawalsPaused = _treasuryWithdrawalsPaused;
        emit PauseSettingsUpdated(depositsPaused, extensionsPaused, treasuryWithdrawalsPaused);
    }

    function setTreasuryWallet(address _treasuryWallet) external onlyOwner {
        require(_treasuryWallet != address(0), "TREASURY_ZERO");
        treasuryWallet = _treasuryWallet;
        emit TreasuryWalletUpdated(_treasuryWallet);
    }

    // ---------------------------------------------------------------------
    // User actions
    // ---------------------------------------------------------------------

    function deposit(uint256 amount, uint8 planId) external nonReentrant {
        require(rewardsActivated, "REWARDS_NOT_ACTIVE");
        require(block.timestamp < rewardEnd, "REWARD_PERIOD_ENDED");
        require(!depositsPaused, "DEPOSITS_PAUSED");
        require(amount >= minDeposit, "BELOW_MINIMUM");

        Plan memory plan = plans[planId];
        require(plan.enabled, "PLAN_DISABLED");

        _autoSync();

        uint256 unlockTime = _roundUpToEpoch(block.timestamp + plan.duration);
        require(unlockTime <= rewardEnd, "LOCK_EXCEEDS_REWARD_END");

        if (vaultCap > 0) {
            require(totalPrincipalOwed + amount <= vaultCap, "VAULT_CAP_EXCEEDED");
        }
        if (walletCap > 0) {
            require(userPrincipalOwed[msg.sender] + amount <= walletCap, "WALLET_CAP_EXCEEDED");
        }

        uint256 weight = (amount * plan.multiplierBps) / BPS;
        require(weight > 0, "WEIGHT_ZERO");

        usdtToken.safeTransferFrom(msg.sender, address(this), amount);

        uint256 positionId = ++nextPositionId;
        positions[positionId] = Position({
            owner: msg.sender,
            planId: planId,
            principal: amount,
            weight: weight,
            startTime: block.timestamp,
            unlockTime: unlockTime,
            rewardDebt: (weight * accRewardPerWeight) / ACC_PRECISION,
            storedRewards: 0,
            lastClaimTime: block.timestamp,
            withdrawn: false,
            withdrawalRequested: false,
            withdrawRequestTime: 0,
            withdrawAvailableTime: 0,
            extensions: 0
        });

        _userPositionIds[msg.sender].push(positionId);
        userPrincipalOwed[msg.sender] += amount;
        totalPrincipalOwed += amount;
        totalActivePrincipal += amount;
        totalActiveWeight += weight;

        scheduledWeightDecrease[unlockTime] += weight;
        scheduledPrincipalDeactivate[unlockTime] += amount;

        emit Deposited(msg.sender, positionId, amount, planId, weight, unlockTime);
    }

    function claimRewards(uint256 positionId) external nonReentrant onlyPositionOwner(positionId) {
        _autoSync();
        _settlePosition(positionId);

        Position storage p = positions[positionId];
        uint256 amount = p.storedRewards;
        require(amount > 0, "NO_REWARDS");

        bool expiredOrInactive = p.weight == 0 || block.timestamp >= p.unlockTime || p.withdrawn;
        require(block.timestamp >= p.lastClaimTime + claimCooldown || expiredOrInactive, "CLAIM_COOLDOWN_ACTIVE");

        p.storedRewards = 0;
        p.lastClaimTime = block.timestamp;
        totalRewardsClaimed += amount;

        yashToken.safeTransfer(msg.sender, amount);
        emit RewardsClaimed(msg.sender, positionId, amount);
    }

    function extendPosition(uint256 positionId, uint8 newPlanId) external nonReentrant onlyPositionOwner(positionId) {
        require(rewardsActivated && block.timestamp < rewardEnd, "REWARD_PERIOD_ENDED");
        require(!extensionsPaused, "EXTENSIONS_PAUSED");

        Plan memory plan = plans[newPlanId];
        require(plan.enabled, "PLAN_DISABLED");

        _autoSync();
        _settlePosition(positionId);

        Position storage p = positions[positionId];
        require(!p.withdrawn, "ALREADY_WITHDRAWN");
        require(p.principal > 0, "NO_PRINCIPAL");
        require(block.timestamp >= p.unlockTime || block.timestamp + extensionWindow >= p.unlockTime, "EXTENSION_NOT_OPEN");

        uint256 newUnlockTime = _roundUpToEpoch(block.timestamp + plan.duration);
        require(newUnlockTime <= rewardEnd, "LOCK_EXCEEDS_REWARD_END");

        if (p.withdrawalRequested) {
            p.withdrawalRequested = false;
            p.withdrawRequestTime = 0;
            p.withdrawAvailableTime = 0;
            totalPendingWithdrawalPrincipal -= p.principal;
            emit WithdrawalRequestCancelled(msg.sender, positionId);
        }

        uint256 oldWeight = p.weight;
        uint256 newWeight = (p.principal * plan.multiplierBps) / BPS;
        require(newWeight > 0, "NEW_WEIGHT_ZERO");

        if (oldWeight > 0) {
            scheduledWeightDecrease[p.unlockTime] -= oldWeight;
            scheduledPrincipalDeactivate[p.unlockTime] -= p.principal;

            if (newWeight >= oldWeight) {
                totalActiveWeight += newWeight - oldWeight;
            } else {
                totalActiveWeight -= oldWeight - newWeight;
            }
        } else {
            totalActiveWeight += newWeight;
            totalActivePrincipal += p.principal;
        }

        scheduledWeightDecrease[newUnlockTime] += newWeight;
        scheduledPrincipalDeactivate[newUnlockTime] += p.principal;

        p.planId = newPlanId;
        p.weight = newWeight;
        p.startTime = block.timestamp;
        p.unlockTime = newUnlockTime;
        p.rewardDebt = (newWeight * accRewardPerWeight) / ACC_PRECISION;
        p.extensions += 1;

        emit PositionExtended(msg.sender, positionId, newPlanId, newWeight, newUnlockTime);
    }

    function requestWithdrawal(uint256 positionId) external nonReentrant onlyPositionOwner(positionId) {
        _autoSync();
        _settlePosition(positionId);

        Position storage p = positions[positionId];
        require(!p.withdrawn, "ALREADY_WITHDRAWN");
        require(!p.withdrawalRequested, "ALREADY_REQUESTED");
        require(block.timestamp >= p.unlockTime, "LOCK_NOT_EXPIRED");
        require(p.weight == 0, "POSITION_STILL_ACTIVE");

        p.withdrawalRequested = true;
        p.withdrawRequestTime = block.timestamp;
        p.withdrawAvailableTime = block.timestamp + withdrawalDelay;
        totalPendingWithdrawalPrincipal += p.principal;

        emit WithdrawalRequested(msg.sender, positionId, p.principal, p.withdrawAvailableTime);
    }

    function cancelWithdrawalRequest(uint256 positionId) external nonReentrant onlyPositionOwner(positionId) {
        Position storage p = positions[positionId];
        require(p.withdrawalRequested, "NOT_REQUESTED");
        require(!p.withdrawn, "ALREADY_WITHDRAWN");

        p.withdrawalRequested = false;
        p.withdrawRequestTime = 0;
        p.withdrawAvailableTime = 0;
        totalPendingWithdrawalPrincipal -= p.principal;

        emit WithdrawalRequestCancelled(msg.sender, positionId);
    }

    function withdraw(uint256 positionId) external nonReentrant onlyPositionOwner(positionId) {
        _autoSync();
        _settlePosition(positionId);

        Position storage p = positions[positionId];
        require(!p.withdrawn, "ALREADY_WITHDRAWN");
        require(p.withdrawalRequested, "WITHDRAWAL_NOT_REQUESTED");
        require(block.timestamp >= p.withdrawAvailableTime, "WITHDRAWAL_DELAY_ACTIVE");
        require(p.weight == 0, "POSITION_STILL_ACTIVE");

        uint256 amount = p.principal;
        require(usdtToken.balanceOf(address(this)) >= amount, "USDT_REFILL_NEEDED");

        p.withdrawn = true;
        p.withdrawalRequested = false;
        p.withdrawRequestTime = 0;
        p.withdrawAvailableTime = 0;

        totalPrincipalOwed -= amount;
        userPrincipalOwed[msg.sender] -= amount;
        totalPendingWithdrawalPrincipal -= amount;

        usdtToken.safeTransfer(msg.sender, amount);
        emit Withdrawn(msg.sender, positionId, amount);
    }

    // ---------------------------------------------------------------------
    // Treasury actions
    // ---------------------------------------------------------------------

    function withdrawUsdtToTreasury(uint256 amount) external onlyOwner nonReentrant {
        require(!treasuryWithdrawalsPaused, "TREASURY_WITHDRAWALS_PAUSED");
        require(amount > 0, "AMOUNT_ZERO");

        uint256 balance = usdtToken.balanceOf(address(this));
        require(balance >= amount, "INSUFFICIENT_USDT");
        require(balance - amount >= totalPendingWithdrawalPrincipal, "PENDING_WITHDRAWALS_PROTECTED");

        totalTreasuryWithdrawn += amount;
        usdtToken.safeTransfer(treasuryWallet, amount);
        emit UsdtWithdrawnToTreasury(treasuryWallet, amount);
    }

    function refillUsdt(uint256 amount) external nonReentrant {
        require(amount > 0, "AMOUNT_ZERO");
        usdtToken.safeTransferFrom(msg.sender, address(this), amount);
        totalTreasuryRefilled += amount;
        emit UsdtRefilled(msg.sender, amount);
    }

    /**
     * @notice Recover only YASH that was never allocated to users.
     * Callable only after the reward program has ended and all expiry epochs are synced.
     */
    function recoverUnallocatedYash(address to, uint256 amount) external onlyOwner nonReentrant {
        require(to != address(0), "TO_ZERO");
        require(rewardsActivated && block.timestamp >= rewardEnd, "REWARD_PERIOD_NOT_ENDED");
        require(!_syncNeeded(), "SYNC_REQUIRED");

        uint256 balance = yashToken.balanceOf(address(this));
        uint256 outstandingAccrued = totalRewardsAccrued > totalRewardsClaimed
            ? totalRewardsAccrued - totalRewardsClaimed
            : 0;
        uint256 excess = balance > outstandingAccrued ? balance - outstandingAccrued : 0;

        require(amount > 0 && amount <= excess, "AMOUNT_EXCEEDS_UNALLOCATED");
        totalRecoveredUnallocatedYash += amount;
        yashToken.safeTransfer(to, amount);
        emit UnallocatedYashRecovered(to, amount);
    }

    // ---------------------------------------------------------------------
    // Public sync
    // ---------------------------------------------------------------------

    /**
     * @notice Permissionless maintenance. Processes up to maxEpochs expired daily buckets.
     * No funds move. Can be called repeatedly after long inactivity.
     */
    function syncVault(uint256 maxEpochs) external returns (uint256 processed) {
        require(maxEpochs > 0 && maxEpochs <= MAX_PUBLIC_SYNC_EPOCHS, "BAD_MAX_EPOCHS");
        processed = _syncUpTo(maxEpochs);
        emit VaultSynced(msg.sender, processed, lastRewardTime, nextEpochToProcess);
    }

    /**
     * @notice Frontend helper for deciding whether a public sync transaction is needed.
     */
    function syncPreview()
        external
        view
        returns (
            bool syncNeeded,
            uint256 nextEpoch,
            uint256 targetTime,
            uint256 pendingEpochs,
            uint256 currentActiveWeight,
            uint256 currentActivePrincipal
        )
    {
        targetTime = rewardsActivated ? _rewardTargetNow() : 0;
        nextEpoch = nextEpochToProcess;
        pendingEpochs = _pendingEpochCount();
        syncNeeded = pendingEpochs > 0;
        currentActiveWeight = previewActiveWeight();
        currentActivePrincipal = previewActivePrincipal();
    }

    // ---------------------------------------------------------------------
    // Views for frontend / admin
    // ---------------------------------------------------------------------

    function getUserPositionIds(address user) external view returns (uint256[] memory) {
        return _userPositionIds[user];
    }

    function getUserPositionCount(address user) external view returns (uint256) {
        return _userPositionIds[user].length;
    }

    function getUserPositionIdAt(address user, uint256 index) external view returns (uint256) {
        return _userPositionIds[user][index];
    }

    function pendingRewards(uint256 positionId) public view returns (uint256) {
        Position memory p = positions[positionId];
        if (p.owner == address(0)) return 0;
        if (p.withdrawn || p.weight == 0) return p.storedRewards;

        uint256 applicableAcc;
        if (p.unlockTime <= lastProcessedEpoch && epochProcessed[p.unlockTime]) {
            applicableAcc = accRewardPerWeightAtEpoch[p.unlockTime];
        } else if (block.timestamp >= p.unlockTime) {
            applicableAcc = _previewAccUntil(p.unlockTime);
        } else {
            applicableAcc = _previewAccUntil(block.timestamp);
        }

        uint256 accumulated = (p.weight * applicableAcc) / ACC_PRECISION;
        uint256 newRewards = accumulated > p.rewardDebt ? accumulated - p.rewardDebt : 0;
        return p.storedRewards + newRewards;
    }

    function previewUserPendingRewards(uint256 positionId) external view returns (uint256) {
        return pendingRewards(positionId);
    }

    function canClaim(uint256 positionId) external view returns (bool) {
        Position memory p = positions[positionId];
        if (p.owner == address(0)) return false;
        if (pendingRewards(positionId) == 0) return false;
        bool expiredOrInactive = p.weight == 0 || block.timestamp >= p.unlockTime || p.withdrawn;
        return block.timestamp >= p.lastClaimTime + claimCooldown || expiredOrInactive;
    }

    function canRequestWithdrawal(uint256 positionId) external view returns (bool) {
        Position memory p = positions[positionId];
        return p.owner != address(0)
            && !p.withdrawn
            && !p.withdrawalRequested
            && block.timestamp >= p.unlockTime;
    }

    function canWithdraw(uint256 positionId) external view returns (bool) {
        Position memory p = positions[positionId];
        return p.owner != address(0)
            && !p.withdrawn
            && p.withdrawalRequested
            && block.timestamp >= p.withdrawAvailableTime
            && usdtToken.balanceOf(address(this)) >= p.principal;
    }

    function canExtend(uint256 positionId) external view returns (bool) {
        Position memory p = positions[positionId];
        if (!rewardsActivated || block.timestamp >= rewardEnd || extensionsPaused) return false;
        if (p.owner == address(0) || p.withdrawn || p.principal == 0) return false;
        if (!(block.timestamp >= p.unlockTime || block.timestamp + extensionWindow >= p.unlockTime)) return false;

        // At least one enabled production plan must still fit before rewardEnd.
        bool plan1Fits = plans[PLAN_6_MONTHS].enabled
            && _roundUpToEpoch(block.timestamp + plans[PLAN_6_MONTHS].duration) <= rewardEnd;
        bool plan2Fits = plans[PLAN_12_MONTHS].enabled
            && _roundUpToEpoch(block.timestamp + plans[PLAN_12_MONTHS].duration) <= rewardEnd;
        return plan1Fits || plan2Fits;
    }

    function canDepositPlan(uint8 planId) external view returns (bool) {
        if (!rewardsActivated || depositsPaused || block.timestamp >= rewardEnd) return false;
        Plan memory plan = plans[planId];
        if (!plan.enabled) return false;
        return _roundUpToEpoch(block.timestamp + plan.duration) <= rewardEnd;
    }

    function usdtBalanceInVault() public view returns (uint256) {
        return usdtToken.balanceOf(address(this));
    }

    function yashBalanceInVault() public view returns (uint256) {
        return yashToken.balanceOf(address(this));
    }

    function usdtShortfallForAllPrincipal() public view returns (uint256) {
        uint256 balance = usdtToken.balanceOf(address(this));
        return totalPrincipalOwed > balance ? totalPrincipalOwed - balance : 0;
    }

    function usdtShortfallForPendingWithdrawals() public view returns (uint256) {
        uint256 balance = usdtToken.balanceOf(address(this));
        return totalPendingWithdrawalPrincipal > balance ? totalPendingWithdrawalPrincipal - balance : 0;
    }

    function previewActiveWeight() public view returns (uint256 weight) {
        weight = totalActiveWeight;
        if (!rewardsActivated || nextEpochToProcess == 0) return weight;

        uint256 target = _rewardTargetNow();
        uint256 epoch = nextEpochToProcess;
        while (epoch <= target) {
            uint256 dec = scheduledWeightDecrease[epoch];
            weight = dec >= weight ? 0 : weight - dec;
            epoch += epochLength;
        }
    }

    function previewActivePrincipal() public view returns (uint256 principal) {
        principal = totalActivePrincipal;
        if (!rewardsActivated || nextEpochToProcess == 0) return principal;

        uint256 target = _rewardTargetNow();
        uint256 epoch = nextEpochToProcess;
        while (epoch <= target) {
            uint256 dec = scheduledPrincipalDeactivate[epoch];
            principal = dec >= principal ? 0 : principal - dec;
            epoch += epochLength;
        }
    }

    function principalUnlockingBefore(uint256 deadline) external view returns (uint256 amount) {
        if (!rewardsActivated || nextEpochToProcess == 0 || deadline < block.timestamp) return 0;

        uint256 end = deadline < rewardEnd ? deadline : rewardEnd;
        uint256 epoch = nextEpochToProcess;
        while (epoch <= end) {
            amount += scheduledPrincipalDeactivate[epoch];
            epoch += epochLength;
        }
    }

    function estimatedRewardPerYear() external view returns (uint256) {
        if (!rewardsActivated || block.timestamp >= rewardEnd) return 0;
        return rewardRate * 365 days;
    }

    function secondsUntilRewardEnd() external view returns (uint256) {
        return !rewardsActivated || block.timestamp >= rewardEnd ? 0 : rewardEnd - block.timestamp;
    }

    function unallocatedYashAvailableAfterEnd() external view returns (uint256) {
        if (!rewardsActivated || block.timestamp < rewardEnd || _syncNeeded()) return 0;
        uint256 balance = yashToken.balanceOf(address(this));
        uint256 outstandingAccrued = totalRewardsAccrued > totalRewardsClaimed
            ? totalRewardsAccrued - totalRewardsClaimed
            : 0;
        return balance > outstandingAccrued ? balance - outstandingAccrued : 0;
    }

    // ---------------------------------------------------------------------
    // Internal reward / sync accounting
    // ---------------------------------------------------------------------

    function _autoSync() internal {
        if (!rewardsActivated) return;
        uint256 pending = _pendingEpochCount();
        require(pending <= MAX_AUTO_SYNC_EPOCHS, "SYNC_REQUIRED_CALL_SYNCVAULT");
        _syncUpTo(pending);
    }

    function _syncUpTo(uint256 maxEpochs) internal returns (uint256 processed) {
        if (!rewardsActivated) return 0;

        uint256 target = _rewardTargetNow();
        uint256 epoch = nextEpochToProcess;

        while (epoch != 0 && epoch <= target && processed < maxEpochs) {
            _advanceRewards(epoch);

            uint256 weightDecrease = scheduledWeightDecrease[epoch];
            uint256 principalDecrease = scheduledPrincipalDeactivate[epoch];

            if (weightDecrease > 0 || principalDecrease > 0) {
                accRewardPerWeightAtEpoch[epoch] = accRewardPerWeight;
                epochProcessed[epoch] = true;
                lastProcessedEpoch = epoch;

                if (weightDecrease > 0) {
                    totalActiveWeight -= weightDecrease;
                    scheduledWeightDecrease[epoch] = 0;
                }
                if (principalDecrease > 0) {
                    totalActivePrincipal -= principalDecrease;
                    scheduledPrincipalDeactivate[epoch] = 0;
                }

                emit EpochProcessed(epoch, weightDecrease, principalDecrease, accRewardPerWeight);
            }

            epoch += epochLength;
            nextEpochToProcess = epoch;
            unchecked { ++processed; }
        }

        // If all due expiry buckets have been processed, safely advance rewards to target.
        if (nextEpochToProcess == 0 || nextEpochToProcess > target) {
            _advanceRewards(target);
        }

        // No position may be created beyond rewardEnd, so once all epochs through rewardEnd
        // are processed there is no reason to continue generating empty epochs forever.
        if (target == rewardEnd && nextEpochToProcess != 0 && nextEpochToProcess > rewardEnd) {
            nextEpochToProcess = 0;
        }
    }

    function _advanceRewards(uint256 toTime) internal {
        if (toTime <= lastRewardTime) return;

        uint256 cappedFrom = lastRewardTime < rewardEnd ? lastRewardTime : rewardEnd;
        uint256 cappedTo = toTime < rewardEnd ? toTime : rewardEnd;

        if (cappedTo > cappedFrom && totalActiveWeight > 0) {
            uint256 reward = (cappedTo - cappedFrom) * rewardRate;
            totalRewardsAccrued += reward;
            accRewardPerWeight += (reward * ACC_PRECISION) / totalActiveWeight;
        }

        lastRewardTime = toTime;
    }

    function _settlePosition(uint256 positionId) internal {
        Position storage p = positions[positionId];
        if (p.owner == address(0) || p.weight == 0) return;

        uint256 applicableAcc = accRewardPerWeight;
        bool expiredAndProcessed = p.unlockTime <= lastProcessedEpoch && epochProcessed[p.unlockTime];

        if (expiredAndProcessed) {
            applicableAcc = accRewardPerWeightAtEpoch[p.unlockTime];
        }

        uint256 accumulated = (p.weight * applicableAcc) / ACC_PRECISION;
        if (accumulated > p.rewardDebt) {
            p.storedRewards += accumulated - p.rewardDebt;
        }

        if (expiredAndProcessed) {
            p.weight = 0;
            p.rewardDebt = 0;
        } else {
            p.rewardDebt = accumulated;
        }
    }

    function _previewAccUntil(uint256 targetTime) internal view returns (uint256) {
        if (!rewardsActivated) return accRewardPerWeight;
        if (targetTime <= lastRewardTime) return accRewardPerWeight;

        uint256 cappedTarget = targetTime < rewardEnd ? targetTime : rewardEnd;
        uint256 localAcc = accRewardPerWeight;
        uint256 localWeight = totalActiveWeight;
        uint256 localLast = lastRewardTime;
        uint256 epoch = nextEpochToProcess;

        while (epoch != 0 && epoch <= cappedTarget) {
            localAcc = _previewAdvance(localAcc, localLast, epoch, localWeight);
            localLast = epoch;

            uint256 weightDecrease = scheduledWeightDecrease[epoch];
            if (weightDecrease > 0) {
                localWeight = weightDecrease >= localWeight ? 0 : localWeight - weightDecrease;
            }

            epoch += epochLength;
        }

        localAcc = _previewAdvance(localAcc, localLast, cappedTarget, localWeight);
        return localAcc;
    }

    function _previewAdvance(
        uint256 localAcc,
        uint256 fromTime,
        uint256 toTime,
        uint256 localWeight
    ) internal view returns (uint256) {
        if (toTime <= fromTime) return localAcc;

        uint256 cappedFrom = fromTime < rewardEnd ? fromTime : rewardEnd;
        uint256 cappedTo = toTime < rewardEnd ? toTime : rewardEnd;

        if (cappedTo > cappedFrom && localWeight > 0) {
            uint256 reward = (cappedTo - cappedFrom) * rewardRate;
            localAcc += (reward * ACC_PRECISION) / localWeight;
        }
        return localAcc;
    }

    function _pendingEpochCount() internal view returns (uint256) {
        if (!rewardsActivated || nextEpochToProcess == 0) return 0;
        uint256 target = _rewardTargetNow();
        if (nextEpochToProcess > target) return 0;
        return ((target - nextEpochToProcess) / epochLength) + 1;
    }

    function _syncNeeded() internal view returns (bool) {
        return _pendingEpochCount() > 0;
    }

    function _rewardTargetNow() internal view returns (uint256) {
        return block.timestamp < rewardEnd ? block.timestamp : rewardEnd;
    }

    function _roundUpToEpoch(uint256 timestamp) internal view returns (uint256) {
        uint256 remainder = timestamp % epochLength;
        if (remainder == 0) return timestamp;
        return timestamp + (epochLength - remainder);
    }
}
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.