Skip to content
Verified contractExactMIT

HStaking

Address0x53d67a88d25d5cabf4d2ea78e8a504084b75ccfe
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,065,597
Creation transaction
0x8b454deeb2…253ef646ee

src/HStaking.sol

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

import {Ownable} from "solady/src/auth/Ownable.sol";

interface IHTokenMint {
    function balanceOf(address) external view returns (uint256);
    function transfer(address, uint256) external returns (bool);
    function transferFrom(address, address, uint256) external returns (bool);
}

/// @title HStaking — fixed-APR epoch staking for $H
/// @notice Internal accounting only (no separate sH ERC-20). Rewards come
///         from H minted by the Hook on every rebase tick. APR is configured
///         by the Hook (which is the protocol's policy contract).
contract HStaking is Ownable {

    // ── Constants ───────────────────────────────────────────────────────────
    uint256 public constant EPOCH_DURATION  = 8 hours;
    uint256 public constant EPOCHS_PER_YEAR = 1_095;
    uint256 public constant BPS_DENOMINATOR = 10_000;
    uint256 public constant MAX_EPOCHS_LAG  = 30;
    uint256 public constant PRECISION       = 1e36;
    uint256 public constant MAX_APR_BPS     = 50_000; // 500% hard ceiling

    // ── State ───────────────────────────────────────────────────────────────
    IHTokenMint public immutable hToken;
    address     public hook;

    uint256 public aprBps = 1_500;          // 15% default
    uint256 public accRewardPerShare;
    uint256 public totalStaked;
    uint256 public lastDistributedEpoch;

    struct StakeInfo {
        uint256 amount;
        uint256 rewardDebt;
    }
    mapping(address => StakeInfo) public stakers;

    // ── Reentrancy guard (compact) ──────────────────────────────────────────
    uint256 private _locked = 1;
    modifier nonReentrant() {
        require(_locked == 1, "reentrant");
        _locked = 2;
        _;
        _locked = 1;
    }

    // ── Events ──────────────────────────────────────────────────────────────
    event HookSet(address indexed hook);
    event AprUpdated(uint256 oldBps, uint256 newBps);
    event Staked(address indexed user, uint256 amount, uint256 totalStaked);
    event Unstaked(address indexed user, uint256 amount, uint256 totalStaked);
    event RewardClaimed(address indexed user, uint256 amount);
    event EpochDistributed(uint256 indexed epoch, uint256 reward);
    event EmergencyWithdraw(address indexed user, uint256 amount);

    // ── Constructor ─────────────────────────────────────────────────────────
    constructor(address _hToken, address owner_) {
        require(_hToken != address(0), "zero token");
        _initializeOwner(owner_);
        hToken               = IHTokenMint(_hToken);
        lastDistributedEpoch = block.timestamp / EPOCH_DURATION;
    }

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

    function setHook(address newHook) external onlyOwner {
        require(newHook != address(0), "zero hook");
        require(hook == address(0), "hook already set");
        hook = newHook;
        emit HookSet(newHook);
    }

    /// @notice Adjust APR. Owner-or-hook controlled (so the Hook policy can
    ///         dial APR up/down based on treasury surplus, OHM-style).
    function setAprBps(uint256 _aprBps) external {
        require(msg.sender == owner() || msg.sender == hook, "not authorized");
        require(_aprBps <= MAX_APR_BPS, "apr > max");
        emit AprUpdated(aprBps, _aprBps);
        aprBps = _aprBps;
    }

    // ── Epoch helpers ───────────────────────────────────────────────────────

    function currentEpoch() public view returns (uint256) {
        return block.timestamp / EPOCH_DURATION;
    }

    function epochReward() public view returns (uint256) {
        if (totalStaked == 0) return 0;
        return (totalStaked * aprBps) / BPS_DENOMINATOR / EPOCHS_PER_YEAR;
    }

    // ── Distribution: must be funded by the Hook minting H to this contract ─
    // ── before any epoch boundary is crossed. If reserve runs out, rewards   ─
    // ── are capped to whatever is currently in the contract above principal. ─

    function _distributeCompletedEpochs() internal {
        uint256 epoch = currentEpoch();
        if (epoch <= lastDistributedEpoch) return;
        if (totalStaked == 0) {
            lastDistributedEpoch = epoch;
            return;
        }

        uint256 lastCompleted = epoch - 1;
        if (lastCompleted <= lastDistributedEpoch) return;

        uint256 fromEpoch = lastDistributedEpoch + 1;
        uint256 toEpoch   = lastCompleted;
        if (toEpoch - fromEpoch + 1 > MAX_EPOCHS_LAG) {
            fromEpoch = toEpoch - MAX_EPOCHS_LAG + 1;
        }

        uint256 epochCount     = toEpoch - fromEpoch + 1;
        uint256 rewardPerEpoch = (totalStaked * aprBps) / BPS_DENOMINATOR / EPOCHS_PER_YEAR;
        uint256 totalReward    = rewardPerEpoch * epochCount;

        // Cap to the H reserve actually held above principal (Hook may not
        // have minted enough yet — that's fine, we just under-distribute).
        uint256 reserve = hToken.balanceOf(address(this)) - totalStaked;
        if (totalReward > reserve) totalReward = reserve;

        if (totalReward > 0) {
            accRewardPerShare += (totalReward * PRECISION) / totalStaked;
            emit EpochDistributed(lastCompleted, totalReward);
        }
        lastDistributedEpoch = lastCompleted;
    }

    function _pendingReward(address user) internal view returns (uint256) {
        StakeInfo storage s = stakers[user];
        if (s.amount == 0) return 0;

        uint256 _acc  = accRewardPerShare;
        uint256 epoch = currentEpoch();

        if (totalStaked > 0 && epoch > lastDistributedEpoch) {
            uint256 lastCompleted = epoch - 1;
            if (lastCompleted > lastDistributedEpoch) {
                uint256 fromEpoch = lastDistributedEpoch + 1;
                uint256 toEpoch   = lastCompleted;
                if (toEpoch - fromEpoch + 1 > MAX_EPOCHS_LAG) {
                    fromEpoch = toEpoch - MAX_EPOCHS_LAG + 1;
                }
                uint256 epochCount     = toEpoch - fromEpoch + 1;
                uint256 rewardPerEpoch = (totalStaked * aprBps) / BPS_DENOMINATOR / EPOCHS_PER_YEAR;
                uint256 simReward      = rewardPerEpoch * epochCount;
                uint256 reserve        = hToken.balanceOf(address(this)) - totalStaked;
                if (simReward > reserve) simReward = reserve;
                if (simReward > 0) {
                    _acc += (simReward * PRECISION) / totalStaked;
                }
            }
        }

        uint256 gross = (s.amount * _acc) / PRECISION;
        return gross > s.rewardDebt ? gross - s.rewardDebt : 0;
    }

    function _deliverReward(address to, uint256 amount) internal {
        uint256 reserve = hToken.balanceOf(address(this)) - totalStaked;
        uint256 send    = amount > reserve ? reserve : amount;
        if (send > 0) {
            hToken.transfer(to, send);
            emit RewardClaimed(to, send);
        }
    }

    // ── User actions ────────────────────────────────────────────────────────

    function stake(uint256 amount) external nonReentrant {
        require(amount > 0, "zero amount");
        _distributeCompletedEpochs();

        StakeInfo storage s = stakers[msg.sender];
        if (s.amount > 0) {
            uint256 pending = (s.amount * accRewardPerShare) / PRECISION - s.rewardDebt;
            if (pending > 0) _deliverReward(msg.sender, pending);
        }

        require(hToken.transferFrom(msg.sender, address(this), amount), "transferFrom failed");
        s.amount    += amount;
        totalStaked += amount;
        s.rewardDebt = (s.amount * accRewardPerShare) / PRECISION;

        emit Staked(msg.sender, amount, totalStaked);
    }

    function unstake(uint256 amount) external nonReentrant {
        StakeInfo storage s = stakers[msg.sender];
        require(s.amount >= amount && amount > 0, "invalid amount");
        _distributeCompletedEpochs();

        uint256 pending = (s.amount * accRewardPerShare) / PRECISION - s.rewardDebt;
        if (pending > 0) _deliverReward(msg.sender, pending);

        s.amount    -= amount;
        totalStaked -= amount;
        s.rewardDebt = (s.amount * accRewardPerShare) / PRECISION;

        require(hToken.transfer(msg.sender, amount), "transfer failed");
        emit Unstaked(msg.sender, amount, totalStaked);
    }

    function claim() external nonReentrant {
        StakeInfo storage s = stakers[msg.sender];
        require(s.amount > 0, "nothing staked");
        _distributeCompletedEpochs();

        uint256 pending = (s.amount * accRewardPerShare) / PRECISION - s.rewardDebt;
        require(pending > 0, "nothing to claim");

        s.rewardDebt = (s.amount * accRewardPerShare) / PRECISION;
        _deliverReward(msg.sender, pending);
    }

    function emergencyWithdraw() external nonReentrant {
        StakeInfo storage s = stakers[msg.sender];
        uint256 amount = s.amount;
        require(amount > 0, "nothing staked");

        totalStaked -= amount;
        s.amount     = 0;
        s.rewardDebt = 0;

        require(hToken.transfer(msg.sender, amount), "transfer failed");
        emit EmergencyWithdraw(msg.sender, amount);
    }

    // ── Views ───────────────────────────────────────────────────────────────

    function pendingReward(address user) external view returns (uint256) {
        return _pendingReward(user);
    }

    function stakedBalance(address user) external view returns (uint256) {
        return stakers[user].amount;
    }
}

