Skip to content
Verified contractExactMIT

TycoonVault

Address0xe51fe14c67000f876dce850f6cc231ca75e8ab8a
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,472,929
Creation transaction
0xbfbdd7806c…cb974179ab

src/TycoonVault.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import {ERC20} from "solmate/tokens/ERC20.sol";

/// @title TycoonVault (tycETH)
/// @notice Deposit-side of Tycoon. Takes native ETH, mints non-rebasing shares,
///         lends principal to node operators and books their rewards.
///
/// Accounting invariant:
///     totalAssets() == idle + deployed - reserved
///
///   idle      ETH sitting in this contract
///   deployed  principal lent out to active nodes (held in validators)
///   reserved  assets already owed to the exit queue (shares burnt, ETH not yet paid)
///
/// Exits are queued, not instant beyond the idle buffer. That is not a
/// shortcut -- beacon-chain exits take real time, and pretending otherwise is
/// how LSTs end up insolvent under redemption pressure.
contract TycoonVault is ERC20 {
    /* ----------------------------------------------------------------- */
    /*                              errors                               */
    /* ----------------------------------------------------------------- */

    error NotOwner();
    error NotPendingOwner();
    error ZeroAddress();
    error NotNodes();
    error NodesAlreadySet();
    error ZeroAmount();
    error BelowSeedMinimum();
    error InsufficientLiquidity();
    error NotFinalized();
    error AlreadyClaimed();
    error NotRequestOwner();
    error FeeTooHigh();

    /* ----------------------------------------------------------------- */
    /*                              events                               */
    /* ----------------------------------------------------------------- */

    event OwnershipTransferStarted(address indexed from, address indexed to);
    event OwnershipTransferred(address indexed from, address indexed to);
    event Deposit(address indexed caller, uint256 assets, uint256 shares);
    event WithdrawalRequested(uint256 indexed id, address indexed owner, uint256 shares, uint256 assets);
    event WithdrawalFinalized(uint256 indexed upTo);
    event WithdrawalClaimed(uint256 indexed id, address indexed owner, uint256 assets);
    event Borrowed(address indexed to, uint256 amount);
    event PrincipalRepaid(uint256 amount, uint256 surplusAsRewards);
    event RewardsCredited(uint256 toDepositors, uint256 toTreasury);
    event LossAbsorbed(uint256 amount);

    /* ----------------------------------------------------------------- */
    /*                             constants                             */
    /* ----------------------------------------------------------------- */

    /// @dev Permanently locked shares minted on the first deposit. Blocks the
    ///      donation/rounding inflation attack on an empty vault.
    uint256 public constant SEED_SHARES = 1e15;
    uint256 public constant SEED_MINIMUM = 1 ether;

    uint16 public constant MAX_PROTOCOL_FEE_BPS = 1000; // 10% ceiling, hard-coded
    uint8 internal constant AUTO_FINALIZE_STEPS = 8;

    /* ----------------------------------------------------------------- */
    /*                              storage                              */
    /* ----------------------------------------------------------------- */

    address public owner;
    address public pendingOwner;
    address public nodes;
    address public treasury;
    /// @dev Defaults to zero on purpose. Any protocol fee is taken straight out
    ///      of the depositor reward stream, on top of the node commission, and
    ///      a 14% commission already puts tycETH behind Lido's 10%. Turning
    ///      this on has a direct, measurable cost to depositors.
    uint16 public protocolFeeBps = 0;

    uint256 public idle;
    uint256 public deployed;
    uint256 public reserved;

    struct ExitRequest {
        address owner;
        uint256 assets;
        uint64 requestedAt;
        bool claimed;
    }

    ExitRequest[] public queue;
    uint256 public finalizedUpTo; // queue index; requests below this are payable
    uint256 public finalizedAssets; // idle ETH committed to finalized requests

    /* ----------------------------------------------------------------- */
    /*                            constructor                            */
    /* ----------------------------------------------------------------- */

    constructor(address _owner, address _treasury) ERC20("Tycoon Staked ETH", "tycETH", 18) {
        owner = _owner;
        treasury = _treasury;
    }

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    modifier onlyNodes() {
        if (msg.sender != nodes) revert NotNodes();
        _;
    }


    /* ----------------------------------------------------------------- */
    /*                            ownership                              */
    /* ----------------------------------------------------------------- */

    /// @notice Two-step handover. The deployer wires the system up, then hands
    ///         it to the real owner, who must accept. Two steps because a
    ///         mistyped address in a single-step transfer is unrecoverable.
    function transferOwnership(address to) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        pendingOwner = to;
        emit OwnershipTransferStarted(owner, to);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotPendingOwner();
        emit OwnershipTransferred(owner, pendingOwner);
        owner = pendingOwner;
        pendingOwner = address(0);
    }

    function setNodes(address _nodes) external onlyOwner {
        if (nodes != address(0)) revert NodesAlreadySet();
        nodes = _nodes;
    }

    function setTreasury(address _treasury) external onlyOwner {
        treasury = _treasury;
    }

    function setProtocolFeeBps(uint16 bps) external onlyOwner {
        if (bps > MAX_PROTOCOL_FEE_BPS) revert FeeTooHigh();
        protocolFeeBps = bps;
    }

    /* ----------------------------------------------------------------- */
    /*                            accounting                             */
    /* ----------------------------------------------------------------- */

    function totalAssets() public view returns (uint256) {
        return idle + deployed - reserved;
    }

    /// @notice ETH that can be lent to a new node right now.
    function availableToBorrow() public view returns (uint256) {
        return idle > reserved ? idle - reserved : 0;
    }

    function convertToShares(uint256 assets) public view returns (uint256) {
        uint256 supply = totalSupply;
        uint256 assets_ = totalAssets();
        if (supply == 0 || assets_ == 0) return assets;
        return (assets * supply) / assets_;
    }

    function convertToAssets(uint256 shares) public view returns (uint256) {
        uint256 supply = totalSupply;
        if (supply == 0) return shares;
        return (shares * totalAssets()) / supply;
    }

    /// @notice ETH backing one whole tycETH. Rises as rewards land.
    function pricePerShare() external view returns (uint256) {
        return convertToAssets(1e18);
    }

    /* ----------------------------------------------------------------- */
    /*                           depositor path                          */
    /* ----------------------------------------------------------------- */

    function deposit() external payable returns (uint256 shares) {
        if (msg.value == 0) revert ZeroAmount();

        if (totalSupply == 0) {
            if (msg.value < SEED_MINIMUM) revert BelowSeedMinimum();
            _mint(address(0), SEED_SHARES); // locked forever
            shares = msg.value - SEED_SHARES;
        } else {
            shares = convertToShares(msg.value);
            if (shares == 0) revert ZeroAmount();
        }

        idle += msg.value;
        _mint(msg.sender, shares);
        emit Deposit(msg.sender, msg.value, shares);

        _finalize(AUTO_FINALIZE_STEPS);
    }

    /// @notice Burn shares and join the exit queue.
    function requestWithdrawal(uint256 shares) external returns (uint256 id) {
        if (shares == 0) revert ZeroAmount();
        uint256 assets = convertToAssets(shares);
        if (assets == 0) revert ZeroAmount();

        _burn(msg.sender, shares);
        reserved += assets;

        id = queue.length;
        queue.push(
            ExitRequest({
                owner: msg.sender, assets: assets, requestedAt: uint64(block.timestamp), claimed: false
            })
        );
        emit WithdrawalRequested(id, msg.sender, shares, assets);

        _finalize(AUTO_FINALIZE_STEPS);
    }

    /// @notice Walk the queue in strict FIFO order, marking requests payable
    ///         while uncommitted idle ETH covers them.
    function finalize(uint256 maxSteps) external {
        _finalize(maxSteps);
    }

    function _finalize(uint256 maxSteps) internal {
        uint256 i = finalizedUpTo;
        uint256 len = queue.length;
        if (i >= len) return;

        uint256 free = idle > finalizedAssets ? idle - finalizedAssets : 0;
        uint256 end = i + maxSteps;
        if (end > len) end = len;

        uint256 committed;
        while (i < end) {
            uint256 a = queue[i].assets;
            if (a > free) break;
            free -= a;
            committed += a;
            i++;
        }

        if (i != finalizedUpTo) {
            finalizedAssets += committed;
            finalizedUpTo = i;
            emit WithdrawalFinalized(i);
        }
    }

    function claimWithdrawal(uint256 id) external {
        ExitRequest storage r = queue[id];
        if (id >= finalizedUpTo) revert NotFinalized();
        if (r.claimed) revert AlreadyClaimed();
        if (msg.sender != r.owner) revert NotRequestOwner();

        uint256 assets = r.assets;
        r.claimed = true;
        idle -= assets;
        reserved -= assets;
        finalizedAssets -= assets;

        emit WithdrawalClaimed(id, r.owner, assets);
        _send(r.owner, assets);
    }

    function queueLength() external view returns (uint256) {
        return queue.length;
    }

    /* ----------------------------------------------------------------- */
    /*                             node path                             */
    /* ----------------------------------------------------------------- */

    /// @notice Lend principal to a node being activated.
    function borrow(uint256 amount, address to) external onlyNodes {
        if (amount == 0) revert ZeroAmount();
        if (amount > availableToBorrow()) revert InsufficientLiquidity();
        idle -= amount;
        deployed += amount;
        emit Borrowed(to, amount);
        _send(to, amount);
    }

    /// @notice Return principal on node exit. Anything over the outstanding
    ///         principal is booked as reward.
    function repayPrincipal(uint256 principal) external payable onlyNodes {
        uint256 p = principal > deployed ? deployed : principal;
        uint256 surplus = msg.value > p ? msg.value - p : 0;

        deployed -= p;
        idle += msg.value;

        emit PrincipalRepaid(p, surplus);
        if (surplus > 0) _takeFee(surplus);

        _finalize(AUTO_FINALIZE_STEPS);
    }

    /// @notice Book the depositor-side slice of a node's rewards.
    function creditRewards() external payable onlyNodes {
        if (msg.value == 0) revert ZeroAmount();
        idle += msg.value;
        _takeFee(msg.value);
        _finalize(AUTO_FINALIZE_STEPS);
    }

    /// @notice Write down principal after a node loss has exhausted its bond.
    function absorbLoss(uint256 amount) external onlyNodes {
        uint256 a = amount > deployed ? deployed : amount;
        deployed -= a;
        emit LossAbsorbed(a);
    }

    /// @dev Protocol fee is taken by sending ETH out of `idle`, which lowers
    ///      totalAssets -- depositors keep the remainder via a higher share price.
    function _takeFee(uint256 rewardAmount) internal {
        uint256 fee = (rewardAmount * protocolFeeBps) / 10_000;
        if (fee > 0 && treasury != address(0)) {
            idle -= fee;
            _send(treasury, fee);
        }
        emit RewardsCredited(rewardAmount - fee, fee);
    }

    function _send(address to, uint256 amount) internal {
        (bool ok,) = to.call{value: amount}("");
        require(ok, "TycoonVault: ETH transfer failed");
    }
}

lib/solmate/src/tokens/ERC20.sol

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Transfer(address indexed from, address indexed to, uint256 amount);

    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "solmate/=lib/solmate/src/",
    "forge-std/=lib/forge-std/src/",
    "ds-test/=lib/solmate/lib/ds-test/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.