Skip to content
Verified contractExactMIT

LockedSleeveManager

Address0xfa0ab61e06a0d03097e7963fc60a18f8b87f1e52
Balance

0 ETH

 

Transactions

3

 

Compiler

solc 0.8.20

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,089,852
Creation transaction
0x455267fb96…7c624e2c42

contracts/src/LockedSleeveManager.sol

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

/**
 * @title LockedSleeveManager
 * @notice User opt-in "Locked Yield Sleeve" for Apyx apyUSD (Protocol ID 9).
 *
 * Flow per user:
 *   deposit  → USDC → apxUSD (Curve pool) → apyUSD vault (ERC-4626 deposit)
 *   request  → records unlockTimestamp = now + 30 days
 *   claim    → after 30 days, apyUSD.redeem() → apxUSD → USDC (Curve) → user
 *
 * Key invariants:
 *  - Engine NEVER touches this contract's positions.
 *  - Conservative tier (0) is blocked — 30-day lockup is incompatible.
 *  - No new deposits allowed while a withdraw request is pending.
 *  - Curve pool + coin indices are set by owner before opening to users.
 *
 * Deployment sequence:
 *  1. Deploy this contract (owner = deployer).
 *  2. Call setCurvePool(pool, usdcIdx, apxusdIdx).
 *  3. Verify totalLockedAssetsUsdc() returns 0 — then open to users.
 */

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

interface IERC4626Minimal {
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
    function convertToAssets(uint256 shares) external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
}

// Curve V1 StableSwap — compatible with most USD stablecoin pools
interface ICurvePool {
    function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);
    function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256);
}