lib/solady/src/auth/Ownable.sol

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

/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The caller is not authorized to call the function.
    error Unauthorized();

    /// @dev The `newOwner` cannot be the zero address.
    error NewOwnerIsZeroAddress();

    /// @dev The `pendingOwner` does not have a valid handover request.
    error NoHandoverRequest();

    /// @dev Cannot double-initialize.
    error AlreadyInitialized();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ownership is transferred from `oldOwner` to `newOwner`.
    /// This event is intentionally kept the same as OpenZeppelin's Ownable to be
    /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
    /// despite it not being as lightweight as a single argument event.
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);

    /// @dev An ownership handover to `pendingOwner` has been requested.
    event OwnershipHandoverRequested(address indexed pendingOwner);

    /// @dev The ownership handover to `pendingOwner` has been canceled.
    event OwnershipHandoverCanceled(address indexed pendingOwner);

    /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
    uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
        0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;

    /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
        0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;

    /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
        0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The owner slot is given by:
    /// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
    /// It is intentionally chosen to be a high value
    /// to avoid collision with lower slots.
    /// The choice of manual storage layout is to enable compatibility
    /// with both regular and upgradeable contracts.
    bytes32 internal constant _OWNER_SLOT =
        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;

    /// The ownership handover slot of `newOwner` is given by:
    /// ```
    ///     mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
    ///     let handoverSlot := keccak256(0x00, 0x20)
    /// ```
    /// It stores the expiry timestamp of the two-step ownership handover.
    uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     INTERNAL FUNCTIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
    function _guardInitializeOwner() internal pure virtual returns (bool guard) {}

    /// @dev Initializes the owner directly without authorization guard.
    /// This function must be called upon initialization,
    /// regardless of whether the contract is upgradeable or not.
    /// This is to enable generalization to both regular and upgradeable contracts,
    /// and to save gas in case the initial owner is not the caller.
    /// For performance reasons, this function will not check if there
    /// is an existing owner.
    function _initializeOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                if sload(ownerSlot) {
                    mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
                    revert(0x1c, 0x04)
                }
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(_OWNER_SLOT, newOwner)
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        }
    }

    /// @dev Sets the owner directly without authorization guard.
    function _setOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, newOwner)
            }
        }
    }

    /// @dev Throws if the sender is not the owner.
    function _checkOwner() internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // If the caller is not the stored owner, revert.
            if iszero(eq(caller(), sload(_OWNER_SLOT))) {
                mstore(0x00, 0x82b42900) // `Unauthorized()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Returns how long a two-step ownership handover is valid for in seconds.
    /// Override to return a different value if needed.
    /// Made internal to conserve bytecode. Wrap it in a public function if needed.
    function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
        return 48 * 3600;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  PUBLIC UPDATE FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Allows the owner to transfer the ownership to `newOwner`.
    function transferOwnership(address newOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(shl(96, newOwner)) {
                mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
                revert(0x1c, 0x04)
            }
        }
        _setOwner(newOwner);
    }

    /// @dev Allows the owner to renounce their ownership.
    function renounceOwnership() public payable virtual onlyOwner {
        _setOwner(address(0));
    }

    /// @dev Request a two-step ownership handover to the caller.
    /// The request will automatically expire in 48 hours (172800 seconds) by default.
    function requestOwnershipHandover() public payable virtual {
        unchecked {
            uint256 expires = block.timestamp + _ownershipHandoverValidFor();
            /// @solidity memory-safe-assembly
            assembly {
                // Compute and set the handover slot to `expires`.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, caller())
                sstore(keccak256(0x0c, 0x20), expires)
                // Emit the {OwnershipHandoverRequested} event.
                log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
            }
        }
    }

    /// @dev Cancels the two-step ownership handover to the caller, if any.
    function cancelOwnershipHandover() public payable virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x20), 0)
            // Emit the {OwnershipHandoverCanceled} event.
            log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
        }
    }

    /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
    /// Reverts if there is no existing ownership handover requested by `pendingOwner`.
    function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            let handoverSlot := keccak256(0x0c, 0x20)
            // If the handover does not exist, or has expired.
            if gt(timestamp(), sload(handoverSlot)) {
                mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
                revert(0x1c, 0x04)
            }
            // Set the handover slot to 0.
            sstore(handoverSlot, 0)
        }
        _setOwner(pendingOwner);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   PUBLIC READ FUNCTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the owner of the contract.
    function owner() public view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(_OWNER_SLOT)
        }
    }

    /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
    function ownershipHandoverExpiresAt(address pendingOwner)
        public
        view
        virtual
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the handover slot.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            // Load the handover slot.
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         MODIFIERS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Marks a function as only callable by the owner.
    modifier onlyOwner() virtual {
        _checkOwner();
        _;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "solady/=lib/solady/",
    "forge-std/=lib/forge-std/src/",
    "v4-core/=lib/v4-core/src/",
    "@ensdomains/=/Users/pro/uvault-contracts/lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=/Users/pro/uvault-contracts/lib/v4-core/lib/openzeppelin-contracts/",
    "ds-test/=/Users/pro/uvault-contracts/lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=/Users/pro/uvault-contracts/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "hardhat/=/Users/pro/uvault-contracts/lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=/Users/pro/uvault-contracts/lib/v4-core/lib/openzeppelin-contracts/",
    "solmate/=/Users/pro/uvault-contracts/lib/v4-core/lib/solmate/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.