HYMStaking

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "@openzeppelin/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
"
    },
    "@openzeppelin/contracts/access/Ownable2Step.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.0;

import "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
        _transferOwnership(sender);
    }
}
"
    },
    "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
"
    },
    "@openzeppelin/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
"
    },
    "contracts/HYMStaking.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

/**
* @title HYMStaking - HYM token staking contract with annual reward
* @dev Allows users to lock HYM and receive rewards proportional to time
* @notice Fixes implemented:
* - StartTime corrected for new deposits
* - Rewards claim logic corrected
* - Prepared for Gnosis Safe
* - Better control of accumulated rewards
 */

import '@openzeppelin/contracts/access/Ownable2Step.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';

contract HYMStaking is Ownable2Step, ReentrancyGuard {
    // --- Timelock for Gnosis Safe ---
    address public timelock;
    event TimelockSet(address indexed oldTimelock, address indexed newTimelock);
  
    modifier onlyGov() { 
        require(msg.sender == owner() || msg.sender == timelock, 'Only owner/timelock'); 
        _; 
    }

    function setTimelock(address newTimelock) public onlyOwner {
        emit TimelockSet(timelock, newTimelock);
        timelock = newTimelock;
    }

    // --- Contract Settings ---
    address public vaultAddress;
    IERC20 public immutable hymToken;

    uint256 public rewardRate = 50000; // 5% per year (base 1.000.000)
    uint256 public constant REWARD_DENOMINATOR = 1_000_000;
    uint256 public minimumStake = 10_000 * 1e18;
    uint256 public stakingPeriodForNoFee = 30 days;

    // --- Staking structure ---
    struct StakeInfo {
        uint256 amount;
        uint256 startTime;
        uint256 lastClaimTime; // controls last claim
        uint256 totalClaimed; // total claimed
    }

    mapping(address => StakeInfo) public stakes;

    // --- Events ---
    event Staked(address indexed user, uint256 amount);
    event Unstaked(address indexed user, uint256 amount, uint256 reward);
    event RewardClaimed(address indexed user, uint256 amount);
    event RewardRateUpdated(uint256 newRate);
    event MinimumStakeUpdated(uint256 newAmount);
    event StakingPeriodUpdated(uint256 newPeriod);
    event RewardForfeited(address indexed user, uint256 amount);
    event VaultFunded(uint256 amount);
    event RewardDistributed(address indexed user, uint256 amount);


    /**
* @dev Constructor for the HYMStaking contract.
* @param _hymToken Address of the HYM token.
* @param _vaultAddress Address of the vault.
     */
    constructor(address _hymToken, address _vaultAddress) Ownable2Step() {
        require(_hymToken != address(0), 'Token HYM invalid');
        require(_vaultAddress != address(0), 'Vault address invalid');

        hymToken = IERC20(_hymToken);
        vaultAddress = _vaultAddress;
    }

    /**
        * @notice Allows a user to stake HYM tokens
        * @param amount The amount of tokens to be staked.
     */
    function stake(uint256 amount) external nonReentrant {
        require(amount >= minimumStake, 'Value below minimum');
        require(hymToken.transferFrom(msg.sender, address(this), amount), 'Transfer failed');

        StakeInfo storage info = stakes[msg.sender];

        // Claim pending rewards before adding new stake
        if (info.amount > 0) {
            uint256 pendingReward = _calculatePendingReward(msg.sender);
            if (pendingReward > 0) {
                info.totalClaimed += pendingReward;
                require(hymToken.transfer(msg.sender, pendingReward), "Reward transfer failed");
                emit RewardClaimed(msg.sender, pendingReward);
            }
        }

        // Update startTime and lastClaimTime for new period
        if (info.amount == 0) {
            // First stake
            info.startTime = block.timestamp;
            info.lastClaimTime = block.timestamp;
            info.totalClaimed = 0;
        } else {
            // Additional stake - restart period for entire amount
            info.startTime = block.timestamp;
            info.lastClaimTime = block.timestamp;
        }

        info.amount += amount;

        emit Staked(msg.sender, amount);
    }

    /**
     * @notice Allows a user to unstake their staked tokens and claim rewards
     */
    function unstake() external nonReentrant {
        StakeInfo storage info = stakes[msg.sender];
        require(info.amount > 0, "Nothing in staking");

        uint256 timeStaked = block.timestamp - info.startTime;
        uint256 pendingReward = _calculatePendingReward(msg.sender);
        uint256 amountToTransfer = info.amount;

        // Clears user stake
        info.amount = 0;
        info.startTime = 0;
        info.lastClaimTime = 0;
        info.totalClaimed = 0;

        // Checks if the user has completed the minimum time to receive rewards
        if (timeStaked < stakingPeriodForNoFee && pendingReward > 0) {
            // Reward is redirected to the vault (penalty)
            require(
                hymToken.transfer(vaultAddress, pendingReward),
                "Failed to redirect forfeited reward"
            );
            emit RewardForfeited(msg.sender, pendingReward);
        } else if (pendingReward > 0) {
            // User eligible receives rewards
            require(
                hymToken.balanceOf(address(this)) >= pendingReward + amountToTransfer,
                "Insufficient contract balance"
            );
            require(
                hymToken.transfer(msg.sender, pendingReward),
                "Reward transfer failed"
            );
            emit RewardClaimed(msg.sender, pendingReward);
        }

        // Transfer the deposited amount back
        require(
            hymToken.transfer(msg.sender, amountToTransfer),
            "Unstake transfer failed"
        );

        emit Unstaked(msg.sender, amountToTransfer, pendingReward);
    }

    /**
     * @notice Allows a user to claim their pending rewards
     */
    function claimReward() external nonReentrant {
        StakeInfo storage info = stakes[msg.sender];
        require(info.amount > 0, "No active stake");

        uint256 pendingReward = _calculatePendingReward(msg.sender);
        require(pendingReward > 0, "No reward available");

        require(
            hymToken.balanceOf(address(this)) >= pendingReward,
            "Insufficient contract balance"
        );

        // Update lastClaimTime e totalClaimed
        info.lastClaimTime = block.timestamp;
        info.totalClaimed += pendingReward;

        require(hymToken.transfer(msg.sender, pendingReward), "Reward transfer failed");

        emit RewardClaimed(msg.sender, pendingReward);
    }

    /**
* @notice Calculates the pending reward for a user
* @param user The user's address.
* @return The calculated reward amount.
     */
    function calculateReward(address user) public view returns (uint256) {
        return _calculatePendingReward(user);
    }

    /**
* @dev Internal function to calculate pending rewards
* @param user The user's address
* @return The pending reward since the last claim
     */
    function _calculatePendingReward(address user) internal view returns (uint256) {
        StakeInfo memory info = stakes[user];
        if (info.amount == 0) return 0;

        // Calculate time since last claim (or start of stake)
        uint256 timeForReward = block.timestamp - info.lastClaimTime;

        // Calculate reward proportional to time
        uint256 annualReward = (info.amount * rewardRate * timeForReward) / REWARD_DENOMINATOR / 365 days;
        
        return annualReward;
    }

    /**
     * @notice Allows to preview the reward for a given amount and duration.
     * @param amount The amount to be staked.
     * @param durationInDays The duration of the staking in days.
     * @return The predicted reward.
     */
    function previewReward(uint256 amount, uint256 durationInDays) external view returns (uint256) {
        return (amount * rewardRate * durationInDays * 1 days) / REWARD_DENOMINATOR / 365 days;
    }

    /**
     * @notice Returns complete information about a user's stake
     * @param user The user's address.
     * @return amount The staked amount.
     * @return since The timestamp of the stake's start.
     * @return reward The calculated reward.
     * @return totalClaimed Total claimed by the user.
     */
    function getStakeInfo(
        address user
    ) external view returns (uint256 amount, uint256 since, uint256 reward, uint256 totalClaimed) {
        StakeInfo memory info = stakes[user];
        amount = info.amount;
        since = info.startTime;
        reward = _calculatePendingReward(user);
        totalClaimed = info.totalClaimed;
    }

    /**
     * @notice Updates the reward rate.
     * @param newRate The new reward rate.
     */
    function updateRewardRate(uint256 newRate) external onlyGov {
        require(newRate <= 200000, "Rate too high"); // Maximum 20% per year
        rewardRate = newRate;
        emit RewardRateUpdated(newRate);
    }

    /**
     * @notice Updates the minimum stake amount.
     * @param newMinimum The new minimum stake amount.
     */
    function updateMinimumStake(uint256 newMinimum) external onlyGov {
        require(newMinimum > 0, 'Invalid minimum');
        minimumStake = newMinimum;
        emit MinimumStakeUpdated(newMinimum);
    }

    /**
     * @notice Updates the staking period for fee exemption.
     * @param newPeriodInSeconds The new period in seconds.
     */
    function updateStakingPeriod(uint256 newPeriodInSeconds) external onlyGov {
        require(newPeriodInSeconds >= 1 days, 'Minimum period: 1 day');
        stakingPeriodForNoFee = newPeriodInSeconds;
        emit StakingPeriodUpdated(newPeriodInSeconds);
    }

    /**
     * @notice Checks if the user is eligible for fee exemption.
     * @param user The user's address.
     * @return True if the user is eligible for fee exemption, false otherwise.
     */
    function isEligibleForFeeExemption(address user) external view returns (bool) {
        StakeInfo memory info = stakes[user];
        return info.amount >= minimumStake && block.timestamp >= info.startTime + stakingPeriodForNoFee;
    }

    /**
     * @notice Returns the pending reward for a user.
     * @param user The user's address.
     * @return The amount of pending reward.
     */
    function getPendingReward(address user) external view returns (uint256) {
        return _calculatePendingReward(user);
    }

    /**
     * @notice Returns the address of the staked token.
     * @return The address of the HYM token.
     */
    function token() external view returns (address) {
        return address(hymToken);
    }

    /**
     * @notice Returns the amount of tokens staked by a user.
     * @param user The user's address.
     * @return The amount of tokens staked.
     */
    function getStakedAmount(address user) external view returns (uint256) {
        return stakes[user].amount;
    }

    /**
* @notice Allows the owner to withdraw a user's stake in case of emergency.
* @param user The address of the user whose stake will be withdrawn.
     */
    function emergencyWithdraw(address user) external onlyOwner {
        StakeInfo storage info = stakes[user];
        uint256 amount = info.amount;
        require(amount > 0, 'Nothing to withdraw');

        // Limpa dados do stake
        info.amount = 0;
        info.startTime = 0;
        info.lastClaimTime = 0;
        info.totalClaimed = 0;

        require(hymToken.transfer(user, amount), 'Withdrawal failed');
    }

    /**
     * @notice Returns a detailed summary of a user's stake
     * @param user The user's address.
     * @return amount The amount staked.
     * @return startTime The stake start timestamp.
     * @return lastClaimTime The last claim timestamp.
     * @return pendingReward The calculated pending reward.
     * @return totalClaimed he total claimed.
     * @return isEligible True if the user is eligible for fee exemption.
     */
    function getStakingSummary(
        address user
    )
        external
        view
        returns (
            uint256 amount,
            uint256 startTime,
            uint256 lastClaimTime,
            uint256 pendingReward,
            uint256 totalClaimed,
            bool isEligible
        )
    {
        StakeInfo memory info = stakes[user];
        amount = info.amount;
        startTime = info.startTime;
        lastClaimTime = info.lastClaimTime;
        pendingReward = _calculatePendingReward(user);
        totalClaimed = info.totalClaimed;
        isEligible = (amount >= minimumStake && block.timestamp >= startTime + stakingPeriodForNoFee);
    }

    /**
* @notice Emergency function to retrieve accidentally sent ERC20 tokens
* @param tokenAddress Address of the token to be retrieved
* @param amount Amount to be retrieved
     */
    function emergencyRecoverToken(address tokenAddress, uint256 amount) external onlyOwner {
        require(tokenAddress != address(hymToken), "Cannot recover HYM");
        require(tokenAddress != address(0), "Invalid token address");
        IERC20(tokenAddress).transfer(owner(), amount);
    }

    /**
     * @notice Allows the owner to add HYM tokens for rewards
     * @param amount The amount of tokens to be added
     */
    function fundRewards(uint256 amount) external onlyOwner {
        require(hymToken.transferFrom(msg.sender, address(this), amount), "Transfer failed");
        emit VaultFunded(amount);
    }
}

"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "evmVersion": "paris",
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    }
  }
}}

Tags:
ERC20, Multisig, Staking, Multi-Signature, Factory|addr:0x414a0b979b1326efd4c12154dda03de36a404201|verified:true|block:23436040|tx:0x4b5860ff017995afb232c250da12907905e6859e3760accbcd4c416aa0de2bbf|first_check:1758788508

Submitted on: 2025-09-25 10:21:49

Comments

Log in to comment.

No comments yet.