Skip to content
Verified contractPartialUNLICENSED

ShaolinStaking

Address0xc3ffe0cf66c8bf8293a84413f60b2e9a5660afa1
Balance

0 ETH

 

Transactions

167

 

Compiler

solc 0.8.27

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 200 runs
EVM version
shanghai
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
21,752,762
Creation transaction
0x16cbb034aa…030e8ab2c9
Libraries
src/utils/Time.sol:Time0x5dcd…d133d3

99 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/Staking.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.27;

import "@const/Constants.sol";
import {Time} from "@utils/Time.sol";
import {Errors} from "@utils/Errors.sol";
import {Shaolin} from "@core/Shaolin.sol";
import {IWETH9} from "@interfaces/IWETH9.sol";
import {wdiv, wmul, sub, wpow} from "@utils/Math.sol";
import {SwapActions, SwapActionParams} from "@actions/SwapActions.sol";
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ERC20Burnable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";

struct UserRecord {
    uint256 shares;
    uint256 lockedShaolin;
    uint256 rewardDebt;
    uint32 endTime;
}

/**
 * @title ShaolinStaking
 * @notice The staking contract of the Shaolin system, allowing users to stake tokens, earn rewards, and compound earnings.
 * @dev This contract implements staking using ERC721 tokens as proof of staking positions. Users can stake and earn rewards based on locked periods.
 */