contract LockedSleeveManager {
    // ─── Constants ───────────────────────────────────────────────────────────
    uint256 public constant LOCKED_COOLDOWN   = 30 days;
    uint8   public constant TIER_CONSERVATIVE = 0;  // blocked
    uint8   public constant TIER_BALANCED     = 1;  // eligible
    uint8   public constant TIER_AGGRESSIVE   = 2;  // eligible

    // Ethereum mainnet
    address public constant USDC   = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
    address public constant APXUSD = 0x98A878b1Cd98131B271883B390f68D2c90674665;
    address public constant APYUSD = 0x38EEb52F0771140d10c4E9A9a72349A329Fe8a6A;

    // ─── Errors ───────────────────────────────────────────────────────────────
    error OnlyOwner();
    error ZeroAmount();
    error TierNotEligible();
    error PoolNotSet();
    error NoPosition();
    error CooldownNotMet();
    error WithdrawAlreadyRequested();
    error SlippageTooHigh();
    error Reentrancy();
    error InvalidAddress();
    error SlippageOutOfRange();

    // ─── Events ───────────────────────────────────────────────────────────────
    event LockedDeposit(address indexed user, uint8 tier, uint256 usdcAmount, uint256 apyShares);
    event WithdrawRequested(address indexed user, uint256 unlockTimestamp);
    event LockedWithdraw(address indexed user, uint256 usdcOut);
    event CurvePoolSet(address pool, int128 usdcIdx, int128 apxusdIdx);
    event MaxSlippageSet(uint256 bps);

    // ─── State ───────────────────────────────────────────────────────────────
    address public owner;

    // Curve pool for USDC <-> apxUSD swaps (set by owner before users can deposit)
    address public curvePool;
    int128  public curveUsdcIdx;     // Curve coin index of USDC
    int128  public curveApxusdIdx;   // Curve coin index of apxUSD

    uint256 public maxSlippageBps = 100;  // 1% default; owner can set 0–300
    uint256 private _locked = 1;

    struct ApyxPosition {
        uint256 apyShares;          // apyUSD ERC-4626 shares held by this contract for the user
        uint256 depositTimestamp;   // timestamp of most recent deposit
        uint256 unlockRequestTs;    // 0 = no active request; non-zero = request made at this time
        uint8   tier;               // 1=balanced, 2=aggressive
    }

    mapping(address => ApyxPosition) public userApyxPosition;

    constructor() {
        owner = msg.sender;
        // Approve apyUSD vault to spend apxUSD (deposit path)
        IERC20(APXUSD).approve(APYUSD, type(uint256).max);
    }

    modifier onlyOwner()    { if (msg.sender != owner) revert OnlyOwner(); _; }
    modifier nonReentrant() { if (_locked == 2) revert Reentrancy(); _locked = 2; _; _locked = 1; }

    // ─── Admin ────────────────────────────────────────────────────────────────

    /**
     * @notice Set the Curve pool used for USDC <-> apxUSD swaps.
     *         Must be called before users can deposit.
     * @param pool       Curve pool address.
     * @param usdcIdx    Coin index of USDC in the pool.
     * @param apxusdIdx  Coin index of apxUSD in the pool.
     */
    function setCurvePool(address pool, int128 usdcIdx, int128 apxusdIdx) external onlyOwner {
        if (pool == address(0)) revert InvalidAddress();
        curvePool      = pool;
        curveUsdcIdx   = usdcIdx;
        curveApxusdIdx = apxusdIdx;
        // Approve pool to spend both tokens
        IERC20(USDC).approve(pool, type(uint256).max);
        IERC20(APXUSD).approve(pool, type(uint256).max);
        emit CurvePoolSet(pool, usdcIdx, apxusdIdx);
    }

    /**
     * @notice Update maximum slippage tolerance for Curve swaps.
     * @param bps  Basis points (100 = 1%). Max 300 (3%).
     */
    function setMaxSlippage(uint256 bps) external onlyOwner {
        if (bps > 300) revert SlippageOutOfRange();
        maxSlippageBps = bps;
        emit MaxSlippageSet(bps);
    }

    function transferOwnership(address newOwner) external onlyOwner {
        if (newOwner == address(0)) revert InvalidAddress();
        owner = newOwner;
    }

    // ─── User: Deposit ────────────────────────────────────────────────────────

    /**
     * @notice Deposit USDC into the Apyx locked yield sleeve.
     *         USDC is swapped to apxUSD via Curve, then deposited into apyUSD vault.
     *         No new deposits allowed while a withdraw request is pending.
     *
     * @param usdcAmount  USDC to deposit (6 decimals).
     * @param tier        1=Balanced, 2=Aggressive. Conservative (0) is blocked.
     */
    function depositToApyx(uint256 usdcAmount, uint8 tier) external nonReentrant {
        if (usdcAmount == 0) revert ZeroAmount();
        if (tier == TIER_CONSERVATIVE) revert TierNotEligible();
        if (curvePool == address(0)) revert PoolNotSet();

        ApyxPosition storage pos = userApyxPosition[msg.sender];
        // Block new deposits while a withdrawal is in progress
        if (pos.unlockRequestTs != 0) revert WithdrawAlreadyRequested();

        // 1. Pull USDC from caller
        IERC20(USDC).transferFrom(msg.sender, address(this), usdcAmount);

        // 2. Swap USDC → apxUSD via Curve
        uint256 expectedApx = ICurvePool(curvePool).get_dy(curveUsdcIdx, curveApxusdIdx, usdcAmount);
        uint256 minApx = expectedApx * (10000 - maxSlippageBps) / 10000;
        uint256 apxReceived = ICurvePool(curvePool).exchange(
            curveUsdcIdx, curveApxusdIdx, usdcAmount, minApx
        );
        if (apxReceived < minApx) revert SlippageTooHigh();

        // 3. Deposit apxUSD into apyUSD vault → receive apyUSD shares
        uint256 apyShares = IERC4626Minimal(APYUSD).deposit(apxReceived, address(this));

        // 4. Record position
        pos.apyShares        += apyShares;
        pos.depositTimestamp  = block.timestamp;
        pos.unlockRequestTs   = 0;
        pos.tier              = tier;

        emit LockedDeposit(msg.sender, tier, usdcAmount, apyShares);
    }

    // ─── User: Request Withdraw ───────────────────────────────────────────────

    /**
     * @notice Initiate withdrawal from the Apyx locked sleeve.
     *         Starts the 30-day cooldown. No further deposits until claim is complete.
     *         After calling this, wait 30 days then call claimApyx().
     */
    function requestWithdrawApyx() external {
        ApyxPosition storage pos = userApyxPosition[msg.sender];
        if (pos.apyShares == 0) revert NoPosition();
        if (pos.unlockRequestTs != 0) revert WithdrawAlreadyRequested();

        pos.unlockRequestTs = block.timestamp;
        emit WithdrawRequested(msg.sender, block.timestamp + LOCKED_COOLDOWN);
    }

    // ─── User: Claim ──────────────────────────────────────────────────────────

    /**
     * @notice Claim USDC after the 30-day cooldown has elapsed.
     *         Redeems all apyUSD shares, swaps apxUSD → USDC via Curve, transfers to caller.
     * @return usdcOut  USDC received by the caller.
     */
    function claimApyx() external nonReentrant returns (uint256 usdcOut) {
        ApyxPosition storage pos = userApyxPosition[msg.sender];
        if (pos.apyShares == 0) revert NoPosition();
        if (pos.unlockRequestTs == 0) revert NoPosition();
        if (block.timestamp < pos.unlockRequestTs + LOCKED_COOLDOWN) revert CooldownNotMet();
        if (curvePool == address(0)) revert PoolNotSet();

        uint256 shares = pos.apyShares;
        // Clear position before external calls
        pos.apyShares       = 0;
        pos.unlockRequestTs = 0;

        // 1. Redeem apyUSD shares → apxUSD (apyUSD vault returns apxUSD)
        uint256 apxReceived = IERC4626Minimal(APYUSD).redeem(shares, address(this), address(this));

        // 2. Swap apxUSD → USDC via Curve
        uint256 expectedUsdc = ICurvePool(curvePool).get_dy(curveApxusdIdx, curveUsdcIdx, apxReceived);
        uint256 minUsdc = expectedUsdc * (10000 - maxSlippageBps) / 10000;
        usdcOut = ICurvePool(curvePool).exchange(
            curveApxusdIdx, curveUsdcIdx, apxReceived, minUsdc
        );
        if (usdcOut < minUsdc) revert SlippageTooHigh();

        // 3. Transfer USDC to caller
        IERC20(USDC).transfer(msg.sender, usdcOut);

        emit LockedWithdraw(msg.sender, usdcOut);
    }

    // ─── View Functions ───────────────────────────────────────────────────────

    struct PositionView {
        uint256 apyShares;
        uint256 assetsEstimateUsdc;  // approximate current value (apyUSD → apxUSD → USDC)
        uint256 depositTimestamp;
        uint256 unlockRequestTs;
        uint256 unlockAvailableTs;   // 0 if no request pending
        uint8   tier;
        bool    withdrawRequested;
        int256  daysUntilUnlock;     // -1 = no request, 0 = ready, >0 = days remaining
    }

    function getPosition(address user) external view returns (PositionView memory v) {
        ApyxPosition storage pos = userApyxPosition[user];

        uint256 assetsEst = 0;
        if (pos.apyShares > 0) {
            // apyUSD returns apxUSD (18 decimals) — convert to USDC (6 decimals) at near-parity
            uint256 apxValue = IERC4626Minimal(APYUSD).convertToAssets(pos.apyShares);
            assetsEst = apxValue / 1e12;
        }

        uint256 unlockAvail = pos.unlockRequestTs > 0
            ? pos.unlockRequestTs + LOCKED_COOLDOWN
            : 0;

        int256 daysLeft = -1;
        if (pos.unlockRequestTs != 0) {
            int256 remaining = int256(unlockAvail) - int256(block.timestamp);
            daysLeft = remaining > 0 ? remaining / 1 days : int256(0);
        }

        v = PositionView({
            apyShares:           pos.apyShares,
            assetsEstimateUsdc:  assetsEst,
            depositTimestamp:    pos.depositTimestamp,
            unlockRequestTs:     pos.unlockRequestTs,
            unlockAvailableTs:   unlockAvail,
            tier:                pos.tier,
            withdrawRequested:   pos.unlockRequestTs != 0,
            daysUntilUnlock:     daysLeft
        });
    }

    /**
     * @notice Total USDC-equivalent value locked across all users.
     *         Engine reads this to exclude from regular optimizer accounting.
     *         Computed from this contract's apyUSD balance → apxUSD value → USDC.
     */
    function totalLockedAssetsUsdc() external view returns (uint256) {
        uint256 apyBal = IERC20(APYUSD).balanceOf(address(this));
        if (apyBal == 0) return 0;
        uint256 apxValue = IERC4626Minimal(APYUSD).convertToAssets(apyBal);
        return apxValue / 1e12;  // apxUSD (18 dec) → USDC (6 dec)
    }

    /**
     * @notice Preview USDC value equivalent for a given deposit amount.
     *         Uses current Curve pool rate — informational only, no state changes.
     */
    function previewDeposit(uint256 usdcAmount) external view returns (uint256 estimatedApxUsdc) {
        if (curvePool == address(0) || usdcAmount == 0) return 0;
        uint256 apxOut = ICurvePool(curvePool).get_dy(curveUsdcIdx, curveApxusdIdx, usdcAmount);
        // apxUSD is 18 decimals, USDC is 6 — near-parity conversion
        return apxOut / 1e12;
    }

    /**
     * @notice Preview USDC output for redeeming a given apyUSD share amount.
     *         Uses current Curve pool rate + apyUSD exchange rate.
     */
    function previewRedeem(uint256 apyShares) external view returns (uint256 estimatedUsdc) {
        if (curvePool == address(0) || apyShares == 0) return 0;
        uint256 apxValue = IERC4626Minimal(APYUSD).convertToAssets(apyShares);
        if (apxValue == 0) return 0;
        return ICurvePool(curvePool).get_dy(curveApxusdIdx, curveUsdcIdx, apxValue);
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.