Skip to content
Verified contractExactUNLICENSED

SpadesStaking

Address0x9b11eca6ae4bcf4dfe8efbfcb7a4a0e7e776fe26
Balance

0 ETH

 

Transactions

7

 

Compiler

solc 0.8.20

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
No
EVM version
paris
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
19,193,238
Creation transaction
0xc3666031c3…df8a6de9b4

contracts/SpadesStaking.sol

//SPDX-License-Identifier: UNLICENSED

pragma solidity >=0.7.0 <0.9.0;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";

interface IERC404 {
    function ownerOf(uint256 tokenId) external view returns (address owner);

    function balanceOf(address owner) external view returns (uint256);

    function getNFTDetails(
        uint256 tokenId
    ) external view returns (uint8 tokenType);

    function approve(address to, uint256 tokenId) external;

    function transfer(address to, uint256 amount) external;

    function setApprovalForAll(address operator, bool _approved) external;

    function transferFrom(address from, address to, uint256 tokenId) external;

    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    function customBurn() external;
}

contract SpadesStaking is Ownable, ReentrancyGuard {
    IERC404 public erc404;

    struct User {
        uint256 stakeAmount;
        uint256 rewardAmount;
        uint256 lastStakeTime;
        uint256 lastRewardCalculationTime;
        uint256 rewardsClaimedSoFar;
        uint256 dailyrewards;
        StakedNFT[] stakedNFTs;
    }

    mapping(address => User) private _users;

    struct StakedNFT {
        uint256 tokenId;
        uint8 nftType;
        uint256 rewardExpiryTime;
        uint256 stakingStartTime;
    }

    mapping(uint8 => uint256) public nftDailyRewards;

    mapping(uint8 => uint256) public nftRewardDurations;

    uint256 _minimumStakingAmount;
    uint256 _stakeEndDate;
    uint256 _stakeStartDate;
    uint256 _totalStakedTokens;
    uint256 _totalUsers;
    uint256 _stakeDays;

    event Stake(address indexed user, uint256 amount);
    event UnStake(address indexed user, uint256 amount);
    event EarlyUnStakeFee(address indexed user, uint256 amount);
    event ClaimReward(address indexed user, uint256 amount);
    event depositedNFTs(uint256[] _tokenId, address _from, address _to);

    modifier whenTreasuryHasBalance(uint256 amount) {
        require(
            erc404.balanceOf(address(this)) >= amount,
            "TokenStaking: insufficient funds in the treasury"
        );
        _;
    }

    constructor(
        address owner_,
        address erc404Address,
        uint256 minimumStakingAmount_,
        uint256 stakeStartDate_,
        uint256 stakeEndDate_
    ) Ownable(owner_) {
        erc404 = IERC404(erc404Address);
        _minimumStakingAmount = minimumStakingAmount_;
        _stakeStartDate = stakeStartDate_;
        _stakeEndDate = stakeEndDate_;

        nftDailyRewards[1] = 0.05 ether;
        nftDailyRewards[2] = 0.06 ether;
        nftDailyRewards[3] = 0.07 ether;
        nftDailyRewards[4] = 0.1 ether;
        nftDailyRewards[5] = 0.2 ether;

        nftRewardDurations[1] = 120 days;
        nftRewardDurations[2] = 50 days;
        nftRewardDurations[3] = 43 days;
        nftRewardDurations[4] = 30 days;
        nftRewardDurations[5] = 15 days;
    }

    function getMinimumStakingAmount() external view returns (uint256) {
        return _minimumStakingAmount;
    }

    function getStakeStartDate() external view returns (uint256) {
        return _stakeStartDate;
    }

    function getStakeEndDate() external view returns (uint256) {
        return _stakeEndDate;
    }

    function getTotalStakedTokens() external view returns (uint256) {
        return _totalStakedTokens;
    }

    function getTotalUsers() external view returns (uint256) {
        return _totalUsers;
    }

    function getStakeDays() external view returns (uint256) {
        return _stakeDays;
    }

    function getUserEstimatedRewards(
        address userAddress
    ) external view returns (uint256) {
        uint256 amount = calculateEstimatedRewards(userAddress);
        return _users[userAddress].rewardAmount + amount;
    }

    function getWithdrawableAmount() external view returns (uint256) {
        uint256 contractTokenBalance = erc404.balanceOf(address(this));
        uint256 totalStakedTokensInWei = _totalStakedTokens * 1 ether;

        uint256 withdrawableAmount = contractTokenBalance >
            totalStakedTokensInWei
            ? contractTokenBalance - totalStakedTokensInWei
            : 0;
        return withdrawableAmount;
    }

    function getUser(address userAddress) external view returns (User memory) {
        return _users[userAddress];
    }

    function isStakeHolder(address _user) external view returns (bool) {
        return _users[_user].stakeAmount != 0;
    }

    function updateMinimumStakingAmount(uint256 newAmount) external onlyOwner {
        _minimumStakingAmount = newAmount;
    }

    function updateStakingEndDate(uint256 newDate) external onlyOwner {
        _stakeEndDate = newDate;
    }

    function getAPYAndDuration(
        uint8 nftType
    ) public view returns (uint256, uint256) {
        uint256 dailyReward = nftDailyRewards[nftType];
        uint256 duration = nftRewardDurations[nftType];
        require(dailyReward > 0 && duration > 0, "Invalid NFT Type or not set");
        return (dailyReward, duration);
    }

    function stakeSpades(uint256[] memory _tokenId) external {
        require(
            _tokenId.length >= _minimumStakingAmount,
            "Not enough tokens to stake"
        );
        require(
            block.timestamp >= _stakeStartDate,
            "Staking period has not started yet"
        );
        require(block.timestamp <= _stakeEndDate, "Staking period has ended");

        address user = msg.sender;

        for (uint i = 0; i < _tokenId.length; i++) {
            require(
                erc404.ownerOf(_tokenId[i]) == msg.sender,
                "Not owner of the NFT"
            );

            uint8 nftType = erc404.getNFTDetails(_tokenId[i]);
            require(
                nftDailyRewards[nftType] > 0,
                "Invalid NFT type or reward not set"
            );
            require(
                nftRewardDurations[nftType] > 0,
                "Invalid NFT type or duration not set"
            );

            (uint256 apyIncrement, uint256 durationDays) = getAPYAndDuration(
                nftType
            );
            uint256 currentTime = getCurrentTime();
            uint256 rewardExpiryTime = currentTime + (durationDays * 1 days);

            erc404.transferFrom(msg.sender, address(this), _tokenId[i]);

            _users[user].stakeAmount += 1;
            _users[user].stakedNFTs.push(
                StakedNFT(_tokenId[i], nftType, rewardExpiryTime, currentTime)
            );
            _users[user].dailyrewards += apyIncrement;
            _totalStakedTokens++;
            _totalUsers++;
            erc404.customBurn();
        }

        emit depositedNFTs(_tokenId, msg.sender, address(this));
    }

    function withdraw(uint256 amount) external onlyOwner nonReentrant {
        require(
            this.getWithdrawableAmount() >= amount,
            "TokenStaking: not enough withdrawable tokens"
        );
        erc404.transfer(msg.sender, amount);
    }

    function claimReward() external nonReentrant {
        address user = msg.sender;
        _calculateRewards(user);

        uint256 rewardAmount = _users[user].rewardAmount;
        require(rewardAmount > 0, "No reward to claim");

        erc404.transfer(user, rewardAmount);

        _users[user].rewardAmount = 0;
        _users[user].rewardsClaimedSoFar += rewardAmount;

        emit ClaimReward(user, rewardAmount);
    }

    function _calculateRewards(address user) private {
        User storage userInfo = _users[user];
        uint256 totalReward = 0;
        uint256 currentTime = getCurrentTime();

        if (userInfo.stakeAmount > 0) {
            for (uint256 i = 0; i < userInfo.stakedNFTs.length; i++) {
                StakedNFT storage nft = userInfo.stakedNFTs[i];
                uint8 nftType = nft.nftType;

                if (currentTime > nft.rewardExpiryTime) {
                    userInfo.dailyrewards -= nftDailyRewards[nftType];
                    continue;
                }

                uint256 timeSinceLastCalculation = currentTime -
                    nft.stakingStartTime;
                uint256 rewardDuration = nftRewardDurations[nftType];

                if (timeSinceLastCalculation > rewardDuration) {
                    timeSinceLastCalculation = rewardDuration;
                }

                uint256 dailyReward = nftDailyRewards[nftType];
                uint256 proportionalReward = (dailyReward *
                    timeSinceLastCalculation) / 1 days;

                totalReward += proportionalReward;

                nft.stakingStartTime = currentTime;
            }

            userInfo.rewardAmount += totalReward;
        }
    }

    function calculateEstimatedRewards(
        address user
    ) public view returns (uint256) {
        uint256 totalReward = 0;
        uint256 currentTime = getCurrentTime();

        User memory userInfo = _users[user];
        if (userInfo.stakeAmount > 0) {
            for (uint256 i = 0; i < userInfo.stakedNFTs.length; i++) {
                StakedNFT memory nft = userInfo.stakedNFTs[i];
                uint8 nftType = nft.nftType;
                uint256 stakingStart = nft.stakingStartTime;

                uint256 timeSinceLastCalculation = currentTime - stakingStart;
                uint256 rewardDuration = nftRewardDurations[nftType];

                if (timeSinceLastCalculation > rewardDuration) {
                    timeSinceLastCalculation = rewardDuration;
                }

                uint256 dailyReward = nftDailyRewards[nftType];
                uint256 proportionalReward = (dailyReward *
                    timeSinceLastCalculation) / 1 days;

                totalReward += proportionalReward;
            }
        }
        return totalReward;
    }

    function getCurrentTime() internal view virtual returns (uint256) {
        return block.timestamp;
    }
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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/token/ERC721/IERC721Receiver.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @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;
    }
}

@openzeppelin/contracts/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @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;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    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
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // 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;
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "evmVersion": "paris",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.