File size: 19,361 Bytes
f998fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
{
  "language": "Solidity",
  "sources": {
    "wanderingplanetstake.sol": {
      "content": "// SPDX-License-Identifier: MIT\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\n\n\npragma solidity ^0.8.7;\n\ninterface WPInterFace {\n    function ownerOf(uint256 tokenId) external view returns (address owner);\n    function safeTransferFrom( \n        address from,\n        address to,\n        uint256 tokenId\n    ) external;\n    function totalMinted() external view returns (uint256);\n    function balanceOf(address owner) external view returns (uint256 balance);\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n\ncontract WanderingPlanetStake is Ownable, ReentrancyGuard {    \n    event Staked(address indexed owner, uint256 tokenID);\n    event Reclaimed(address indexed owner, uint256 tokenID);\n    event StakeInterrupted(uint256 indexed tokenId);\n    event Withdraw(address indexed account, uint256 amount);\n    event stakeTimeConfigChanged(Period config_);\n    \n    // Interface for Wandering Planet Contract\n    WPInterFace WP_Contract;  \n\n    struct Stake_Info{\n        bool staked;\n        address previous_owner;\n        uint256 stake_time;\n    }\n\n    struct Period {\n        uint256 startTime;\n        uint256 endTime;\n    }\n\n\n    // Stake Data Sturcture\n    mapping(uint256 => Stake_Info) public planetStakeInfo;\n    // Mapping from owner to the list of staked token IDs(only for querying)\n    mapping(address => uint256[]) private addressStakeList;\n    // Mapping from token ID to index of the owner tokens list(support to operate the addressStakeList)\n    mapping(uint256 => uint256) private addressStakeIndex;\n    // List for all the tokens staked\n    uint256 [] private allStakeList;\n    // support to operate the allStake list\n    mapping(uint256 => uint256) private allStakeIndex;\n\n    Period public stakeTime;\n    address public wandering_planet_address;\n    uint256 public rewardPeriod = 1000;\n\n\n    constructor(address wandering_planet_address_, Period memory stake_time_) {\n        require(wandering_planet_address_ != address(0), \"invalid contract address\");\n        wandering_planet_address = wandering_planet_address_;\n        stakeTime = stake_time_;\n        WP_Contract = WPInterFace(wandering_planet_address);\n    }\n        \n    /***********************************|\n    |                Core               |\n    |__________________________________*/\n    \n    /**\n    * @dev Pubilc function for owners to reclaim their plantes\n    * @param tokenID uint256 ID list of the token to be reclaim\n    */\n    function reclaimPlanets(uint256 [] memory tokenID) external callerIsUser nonReentrant{\n        for(uint256 i = 0; i < tokenID.length; i++){\n            _reclaim(tokenID[i]);\n        }\n    }\n\n    /**\n    * @dev Private function to stake one planet and update the state variabies\n    * The function will be called when users transfer their tokens via 'safeTransferFrom'\n    * @param tokenID uint256 ID of the token to be staked\n    */\n    function _stake(address owner, uint256 tokenID) internal{\n        require(isStakeEnabled(), \"stake not enabled\");\n        Stake_Info storage status = planetStakeInfo[tokenID];\n        require(status.staked == false, \"token is staking\");\n        status.staked = true;\n        status.previous_owner = owner;\n        status.stake_time = block.number;\n        addEnumeration(owner, tokenID);\n        addAllEnmeration(tokenID);\n        emit Staked(owner, tokenID);\n    }\n\n    /**\n    * @dev Private function to reclaim one planet and update the state variabies\n    * @param tokenID uint256 ID of the token to be reclaimed\n    */\n    function _reclaim(uint256 tokenID) internal{\n        require(isStakeEnabled(), \"stake not enabled\");\n        Stake_Info storage status = planetStakeInfo[tokenID];\n        require(status.staked == true, \"the planet is freedom\");\n        require(status.previous_owner == msg.sender, \"you are not the owner\");\n        WP_Contract.safeTransferFrom(address(this), msg.sender, tokenID);\n        status.staked = false;\n        status.previous_owner = address(0);\n        status.stake_time = 0;\n        removeEnumeration(msg.sender, tokenID);\n        removeAllEnmeration(tokenID);\n        emit Reclaimed(msg.sender, tokenID);\n    }\n\n   /**\n    * @dev Public function to batach stake this planets\n    * Approval for all the WP balances is needed\n    * @param tokenIDs list of the tokens to be reclaimed\n    */\n    function batchStake(uint256 [] memory tokenIDs) external callerIsUser nonReentrant(){\n        require(WP_Contract.isApprovedForAll(msg.sender, address(this)), \"no authority\");\n        if (tokenIDs.length == 0){\n            tokenIDs = getOwnedPlanets(msg.sender);\n        }\n        for(uint256 i = 0; i < tokenIDs.length; i++){\n            require(WP_Contract.ownerOf(tokenIDs[i]) == msg.sender, \"not the owner\");\n            WP_Contract.safeTransferFrom(msg.sender, address(this), tokenIDs[i]);\n        }\n    }\n\n    /**\n     * @dev Private function to add a token to this extension's token tracking data structures.\n     * @param address_ representing the owner of the given token ID\n     * @param tokenID uint256 ID of the token to be added to the tokens list\n     */\n    function addEnumeration(address address_, uint256 tokenID) internal {\n        addressStakeIndex[tokenID] = addressStakeList[address_].length;\n        addressStakeList[address_].push(tokenID);\n    }\n\n    /**\n    * @dev Private function to remove a token from this extension's ownership-tracking data structures.\n    * @param address_ representing the previous owner of the given token ID\n    * @param tokenID uint256 ID of the token to be removed from the tokens list of the given address\n    */\n    function removeEnumeration(address address_, uint256 tokenID) internal {\n\n        require(addressStakeList[address_].length > 0, \"No token staked by this address\");\n        uint256 lastTokenIndex = addressStakeList[address_].length - 1;\n        uint256 tokenIndex = addressStakeIndex[tokenID];\n\n        if (tokenIndex != lastTokenIndex) {\n            uint256 lastTokenId = addressStakeList[address_][lastTokenIndex];\n\n            addressStakeList[address_][tokenIndex] = lastTokenId;\n            addressStakeIndex[lastTokenId] = tokenIndex; \n        }\n        addressStakeList[address_].pop();\n    }\n\n    /*\n    * @dev Private function to add a token to this extension's token tracking data structures.\n    * @param tokenID uint256 ID of the token to be added to the tokens list\n    */\n    function addAllEnmeration(uint256 tokenID) internal {\n        allStakeIndex[tokenID] = allStakeList.length;\n        allStakeList.push(tokenID);\n    }\n\n    /**\n    * @dev Private function to remove a token from this extension's ownership-tracking data structures.\n    * @param tokenID uint256 ID of the token to be removed from the tokens list of the given address\n    */\n    function removeAllEnmeration(uint256 tokenID) internal {\n        require(allStakeList.length > 0, \"No token staked\");\n        uint256 lastTokenIndex = allStakeList.length - 1;\n        uint256 tokenIndex = allStakeIndex[tokenID];\n\n        if (tokenIndex != lastTokenIndex) {\n            uint256 lastTokenId = allStakeList[lastTokenIndex];\n\n            allStakeList[tokenIndex] = lastTokenId;\n            allStakeIndex[lastTokenId] = tokenIndex; \n        }\n        allStakeList.pop();\n    }\n\n\n    /***********************************|\n    |               State               |\n    |__________________________________*/\n\n    function isStakeEnabled() public view returns (bool){\n        if (stakeTime.endTime > 0 && block.timestamp > stakeTime.endTime) {\n            return false;\n        }\n        return stakeTime.startTime > 0 && \n            block.timestamp > stakeTime.startTime;\n    }\n    \n    function getOwnedPlanets(address address_) public view returns (uint256 [] memory){\n        uint256 max_tokenID = WP_Contract.totalMinted();\n        uint256 balance = WP_Contract.balanceOf(address_);\n        uint256 cnt = 0;\n        uint256 [] memory ownedtokens = new uint256 [](balance);\n        for(uint256 i = 0; i < max_tokenID; i++){\n            if(WP_Contract.ownerOf(i) == address_){\n                ownedtokens[cnt++] = i;\n            }\n        }\n        return ownedtokens;\n    }\n\n    /**\n    * @dev Public function to get the staked tokens of the given address\n    * @param address_ representing owner address\n    */\n    function getStakeList(address address_) public view returns (uint256 [] memory){\n        return addressStakeList[address_];\n    }\n\n    /**\n    * @dev Public function to get all the stake list\n    */\n    function getAllStakeList() public view returns (uint256 [] memory){\n        return allStakeList;\n    }\n\n    /**\n    * @dev Public function to get all the staked tokens which satisify the condition of stake time\n    */\n    function getValidStakes() public view returns (uint256 [] memory, bool [] memory){\n        uint256 stake_count = allStakeList.length;\n        bool [] memory isvalidstake = new bool [](stake_count);\n        for(uint256 i = 0; i < stake_count; i++){\n            uint256 tokenID = allStakeList[i];\n            Stake_Info memory status = planetStakeInfo[tokenID];\n            if(status.staked && block.number - status.stake_time >= rewardPeriod){\n                isvalidstake[i] = true;\n            }\n            else{\n                isvalidstake[i] = false;\n            }\n        }\n        return (allStakeList, isvalidstake);\n    }\n\n    function getStakeInfo(uint256 tokenID) public view returns (Stake_Info memory){\n        return planetStakeInfo[tokenID];\n    }\n\n\n\n    /***********************************|\n    |               Owner               |\n    |__________________________________*/\n    /**\n    * @dev Owner function to write adward list\n    */\n    function setRewardPeriod(uint256 rewardPeriod_) external onlyOwner{\n        require(rewardPeriod_ > 0, \"invalid parameter\");\n        rewardPeriod = rewardPeriod_;\n    }\n\n    function setStakeTime(Period calldata config_) external onlyOwner {\n        stakeTime = config_;\n        emit stakeTimeConfigChanged(config_);\n    }\n\n    /**\n     * This method is used to prevent some users from mistakenly using transferFrom (instead of safeTransferFrom) to transfer NFT into the contract.\n     * @param tokenIds_ the tokenId list\n     * @param accounts_ the address list\n     */\n    function transferUnstakingTokens(uint256[] calldata tokenIds_, address[] calldata accounts_) external onlyOwner {\n        require(tokenIds_.length == accounts_.length, \"tokenIds_ and accounts_ length mismatch\");\n        require(tokenIds_.length > 0, \"no tokenId\");\n        for (uint256 i = 0; i < tokenIds_.length; i++) {\n            uint256 tokenId = tokenIds_[i];\n            address account = accounts_[i];\n            require(planetStakeInfo[tokenId].stake_time == 0, \"token is staking\");\n            WP_Contract.safeTransferFrom(address(this), account, tokenId);\n        }\n    }\n\n    function stopStake(uint256[] calldata tokenIds_) external onlyOwner {\n        for (uint256 i; i < tokenIds_.length; i++) {\n            uint256 tokenId = tokenIds_[i];\n            _reclaim(tokenId);\n            emit StakeInterrupted(tokenId);\n        }\n    }\n\n\n    function withdraw() external onlyOwner nonReentrant {\n        uint256 balance = address(this).balance;\n        payable(_msgSender()).transfer(balance);\n        emit Withdraw(_msgSender(), balance);\n    }\n\n    /***********************************|\n    |              Modifier             |\n    |__________________________________*/\n    modifier callerIsUser() {\n        require(tx.origin == _msgSender(), \"caller is another contract\");\n        _;\n    }\n\n    /***********************************|\n    |                Hook               |\n    |__________________________________*/\n    function onERC721Received(\n        address,\n        address _from,\n        uint256 _tokenId,\n        bytes memory\n    ) public returns (bytes4) {\n        require(msg.sender == wandering_planet_address, \"only for WP\");\n        _stake(_from, _tokenId);\n        return this.onERC721Received.selector;\n    }\n}"
    },
    "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n}\n"
    },
    "@openzeppelin/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor() {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
    },
    "@openzeppelin/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "abi"
        ]
      }
    }
  }
}