contract ShaolinStaking is ERC721, SwapActions {
    using SafeERC20 for *;

    /**
     * @notice Enum to represent different staking pools with varying durations.
     */
    enum POOLS {
        DAY8, // 8-day pool
        DAY16 // 16-day pool

    }

    uint32 public constant MIN_DURATION = 88 days;
    uint32 public constant MAX_DURATION = 365 days;

    uint32 public immutable startTimestamp;

    IWETH9 public immutable weth;
    Shaolin public immutable shaolin;

    uint256 public totalShares;
    uint256 public rewardPerShare;
    uint96 public tokenId;

    uint32 public lastDistributedDay;

    mapping(POOLS => uint256) public toDistribute;
    mapping(uint256 id => UserRecord record) public userRecords;
    mapping(address user => uint256 totalShares) public userShares;

    mapping(address => bool) isBlacklisted;

    //==========ERRORS==========//
    error ShaolinStaking__InvalidDuration();
    error ShaolinStaking__NoSharesToClaim();
    error ShaolinStaking__LockPeriodNotOver();
    error ShaolinStaking__Blacklisted(address _user);
    error ShaolinStaking__OnlyMintingAndBurning();

    /**
     * @dev Emitted when a user stakes `shaolin` tokens for a specific `duration`.
     * @param staker The address of the user staking.
     * @param shaolin Amount of shaolin tokens staked.
     * @param id The staking position token ID.
     * @param _shares The number of shares obtained from the staking.
     * @param duration The duration for which the tokens are staked.
     */
    event Staked(address indexed staker, uint256 indexed shaolin, uint152 indexed id, uint256 _shares, uint32 duration);

    /**
     * @dev Emitted when a user unstakes their tokens.
     * @param shares The number of shares being unstaked.
     * @param shaolinAmountReceived The amount of shaolin tokens returned to the user.
     * @param _tokenId The staking position token ID.
     * @param recepient The address receiving the unstaked tokens.
     */
    event Unstaked(
        uint256 indexed shares, uint256 indexed shaolinAmountReceived, uint256 indexed _tokenId, address recepient
    );

    /**
     * @dev Emitted when a user claims rewards.
     * @param id The staking position token ID.
     * @param rewards The amount of rewards claimed.
     * @param newRewardDebt The updated reward debt for the staking position.
     * @param ownerOfStake The owner of the staking position.
     */
    event Claimed(uint256 indexed id, uint256 indexed rewards, uint256 indexed newRewardDebt, address ownerOfStake);

    /**
     * @dev Emitted when rewards are distributed for a pool.
     * @param pool The pool where rewards are distributed.
     * @param amount The amount of rewards distributed.
     */
    event Distributed(POOLS indexed pool, uint256 indexed amount);

    /**
     * @dev Emitted when rewards are auto compounded
     * @param newShares The additional shares received from the compounding
     * @param stakeId The stake id that had auto compounded the rewards
     * @param ownerOfStake The owner of the stake
     */
    event CompoundedRewards(uint256 indexed newShares, uint256 indexed stakeId, address indexed ownerOfStake);

    constructor(uint32 _startTimestamp, address _shaolin, address _weth, SwapActionParams memory _params)
        SwapActions(_params)
        ERC721("Staking", "STK")
    {
        startTimestamp = _startTimestamp;

        shaolin = Shaolin(_shaolin);
        weth = IWETH9(_weth);

        lastDistributedDay = 1;
    }

    modifier notBlackListed(address _user) {
        _notBlacklisted(_user);
        _;
    }

    function toggleBlackListed(address _user, bool _value) external onlyOwner {
        isBlacklisted[_user] = _value;
    }

    /**
     * @notice Allows a user to stake a certain amount of Shaolin tokens for a specific duration.
     * @param _duration The duration (in seconds) to lock the tokens for.
     * @param _shaolinAmount The amount of Shaolin tokens to stake.
     * @return _tokenId The ID of the staking position token created.
     * @return shares The number of shares granted for staking.
     */
    function stake(uint32 _duration, uint256 _shaolinAmount)
        external
        notAmount0(_shaolinAmount)
        notBlackListed(msg.sender)
        returns (uint96 _tokenId, uint256 shares)
    {
        require(
            MIN_DURATION <= _duration && _duration <= MAX_DURATION && _duration % 24 hours == 0,
            ShaolinStaking__InvalidDuration()
        );

        updateRewardsIfNecessary();

        _tokenId = ++tokenId;

        shares = convertShaolinToShares(_shaolinAmount, _duration);

        userRecords[_tokenId] = UserRecord({
            endTime: Time.blockTs() + _duration,
            shares: shares,
            rewardDebt: rewardPerShare,
            lockedShaolin: _shaolinAmount
        });

        totalShares += shares;

        userShares[msg.sender] += shares;

        emit Staked(msg.sender, _shaolinAmount, _tokenId, shares, _duration);

        shaolin.transferFrom(msg.sender, address(this), _shaolinAmount);

        _mint(msg.sender, _tokenId);
    }

    /**
     * @notice Allows a user to batch check the total claimable rewards for multiple staking positions.
     * @param _ids The array of staking position token IDs.
     * @return toClaim The total amount of claimable rewards.
     */
    function batchClaimableAmount(uint256[] calldata _ids) external view returns (uint256 toClaim) {
        uint32 currentDay = _getCurrentDay();

        uint256 m_rewardsPerShare = rewardPerShare;

        bool distributeDay8 = (currentDay / 8 > lastDistributedDay / 8);
        bool distributeDay16 = (currentDay / 16 > lastDistributedDay / 16);

        if (distributeDay8) m_rewardsPerShare += wdiv(toDistribute[POOLS.DAY8], totalShares);
        if (distributeDay16) m_rewardsPerShare += wdiv(toDistribute[POOLS.DAY16], totalShares);

        for (uint256 i; i < _ids.length; ++i) {
            uint256 _id = _ids[i];

            UserRecord memory _rec = userRecords[_id];

            toClaim += wmul(_rec.shares, m_rewardsPerShare - _rec.rewardDebt);
        }
    }

    /**
     * @notice Allows a user to unstake their tokens after the staking period has ended.
     * @param _tokenId The staking position token ID.
     * @param _receiver The address to receive the unstaked tokens.
     */
    function unstake(uint256 _tokenId, address _receiver) public notAddress0(_receiver) notAmount0(_tokenId) {
        UserRecord memory record = userRecords[_tokenId];

        require(record.shares != 0, ShaolinStaking__NoSharesToClaim());
        require(record.endTime <= Time.blockTs(), ShaolinStaking__LockPeriodNotOver());
        isApprovedOrOwner(_tokenId, msg.sender);

        address ownerOfPosition = ownerOf(_tokenId);

        _claim(_tokenId, _receiver);

        uint256 _locked = record.lockedShaolin;
        uint256 _shares = record.shares;

        delete userRecords[_tokenId];

        totalShares -= _shares;
        userShares[ownerOfPosition] -= _shares;

        emit Unstaked(_shares, _locked, _tokenId, _receiver);

        shaolin.transfer(_receiver, _locked);

        _burn(_tokenId);
    }

    function compoundRewards(uint256 _id, uint256 _amountShaolinMin, uint32 _deadline)
        external
        notExpired(_deadline)
        notBlackListed(ownerOf(_id))
    {
        updateRewardsIfNecessary();
        isApprovedOrOwner(_id, msg.sender);

        UserRecord storage _rec = userRecords[_id];

        uint256 amountToCompound = wmul(_rec.shares, rewardPerShare - _rec.rewardDebt);

        uint256 shaolinAmount =
            swapExactInput(address(weth), address(shaolin), amountToCompound, _amountShaolinMin, POOL_FEE, _deadline);

        _rec.rewardDebt = rewardPerShare;
        _rec.lockedShaolin += uint256(shaolinAmount);
        _rec.shares += uint256(shaolinAmount);

        address _ownerOfPosition = ownerOf(_id);

        userShares[_ownerOfPosition] += shaolinAmount;

        totalShares += shaolinAmount;

        emit CompoundedRewards(shaolinAmount, _id, ownerOf(_id));
    }

    function convertShaolinToShares(uint256 _amount, uint32 _duration) public pure returns (uint256 shares) {
        shares = _amount;

        shares += uint256(
            wmul(
                uint256(_amount),
                _stakingBonus(
                    _duration, MIN_DURATION, MAX_DURATION, STAKING_ERANK_MINIMUM_BONUS, STAKING_ERANK_MAXIMUM_BONUS
                )
            )
        );
    }

    // Generic function to calculate the linear interpolation
    function _stakingBonus(
        uint32 _duration,
        uint32 _lowerBoundDays,
        uint32 _upperBoundDays,
        uint256 _lowerMultiplier,
        uint256 _upperMultiplier
    ) private pure returns (uint256) {
        return _lowerMultiplier
            + (_duration - _lowerBoundDays) * (_upperMultiplier - _lowerMultiplier) / (_upperBoundDays - _lowerBoundDays);
    }

    /**
     * @notice Allows batch unstaking of multiple staking positions.
     * @param _ids Array of staking position token IDs.
     * @param _receiver Address to receive the unstaked tokens.
     */
    function batchUnstake(uint256[] calldata _ids, address _receiver) external {
        for (uint256 i; i < _ids.length; ++i) {
            unstake(_ids[i], _receiver);
        }
    }

    /**
     * @notice Allows a user to claim their staking rewards.
     * @param _tokenId The staking position token ID.
     * @param _receiver The address to receive the rewards.
     */
    function claim(uint256 _tokenId, address _receiver) public notAddress0(_receiver) notAmount0(_tokenId) {
        isApprovedOrOwner(_tokenId, msg.sender);
        _claim(_tokenId, _receiver);
    }

    /**
     * @notice Batch claim rewards for multiple staking positions.
     * @param _ids Array of staking position token IDs.
     * @param _receiver Address to receive the claimed rewards.
     */
    function batchClaim(uint256[] calldata _ids, address _receiver) external {
        for (uint256 i; i < _ids.length; ++i) {
            claim(_ids[i], _receiver);
        }
    }

    /**
     * @notice Checks if the user is authorized to operate on a given token.
     * @param _tokenId The staking position token ID.
     * @param _spender The address to check.
     */
    function isApprovedOrOwner(uint256 _tokenId, address _spender) public view {
        _checkAuthorized(ownerOf(_tokenId), _spender, _tokenId);
    }

    /**
     * @notice Distributes rewards into the staking pools.
     * @param _amount The amount of rewards to distribute.
     */
    function distribute(uint256 _amount) external notAmount0(_amount) {
        _distribute(_amount);
    }

    function distributeToSpecificPool(POOLS _pool, uint256 _amount) external notAmount0(_amount) {
        updateRewardsIfNecessary();

        weth.safeTransferFrom(msg.sender, address(this), _amount);
        toDistribute[_pool] += _amount;
    }

    /**
     * @notice Updates the staking rewards if necessary.
     */
    function updateRewardsIfNecessary() public {
        if (totalShares == 0) return;

        uint32 currentDay = _getCurrentDay();

        bool distributeDay8 = (currentDay / 8 > lastDistributedDay / 8);
        bool distributeDay16 = (currentDay / 16 > lastDistributedDay / 16);

        if (distributeDay8) _updateRewards(POOLS.DAY8, toDistribute);
        if (distributeDay16) _updateRewards(POOLS.DAY16, toDistribute);

        lastDistributedDay = currentDay;
    }

    /**
     * @dev Internal function to claim rewards for a staking position.
     * @param _tokenId The staking position token ID.
     * @param _receiver The address to receive the rewards.
     */
    function _claim(uint256 _tokenId, address _receiver) internal {
        UserRecord storage _rec = userRecords[_tokenId];
        updateRewardsIfNecessary();

        uint256 amountToClaim = wmul(_rec.shares, rewardPerShare - _rec.rewardDebt);
        _rec.rewardDebt = rewardPerShare;

        emit Claimed(_tokenId, amountToClaim, rewardPerShare, ownerOf(_tokenId));

        weth.transfer(_receiver, amountToClaim);
    }

    /**
     * @dev Internal function to distribute rewards into pools.
     * @param amount The amount of rewards to distribute.
     */
    function _distribute(uint256 amount) internal {
        updateRewardsIfNecessary();

        toDistribute[POOLS.DAY8] += wmul(amount, DAY8POOL_DIST);
        toDistribute[POOLS.DAY16] += wmul(amount, DAY16POOL_DIST);

        weth.safeTransferFrom(msg.sender, address(this), amount);
    }

    /**
     * @dev Internal function to update rewards for a given pool.
     * @param pool The pool being updated.
     * @param toDist A reference to the mapping of distributions.
     */
    function _updateRewards(POOLS pool, mapping(POOLS => uint256) storage toDist) internal {
        if (toDist[pool] == 0) return;

        rewardPerShare += wdiv(toDist[pool], totalShares);

        emit Distributed(pool, toDist[pool]);
        toDistribute[pool] = 0;
    }

    /**
     * @dev Returns the current day since the contract started.
     * @return currentDay The current day.
     */
    function _getCurrentDay() internal view returns (uint32 currentDay) {
        if (startTimestamp > Time.blockTs()) return 1;
        currentDay = Time.dayGap(startTimestamp, Time.blockTs()) + 1;
    }

    function _notBlacklisted(address _user) internal view {
        require(!isBlacklisted[_user], ShaolinStaking__Blacklisted(_user));
    }

    /**
     * @dev Overrides the _update function from ERC721 to restrict token transfers.
     * @param to The address to update the ownership to.
     * @param _id The ID of the token.
     * @param auth The authorized address for the update.
     * @return The address of the token's previous owner.
     */
    function _update(address to, uint256 _id, address auth) internal override returns (address) {
        address from = _ownerOf(_id);
        require(from == address(0) || to == address(0), ShaolinStaking__OnlyMintingAndBurning());
        return super._update(to, _id, auth);
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {
    "src/utils/Time.sol": {
      "Time": "0x5dcd2315a462f0046641b2118e106fbb47d133d3"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": [
    ":@actions/=src/actions/",
    ":@chainlink/=lib/chainlink/",
    ":@const/=src/const/",
    ":@core/=src/",
    ":@interfaces/=src/interfaces/",
    ":@layerzerolabs/lz-evm-protocol-v2/=lib/layerzero-v2/packages/layerzero-v2/evm/protocol/",
    ":@layerzerolabs/oapp-evm/=lib/devtools/packages/oapp-evm/",
    ":@layerzerolabs/oft-evm/=lib/devtools/packages/oft-evm/",
    ":@libs/=src/libs/",
    ":@murky/=lib/murky/src/",
    ":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    ":@script/=script/",
    ":@uniswap/v2-core/=lib/v2-core/",
    ":@uniswap/v2-periphery/=lib/v2-periphery/",
    ":@uniswap/v3-core/=lib/v3-core/",
    ":@uniswap/v3-periphery/=lib/v3-periphery/",
    ":@utils/=src/utils/",
    ":chainlink/=lib/chainlink/",
    ":devtools/=lib/devtools/packages/toolbox-foundry/src/",
    ":ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    ":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    ":forge-std/=lib/forge-std/src/",
    ":halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    ":layerzero-v2/=lib/layerzero-v2/",
    ":openzeppelin-contracts/=lib/openzeppelin-contracts/",
    ":v3-core/=lib/v3-core/contracts/",
    ":v3-periphery/=lib/v3-periphery/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.