MasterChef

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": {
    "MasterChef.sol": {
      "content": "// SPDX-License-Identifier: MIT\r
\r
pragma solidity ^0.8.0;\r
\r
/**\r
 * @dev Interface of the ERC20 standard as defined in the EIP.\r
 */\r
interface IERC20 {\r
    /**\r
     * @dev Returns the amount of tokens in existence.\r
     */\r
    function totalSupply() external view returns (uint256);\r
\r
    /**\r
     * @dev Returns the amount of tokens owned by `account`.\r
     */\r
    function balanceOf(address account) external view returns (uint256);\r
\r
    function decimals() external view returns (uint8);\r
\r
    /**\r
     * @dev Moves `amount` tokens from the caller's account to `recipient`.\r
     *\r
     * Returns a boolean value indicating whether the operation succeeded.\r
     *\r
     * Emits a {Transfer} event.\r
     */\r
    function transfer(\r
        address recipient,\r
        uint256 amount\r
    ) external returns (bool);\r
\r
    /**\r
     * @dev Returns the remaining number of tokens that `spender` will be\r
     * allowed to spend on behalf of `owner` through {transferFrom}. This is\r
     * zero by default.\r
     *\r
     * This value changes when {approve} or {transferFrom} are called.\r
     */\r
    function allowance(\r
        address owner,\r
        address spender\r
    ) external view returns (uint256);\r
\r
    /**\r
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\r
     *\r
     * Returns a boolean value indicating whether the operation succeeded.\r
     *\r
     * IMPORTANT: Beware that changing an allowance with this method brings the risk\r
     * that someone may use both the old and the new allowance by unfortunate\r
     * transaction ordering. One possible solution to mitigate this race\r
     * condition is to first reduce the spender's allowance to 0 and set the\r
     * desired value afterwards:\r
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r
     *\r
     * Emits an {Approval} event.\r
     */\r
    function approve(address spender, uint256 amount) external returns (bool);\r
\r
    /**\r
     * @dev Moves `amount` tokens from `sender` to `recipient` using the\r
     * allowance mechanism. `amount` is then deducted from the caller's\r
     * allowance.\r
     *\r
     * Returns a boolean value indicating whether the operation succeeded.\r
     *\r
     * Emits a {Transfer} event.\r
     */\r
    function transferFrom(\r
        address sender,\r
        address recipient,\r
        uint256 amount\r
    ) external returns (bool);\r
\r
    function mint(address _to, uint256 _amount) external;\r
\r
    /**\r
     * @dev Emitted when `value` tokens are moved from one account (`from`) to\r
     * another (`to`).\r
     *\r
     * Note that `value` may be zero.\r
     */\r
    event Transfer(address indexed from, address indexed to, uint256 value);\r
\r
    /**\r
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\r
     * a call to {approve}. `value` is the new allowance.\r
     */\r
    event Approval(\r
        address indexed owner,\r
        address indexed spender,\r
        uint256 value\r
    );\r
}\r
\r
/**\r
 * @dev 封装了 Solidity 的算术运算并添加了溢出检查。\r
 *\r
 * Solidity 中的算术运算会溢出溢出。\r
 * 这很容易导致错误,因为程序员通常因为溢出会引发错误,这是高级编程语言中的普遍情况。\r
 * “SafeMath”通过在操作溢出时恢复事务来恢复这种直觉。\r
 *\r
 * 使用这个库而不是未经检查的操作可以消除一整类错误,因此建议始终使用它。\r
 */\r
library SafeMath {\r
    /**\r
     * @dev 返回两个无符号整数的相加,在溢出时恢复。\r
     *\r
     * Counterpart to Solidity's `+` operator.\r
     *\r
     * Requirements:\r
     *\r
     * - Addition cannot overflow.\r
     */\r
    function add(uint256 a, uint256 b) internal pure returns (uint256) {\r
        uint256 c = a + b;\r
        require(c >= a, "SafeMath: addition overflow");\r
\r
        return c;\r
    }\r
\r
    /**\r
     * @dev Returns the subtraction of two unsigned integers, reverting on\r
     * overflow (when the result is negative).\r
     *\r
     * Counterpart to Solidity's `-` operator.\r
     *\r
     * Requirements:\r
     *\r
     * - Subtraction cannot overflow.\r
     */\r
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\r
        return sub(a, b, "SafeMath: subtraction overflow");\r
    }\r
\r
    /**\r
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\r
     * overflow (when the result is negative).\r
     *\r
     * Counterpart to Solidity's `-` operator.\r
     *\r
     * Requirements:\r
     *\r
     * - Subtraction cannot overflow.\r
     */\r
    function sub(\r
        uint256 a,\r
        uint256 b,\r
        string memory errorMessage\r
    ) internal pure returns (uint256) {\r
        require(b <= a, errorMessage);\r
        uint256 c = a - b;\r
\r
        return c;\r
    }\r
\r
    /**\r
     * @dev Returns the multiplication of two unsigned integers, reverting on\r
     * overflow.\r
     *\r
     * Counterpart to Solidity's `*` operator.\r
     *\r
     * Requirements:\r
     *\r
     * - Multiplication cannot overflow.\r
     */\r
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r
        // benefit is lost if 'b' is also tested.\r
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\r
        if (a == 0) {\r
            return 0;\r
        }\r
\r
        uint256 c = a * b;\r
        require(c / a == b, "SafeMath: multiplication overflow");\r
\r
        return c;\r
    }\r
\r
    /**\r
     * @dev Returns the integer division of two unsigned integers. Reverts on\r
     * division by zero. The result is rounded towards zero.\r
     *\r
     * Counterpart to Solidity's `/` operator. Note: this function uses a\r
     * `revert` opcode (which leaves remaining gas untouched) while Solidity\r
     * uses an invalid opcode to revert (consuming all remaining gas).\r
     *\r
     * Requirements:\r
     *\r
     * - The divisor cannot be zero.\r
     */\r
    function div(uint256 a, uint256 b) internal pure returns (uint256) {\r
        return div(a, b, "SafeMath: division by zero");\r
    }\r
\r
    /**\r
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\r
     * division by zero. The result is rounded towards zero.\r
     *\r
     * Counterpart to Solidity's `/` operator. Note: this function uses a\r
     * `revert` opcode (which leaves remaining gas untouched) while Solidity\r
     * uses an invalid opcode to revert (consuming all remaining gas).\r
     *\r
     * Requirements:\r
     *\r
     * - The divisor cannot be zero.\r
     */\r
    function div(\r
        uint256 a,\r
        uint256 b,\r
        string memory errorMessage\r
    ) internal pure returns (uint256) {\r
        require(b > 0, errorMessage);\r
        uint256 c = a / b;\r
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold\r
\r
        return c;\r
    }\r
\r
    /**\r
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\r
     * Reverts when dividing by zero.\r
     *\r
     * Counterpart to Solidity's `%` operator. This function uses a `revert`\r
     * opcode (which leaves remaining gas untouched) while Solidity uses an\r
     * invalid opcode to revert (consuming all remaining gas).\r
     *\r
     * Requirements:\r
     *\r
     * - The divisor cannot be zero.\r
     */\r
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\r
        return mod(a, b, "SafeMath: modulo by zero");\r
    }\r
\r
    /**\r
     * @dev 返回两个无符号整数相除的余数。 (unsigned integer modulo),\r
     * Reverts with custom message when dividing by zero.\r
     *\r
     * Counterpart to Solidity's `%` operator. This function uses a `revert`\r
     * opcode (which leaves remaining gas untouched) while Solidity uses an\r
     * invalid opcode to revert (consuming all remaining gas).\r
     *\r
     * Requirements:\r
     *\r
     * - The divisor cannot be zero.\r
     */\r
    function mod(\r
        uint256 a,\r
        uint256 b,\r
        string memory errorMessage\r
    ) internal pure returns (uint256) {\r
        require(b != 0, errorMessage);\r
        return a % b;\r
    }\r
}\r
\r
/**\r
 * @dev 地址类型相关函数集合\r
 */\r
library Address {\r
    /**\r
     * @dev 如果 `account` 是合约,则返回 true。\r
     *\r
     * [IMPORTANT]\r
     * ====\r
     * 假设此函数返回 false 的地址是外部账户 (EOA) 而不是合约是不安全的。\r
     *\r
     * 其中,对于以下类型的地址,`isContract` 将返回 false:\r
     *\r
     *  - 外部账户\r
     *  - 施工合约\r
     *  - 将创建合约的地址\r
     *  - 合约存在但被销毁的地址\r
     * ====\r
     */\r
    function isContract(address account) internal view returns (bool) {\r
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\r
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\r
        // for accounts without code, i.e. `keccak256('')`\r
        bytes32 codehash;\r
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\r
        // solhint-disable-next-line no-inline-assembly\r
        assembly {\r
            codehash := extcodehash(account)\r
        }\r
        return (codehash != accountHash && codehash != 0x0);\r
    }\r
\r
    /**\r
     * @dev 替代 Solidity 的 `transfer`:将 `amount` wei 发送给 `recipient`,\r
     * 转发所有可用的 gas 并在出现错误时恢复。\r
     *\r
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\r
     * of certain opcodes, possibly making contracts go over the 2300 gas limit\r
     * imposed by `transfer`, making them unable to receive funds via\r
     * `transfer`. {sendValue} removes this limitation.\r
     *\r
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\r
     *\r
     * IMPORTANT: because control is transferred to `recipient`, care must be\r
     * taken to not create reentrancy vulnerabilities. Consider using\r
     * {ReentrancyGuard} or the\r
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\r
     */\r
    function sendValue(address payable recipient, uint256 amount) internal {\r
        require(\r
            address(this).balance >= amount,\r
            "Address: insufficient balance"\r
        );\r
\r
        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\r
        (bool success, ) = recipient.call{value: amount}("");\r
        require(\r
            success,\r
            "Address: unable to send value, recipient may have reverted"\r
        );\r
    }\r
\r
    /**\r
     * @dev Performs a Solidity function call using a low level `call`. A\r
     * plain`call` is an unsafe replacement for a function call: use this\r
     * function instead.\r
     *\r
     * If `target` reverts with a revert reason, it is bubbled up by this\r
     * function (like regular Solidity function calls).\r
     *\r
     * Returns the raw returned data. To convert to the expected return value,\r
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\r
     *\r
     * Requirements:\r
     *\r
     * - `target` must be a contract.\r
     * - calling `target` with `data` must not revert.\r
     *\r
     * _Available since v3.1._\r
     */\r
    function functionCall(\r
        address target,\r
        bytes memory data\r
    ) internal returns (bytes memory) {\r
        return functionCall(target, data, "Address: low-level call failed");\r
    }\r
\r
    /**\r
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\r
     * `errorMessage` as a fallback revert reason when `target` reverts.\r
     *\r
     * _Available since v3.1._\r
     */\r
    function functionCall(\r
        address target,\r
        bytes memory data,\r
        string memory errorMessage\r
    ) internal returns (bytes memory) {\r
        return _functionCallWithValue(target, data, 0, errorMessage);\r
    }\r
\r
    /**\r
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\r
     * but also transferring `value` wei to `target`.\r
     *\r
     * Requirements:\r
     *\r
     * - the calling contract must have an ETH balance of at least `value`.\r
     * - the called Solidity function must be `payable`.\r
     *\r
     * _Available since v3.1._\r
     */\r
    function functionCallWithValue(\r
        address target,\r
        bytes memory data,\r
        uint256 value\r
    ) internal returns (bytes memory) {\r
        return\r
            functionCallWithValue(\r
                target,\r
                data,\r
                value,\r
                "Address: low-level call with value failed"\r
            );\r
    }\r
\r
    /**\r
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\r
     * with `errorMessage` as a fallback revert reason when `target` reverts.\r
     *\r
     * _Available since v3.1._\r
     */\r
    function functionCallWithValue(\r
        address target,\r
        bytes memory data,\r
        uint256 value,\r
        string memory errorMessage\r
    ) internal returns (bytes memory) {\r
        require(\r
            address(this).balance >= value,\r
            "Address: insufficient balance for call"\r
        );\r
        return _functionCallWithValue(target, data, value, errorMessage);\r
    }\r
\r
    function _functionCallWithValue(\r
        address target,\r
        bytes memory data,\r
        uint256 weiValue,\r
        string memory errorMessage\r
    ) private returns (bytes memory) {\r
        require(isContract(target), "Address: call to non-contract");\r
\r
        // solhint-disable-next-line avoid-low-level-calls\r
        (bool success, bytes memory returndata) = target.call{value: weiValue}(\r
            data\r
        );\r
        if (success) {\r
            return returndata;\r
        } else {\r
            // Look for revert reason and bubble it up if present\r
            if (returndata.length > 0) {\r
                // The easiest way to bubble the revert reason is using memory via assembly\r
\r
                // solhint-disable-next-line no-inline-assembly\r
                assembly {\r
                    let returndata_size := mload(returndata)\r
                    revert(add(32, returndata), returndata_size)\r
                }\r
            } else {\r
                revert(errorMessage);\r
            }\r
        }\r
    }\r
}\r
\r
/**\r
 * @title SafeERC20\r
 * @dev Wrappers around ERC20 operations that throw on failure (when the token\r
 * contract returns false). Tokens that return no value (and instead revert or\r
 * throw on failure) are also supported, non-reverting calls are assumed to be\r
 * successful.\r
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\r
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\r
 */\r
library SafeERC20 {\r
    using SafeMath for uint256;\r
    using Address for address;\r
\r
    function safeTransfer(IERC20 token, address to, uint256 value) internal {\r
        _callOptionalReturn(\r
            token,\r
            abi.encodeWithSelector(token.transfer.selector, to, value)\r
        );\r
    }\r
\r
    function safeTransferFrom(\r
        IERC20 token,\r
        address from,\r
        address to,\r
        uint256 value\r
    ) internal {\r
        _callOptionalReturn(\r
            token,\r
            abi.encodeWithSelector(token.transferFrom.selector, from, to, value)\r
        );\r
    }\r
\r
    /**\r
     * @dev 已弃用。\r
     * 此函数存在与 {IERC20-approve} 中发现的问题类似的问题,不鼓励使用。\r
     *\r
     * 如果可能,请改用 {safeIncreaseAllowance} 和 {safeDecreaseAllowance}。\r
     */\r
    function safeApprove(\r
        IERC20 token,\r
        address spender,\r
        uint256 value\r
    ) internal {\r
        // safeApprove should only be called when setting an initial allowance,\r
        // or when resetting it to zero. To increase and decrease it, use\r
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\r
        // solhint-disable-next-line max-line-length\r
        require(\r
            (value == 0) || (token.allowance(address(this), spender) == 0),\r
            "SafeERC20: approve from non-zero to non-zero allowance"\r
        );\r
        _callOptionalReturn(\r
            token,\r
            abi.encodeWithSelector(token.approve.selector, spender, value)\r
        );\r
    }\r
\r
    function safeIncreaseAllowance(\r
        IERC20 token,\r
        address spender,\r
        uint256 value\r
    ) internal {\r
        uint256 newAllowance = token.allowance(address(this), spender).add(\r
            value\r
        );\r
        _callOptionalReturn(\r
            token,\r
            abi.encodeWithSelector(\r
                token.approve.selector,\r
                spender,\r
                newAllowance\r
            )\r
        );\r
    }\r
\r
    function safeDecreaseAllowance(\r
        IERC20 token,\r
        address spender,\r
        uint256 value\r
    ) internal {\r
        uint256 newAllowance = token.allowance(address(this), spender).sub(\r
            value,\r
            "SafeERC20: decreased allowance below zero"\r
        );\r
        _callOptionalReturn(\r
            token,\r
            abi.encodeWithSelector(\r
                token.approve.selector,\r
                spender,\r
                newAllowance\r
            )\r
        );\r
    }\r
\r
    /**\r
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\r
     * on the return value: the return value is optional (but if data is returned, it must not be false).\r
     * @param token The token targeted by the call.\r
     * @param data The call data (encoded using abi.encode or one of its variants).\r
     */\r
    function _callOptionalReturn(IERC20 token, bytes memory data) private {\r
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\r
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\r
        // the target address contains contract code and also asserts for success in the low-level call.\r
\r
        bytes memory returndata = address(token).functionCall(\r
            data,\r
            "SafeERC20: low-level call failed"\r
        );\r
        if (returndata.length > 0) {\r
            // Return data is optional\r
            // solhint-disable-next-line max-line-length\r
            require(\r
                abi.decode(returndata, (bool)),\r
                "SafeERC20: ERC20 operation did not succeed"\r
            );\r
        }\r
    }\r
}\r
\r
/*\r
 * @dev Provides information about the current execution context, including the\r
 * sender of the transaction and its data. While these are generally available\r
 * via msg.sender and msg.data, they should not be accessed in such a direct\r
 * manner, since when dealing with GSN meta-transactions the account sending and\r
 * paying for execution may not be the actual sender (as far as an application\r
 * is concerned).\r
 *\r
 * This contract is only required for intermediate, library-like contracts.\r
 */\r
abstract contract Context {\r
    function _msgSender() internal view virtual returns (address payable) {\r
        return payable(msg.sender);\r
    }\r
\r
    function _msgData() internal view virtual returns (bytes memory) {\r
        this;\r
        // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\r
        return msg.data;\r
    }\r
}\r
\r
/**\r
 * @dev Contract module which provides a basic access control mechanism, where\r
 * there is an account (an owner) that can be granted exclusive access to\r
 * specific functions.\r
 *\r
 * By default, the owner account will be the one that deploys the contract. This\r
 * can later be changed with {transferOwnership}.\r
 *\r
 * This module is used through inheritance. It will make available the modifier\r
 * `onlyOwner`, which can be applied to your functions to restrict their use to\r
 * the owner.\r
 */\r
contract Ownable is Context {\r
    address private _owner;\r
\r
    event OwnershipTransferred(\r
        address indexed previousOwner,\r
        address indexed newOwner\r
    );\r
\r
    /**\r
     * @dev Initializes the contract setting the deployer as the initial owner.\r
     */\r
    constructor() {\r
        address msgSender = _msgSender();\r
        _owner = msgSender;\r
        emit OwnershipTransferred(address(0), msgSender);\r
    }\r
\r
    /**\r
     * @dev Returns the address of the current owner.\r
     */\r
    function owner() public view returns (address) {\r
        return _owner;\r
    }\r
\r
    /**\r
     * @dev Throws if called by any account other than the owner.\r
     */\r
    modifier onlyOwner() {\r
        require(_owner == _msgSender(), "Ownable: caller is not the owner");\r
        _;\r
    }\r
\r
    /**\r
     * @dev Leaves the contract without owner. It will not be possible to call\r
     * `onlyOwner` functions anymore. Can only be called by the current owner.\r
     *\r
     * NOTE: Renouncing ownership will leave the contract without an owner,\r
     * thereby removing any functionality that is only available to the owner.\r
     */\r
    function renounceOwnership() public virtual onlyOwner {\r
        emit OwnershipTransferred(_owner, address(0));\r
        _owner = address(0);\r
    }\r
\r
    /**\r
     * @dev Transfers ownership of the contract to a new account (`newOwner`).\r
     * Can only be called by the current owner.\r
     */\r
    function transferOwnership(address newOwner) public virtual onlyOwner {\r
        require(\r
            newOwner != address(0),\r
            "Ownable: new owner is the zero address"\r
        );\r
        emit OwnershipTransferred(_owner, newOwner);\r
        _owner = newOwner;\r
    }\r
}\r
\r
// 请注意,它是可拥有的,并且拥有者拥有巨大的权力。\r
// 一旦 SUSHI 被充分分配并且社区可以表现出自我管理,所有权将转移到治理智能合约。\r
//\r
contract MasterChef is Ownable {\r
    using SafeMath for uint256;\r
    using SafeERC20 for IERC20;\r
\r
    // 每个用户的信息。\r
    struct UserInfo {\r
        uint256 amount; // 用户提供了多少 LP 代币。\r
        uint256 rewardDebt; // 用户已经获取的奖励\r
        uint256 totalReward; // 累计获得的奖励\r
        //\r
        // 我们在这里做一些花哨的数学运算。\r
        // 基本上,在任何时间点,有权授予用户但待分配的 SUSHI 数量为:\r
        //\r
        //   pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt\r
        //\r
        // 每当用户将 LP 代币存入或提取到池中时。这是发生的事情:\r
        //   1. 池的 `accSushiPerShare`(和 `lastRewardBlock`)得到更新。\r
        //   2. 用户收到发送到他/她的地址的待处理奖励。\r
        //   3. 用户的“金额”得到更新。\r
        //   4. 用户的“rewardDebt”得到更新。\r
    }\r
\r
    // 每个池的信息。\r
    struct PoolInfo {\r
        IERC20 lpToken; // LP 代币合约地址。\r
        uint256 decimals; // LP 代币的精度\r
        uint256 totalPower;\r
        uint256 allocPoint; // 分配给此池的分配点数。 SUSHI 分配每个块。\r
        uint256 lastRewardTime; // SUSHI 分配发生的最后一个块号。\r
        uint256 accSushiPerShare; // 质押一个LPToken的全局收益\r
    }\r
\r
\r
    // The SUSHI TOKEN!\r
    IERC20 public token;\r
\r
    uint256 public powerPerPrice = 1e18; // 1 Power的价格\r
    uint256 public lastPriceUpdateTime; // 上次更新价格的时间\r
    uint256 public depreciationPerDayBps = 30; // 0.3% = 30/10000\r
    uint256 public constant PRICE_DENOMINATOR = 10000;\r
\r
    // 初始每10分钟奖励50个\r
    uint256 public constant INITIAL_REWARD = 50e18; // 50个token,18位精度\r
    uint256 public BlockRewards = 50e18;\r
    uint256 public constant REWARD_INTERVAL = 600; // 10分钟=600秒\r
    uint256 public tokenPerSecond = INITIAL_REWARD / REWARD_INTERVAL;\r
    uint256 public constant HALVING_INTERVAL = 210000 * 600; // 2100000分钟=126000000秒\r
\r
    uint256 private constant INVITE_REWARD_RATE_BASIS_POINTS = 10000;\r
    uint256 private constant BURN_RATE_BASIS_POINTS = 1000;\r
    uint256 public inviteRewardRate = 500; // 邀请人奖励比例 1000/10000 = 10%\r
    uint256 public burnRate = 1000; // 烧伤比例门槛 1000/1000 = 100% 邀请人和下级的算力比必须大于等于这个比例才能拿满奖励\r
    address public fundAddress; // 基金地址\r
    \r
\r
    \r
    address public operator;\r
    uint256 public nextNodeId = 1;\r
    bool public createNodePublic = false; // 是否公开创建矿池\r
    mapping(uint256 => address) public nodes;\r
    mapping(address => uint256) public userNode; \r
    mapping(string => uint256) public nodeIdByCommand;\r
\r
    mapping(address => address) public inviter; //邀请人\r
    mapping(address => uint256) public inviteCount; //邀请人好友数\r
    mapping(address => uint256) public totalInviteReward; //累计奖励\r
\r
    // 每个池的信息。\r
    PoolInfo[] public poolInfo;\r
    // 每个持有 LP 代币的用户的信息。\r
    mapping(uint256 => mapping(address => UserInfo)) public userInfo;\r
    mapping(address => uint256) public Pid;\r
    // 总分配点数。 必须是所有池中所有分配点的总和。\r
    uint256 public totalAllocPoint = 0;\r
    // SUSHI 挖矿开始时的时间戳。\r
    uint256 public startTime;\r
\r
    event Deposit(\r
        address indexed user,\r
        uint256 indexed pid,\r
        uint256 amount,\r
        uint256 powerAmount\r
    );\r
    event Withdraw(\r
        address indexed user,\r
        uint256 indexed pid,\r
        uint256 amount,\r
        uint256 powerAmount\r
    );\r
    event EmergencyWithdraw(\r
        address indexed user,\r
        uint256 indexed pid,\r
        uint256 amount,\r
        uint256 powerAmount\r
    );\r
    event BindInviter(address indexed user, address indexed inviter);\r
    event InviteReward(\r
        uint256 indexed pid,\r
        address indexed user,\r
        address indexed inviter,\r
        uint256 amount\r
    );\r
    event TakeUserReward(\r
        uint256 indexed pid,\r
        address indexed user,\r
        uint256 amount\r
    );\r
    \r
    event CreateNode(address indexed creator, uint256 indexed nodeId);\r
    event JoinNode(address indexed user, uint256 indexed nodeId);\r
    event TransferNode(\r
        uint256 indexed nodeId,\r
        address indexed from,\r
        address indexed to\r
    );\r
    event SetNodeCommand(uint256 indexed nodeId, string command);\r
    event OperatorSet(address indexed operator);\r
    event CreateNodePublicSet(bool indexed createNodePublic);\r
\r
    constructor(address _token, uint256 _startTime, address _fundAddress) {\r
        token = IERC20(_token);\r
        startTime = _startTime;\r
        fundAddress = _fundAddress;\r
        lastPriceUpdateTime = startTime;\r
    }\r
\r
    function setInviteRewardRate(uint256 _inviteRewardRate) external onlyOwner {\r
        require(\r
            _inviteRewardRate <= INVITE_REWARD_RATE_BASIS_POINTS,\r
            "Invalid invite reward rate"\r
        );\r
        inviteRewardRate = _inviteRewardRate;\r
    }\r
\r
    modifier onlyOperator() {\r
        require(msg.sender == operator, "Not operator");\r
        _;\r
    }\r
\r
    function setBurnRate(uint256 _burnRate) external onlyOwner {\r
        burnRate = _burnRate;\r
    }\r
\r
    function setFundAddress(address _fundAddress) external onlyOwner {\r
        require(_fundAddress != address(0), "Invalid fund address");\r
        fundAddress = _fundAddress;\r
    }\r
\r
    function setOperator(address _operator) external onlyOwner {\r
        operator = _operator;\r
        emit OperatorSet(_operator);\r
    }\r
\r
    function setCreateNodePublic() external onlyOwner {\r
        createNodePublic = !createNodePublic;\r
    }\r
\r
    function createNode(address _creator) external {\r
        require(createNodePublic || msg.sender == operator, "Not authorized");\r
        require(_creator != address(0), "Invalid creator");\r
\r
        uint256 nodeId = nextNodeId;\r
        nextNodeId += 1;\r
        nodes[nodeId] = _creator;\r
\r
        emit CreateNode(_creator, nodeId);\r
    }\r
\r
    function transferNode(uint256 nodeId, address newCreator) external {\r
        require(nodes[nodeId] == msg.sender, "permission denied");\r
        require(newCreator != address(0), "Invalid new creator");\r
        nodes[nodeId] = newCreator;\r
        emit TransferNode(nodeId, msg.sender, newCreator);\r
    }\r
\r
    function setNodeCommand(uint256 nodeId, string memory command) external {\r
        require(nodes[nodeId] == msg.sender, "Not creator");\r
        require(bytes(command).length != 0, "Invalid command");\r
        require(nodeIdByCommand[command] == 0, "Command already exists");\r
        nodeIdByCommand[command] = nodeId;\r
        emit SetNodeCommand(nodeId, command);\r
    }\r
\r
    function joinNode(uint256 _nodeId) external {\r
        require(nodes[_nodeId] != address(0), "Node not exist");\r
        userNode[msg.sender] = _nodeId;\r
        emit JoinNode(msg.sender, _nodeId);\r
    }\r
\r
    function Halving() public {\r
        BlockRewards = currentRewardPerInterval();\r
    }\r
\r
    // 返回当前每10分钟的奖励(已考虑减半)\r
    function currentRewardPerInterval() public view returns (uint256) {\r
        if (block.timestamp < startTime) {\r
            return 0;\r
        }\r
        uint256 elapsed = block.timestamp - startTime;\r
        uint256 halvings = elapsed / HALVING_INTERVAL;\r
        return INITIAL_REWARD >> halvings; // 每减半一次奖励除以2\r
    }\r
\r
    // 返回当前每秒奖励(动态计算)\r
    function currentRewardPerSecond() public view returns (uint256) {\r
        return BlockRewards / REWARD_INTERVAL;\r
    }\r
\r
    function poolLength() external view returns (uint256) {\r
        return poolInfo.length;\r
    }\r
\r
    // 将新的 lp 添加到池中。 只能由所有者调用。\r
    // XXX 不要多次添加相同的 LP 令牌。 如果你这样做,奖励会被搞砸。\r
    // _allocPoint 分配点\r
    // _withUpdate 是否马上更新所有池的奖励变量。 小心汽油消费!\r
    function add(\r
        uint256 _allocPoint,\r
        IERC20 _lpToken,\r
        bool _withUpdate\r
    ) public onlyOwner {\r
        require(Pid[address(_lpToken)] == 0); //防呆,避免重复添加池\r
\r
        if (_withUpdate) {\r
            massUpdatePools();\r
        }\r
        uint256 lastRewardTime = block.timestamp > startTime\r
            ? block.timestamp\r
            : startTime;\r
        totalAllocPoint = totalAllocPoint.add(_allocPoint);\r
        poolInfo.push(\r
            PoolInfo({\r
                lpToken: _lpToken,\r
                decimals:10 ** _lpToken.decimals(),\r
                allocPoint: _allocPoint,\r
                lastRewardTime: lastRewardTime,\r
                accSushiPerShare: 0,\r
                totalPower: 0\r
            })\r
        );\r
\r
        Pid[address(_lpToken)] = poolInfo.length;\r
    }\r
\r
    // 更新给定池的 token 分配点。 只能由所有者调用。\r
    function set(\r
        uint256 _pid,\r
        uint256 _allocPoint,\r
        bool _withUpdate\r
    ) public onlyOwner {\r
        if (_withUpdate) {\r
            massUpdatePools();\r
        }\r
        totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(\r
            _allocPoint\r
        );\r
        poolInfo[_pid].allocPoint = _allocPoint;\r
    }\r
\r
    // 查看功能以查看前端待处理的 SUSHI。\r
    function pendingSushi(\r
        uint256 _pid,\r
        address _user\r
    ) external view returns (uint256) {\r
        PoolInfo storage pool = poolInfo[_pid];\r
        UserInfo storage user = userInfo[_pid][_user];\r
        uint256 accSushiPerShare = pool.accSushiPerShare;\r
        if (block.timestamp > pool.lastRewardTime && pool.totalPower != 0) {\r
            // 倍数\r
            uint256 timeElapsed = block.timestamp - pool.lastRewardTime;\r
            // sushi奖励 = 倍数x每块产出x池的分配点/总的分配点\r
            uint256 sushiReward = timeElapsed\r
                .mul(currentRewardPerSecond())\r
                .mul(pool.allocPoint)\r
                .div(totalAllocPoint);\r
            // 每股累积 SUSHI = 当前值+(sushi奖励x1万亿/LP流动性)\r
            accSushiPerShare = accSushiPerShare.add(\r
                sushiReward.mul(1e12).div(pool.totalPower)\r
            );\r
        }\r
        return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);\r
    }\r
\r
    // 更新所有池的奖励变量。 小心汽油消费!\r
    function massUpdatePools() public {\r
        uint256 length = poolInfo.length;\r
        for (uint256 pid = 0; pid < length; ++pid) {\r
            updatePool(pid);\r
        }\r
    }\r
\r
    // 更新给定池的奖励变量以保持最新。\r
    function updatePool(uint256 _pid) public {\r
        PoolInfo storage pool = poolInfo[_pid];\r
        if (block.timestamp <= pool.lastRewardTime) {\r
            return;\r
        }\r
        if (pool.totalPower == 0) {\r
            pool.lastRewardTime = block.timestamp;\r
            return;\r
        }\r
        uint256 timeElapsed = block.timestamp - pool.lastRewardTime;\r
        uint256 sushiReward = timeElapsed\r
            .mul(currentRewardPerSecond())\r
            .mul(pool.allocPoint)\r
            .div(totalAllocPoint);\r
        token.mint(address(this), sushiReward);\r
        // 给masterchef铸币 奖励数额\r
        pool.accSushiPerShare = pool.accSushiPerShare.add(\r
            sushiReward.mul(1e12).div(pool.totalPower)\r
        );\r
        pool.lastRewardTime = block.timestamp;\r
    }\r
\r
    function bindInviter(address _inviter) external {\r
        require(inviter[msg.sender] == address(0), "Already bound");\r
        require(_inviter != address(0), "Invalid inviter");\r
        require(inviter[_inviter] != msg.sender, "Inviter cannot be same as user");\r
        require(_inviter != msg.sender, "Inviter cannot be self");\r
\r
        inviter[msg.sender] = _inviter;\r
        inviteCount[_inviter] += 1;\r
        emit BindInviter(msg.sender, _inviter);\r
    }\r
\r
    function updatePrice() public {\r
        if (block.timestamp <= lastPriceUpdateTime) return;\r
\r
        uint256 elapsed = block.timestamp - lastPriceUpdateTime;\r
\r
        // 每秒线性摊:powerPerPrice += powerPerPrice * (bps/天) * 秒数 / 86400\r
        uint256 delta = (powerPerPrice * depreciationPerDayBps * elapsed) /\r
            (PRICE_DENOMINATOR * 86400);\r
\r
        if (delta > 0) {\r
            powerPerPrice += delta;\r
            lastPriceUpdateTime = block.timestamp;\r
        }\r
        //每天自动提现一次\r
        // if (block.timestamp - lastwithdrawTime >= 86400) {\r
        //     withdraw();\r
        // }\r
    }\r
\r
    // 将 LP 代币存入 MasterChef 以分配 SUSHI。\r
    function deposit(uint256 _pid, uint256 _amount) public {\r
        require(_amount > 0, "Invalid amount");\r
        require(userNode[msg.sender] >0 ,"Must join a pool to mine");\r
\r
        updatePrice();\r
        PoolInfo storage pool = poolInfo[_pid];\r
        UserInfo storage user = userInfo[_pid][msg.sender];\r
        updatePool(_pid);\r
        if (user.amount > 0) {\r
            uint256 pending = user\r
                .amount\r
                .mul(pool.accSushiPerShare)\r
                .div(1e12)\r
                .sub(user.rewardDebt);\r
            _processUserRewardAndFee(_pid, pending, msg.sender);\r
        }\r
        pool.lpToken.safeTransferFrom(\r
            address(msg.sender),\r
            address(this),\r
            _amount\r
        );\r
\r
        // 更新矿池总算力\r
        uint256 powerAmount = (_amount * powerPerPrice) / pool.decimals;\r
        pool.totalPower = pool.totalPower.add(powerAmount);\r
        user.amount = user.amount.add(powerAmount);\r
        user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\r
        emit Deposit(msg.sender, _pid, _amount, powerAmount);\r
    }\r
\r
    // 从 MasterChef 中提现 LP 代币。\r
    function withdraw(uint256 _pid, uint256 _powerAmount) public {\r
        PoolInfo storage pool = poolInfo[_pid];\r
        UserInfo storage user = userInfo[_pid][msg.sender];\r
        require(_powerAmount > 0, "Invalid power amount");\r
        require(user.amount >= _powerAmount, "withdraw: not good");\r
        updatePrice();\r
        updatePool(_pid);\r
        uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(\r
            user.rewardDebt\r
        );\r
        _processUserRewardAndFee(_pid, pending, msg.sender);\r
\r
        // 更新矿池总算力\r
        uint256 _amount = (_powerAmount * pool.decimals) / powerPerPrice;\r
        pool.totalPower = pool.totalPower.sub(_powerAmount);\r
        user.amount = user.amount.sub(_powerAmount);\r
        user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\r
        pool.lpToken.safeTransfer(address(msg.sender), _amount);\r
        emit Withdraw(msg.sender, _pid, _amount, _powerAmount);\r
    }\r
\r
    // 提现而不关心奖励。 仅限紧急情况。\r
    function emergencyWithdraw(uint256 _pid) public {\r
        PoolInfo storage pool = poolInfo[_pid];\r
        UserInfo storage user = userInfo[_pid][msg.sender];\r
        require(user.amount > 0, "Invalid user amount");\r
\r
        uint256 _amount = (user.amount * pool.decimals) / powerPerPrice;\r
        pool.lpToken.safeTransfer(address(msg.sender), _amount);\r
        emit EmergencyWithdraw(msg.sender, _pid, _amount, user.amount);\r
        // 更新矿池总算力\r
        pool.totalPower = pool.totalPower.sub(user.amount);\r
        user.amount = 0;\r
        user.rewardDebt = 0;\r
    }\r
\r
    // 直接领取收益\r
    function takerWithdraw(uint256 _pid) public {\r
        PoolInfo storage pool = poolInfo[_pid];\r
        UserInfo storage user = userInfo[_pid][msg.sender];\r
        updatePool(_pid);\r
        if (user.amount > 0) {\r
            uint256 pending = user\r
                .amount\r
                .mul(pool.accSushiPerShare)\r
                .div(1e12)\r
                .sub(user.rewardDebt);\r
            _processUserRewardAndFee(_pid, pending, msg.sender);\r
        }\r
        user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\r
    }\r
\r
    // 处理用户收益和手续费的内部函数\r
    function _processUserRewardAndFee(\r
        uint256 _pid,\r
        uint256 pending,\r
        address userAddress\r
    ) internal {\r
        if (pending == 0) return;\r
\r
        uint256 baseInviteReward = (pending * inviteRewardRate) /\r
            INVITE_REWARD_RATE_BASIS_POINTS;\r
\r
        uint256 finalInviteReward = 0;\r
        address creator = nodes[userNode[userAddress]];\r
        uint256 creatorFee = (pending * 5) / 100;\r
        uint256 toUser = pending - baseInviteReward - creatorFee;\r
\r
        if (inviter[userAddress] != address(0) && inviteRewardRate > 0) {\r
            address inviterAddress = inviter[userAddress];\r
            uint256 userPower = userInfo[_pid][userAddress].amount;\r
            uint256 inviterPower = userInfo[_pid][inviterAddress].amount;\r
\r
            if (inviterPower > 0 && userPower > 0) {\r
                // 核心烧伤逻辑 inviterPower / userPower < burnRate / 1000\r
                // (50*500/100)/1000\r
                if (\r
                    burnRate > 0 &&\r
                    (inviterPower * BURN_RATE_BASIS_POINTS <\r
                        userPower * burnRate)\r
                ) {\r
                    // 触发烧伤\r
                    finalInviteReward =\r
                        (baseInviteReward *\r
                            inviterPower *\r
                            BURN_RATE_BASIS_POINTS) /\r
                        (userPower * burnRate);\r
                } else {\r
                    finalInviteReward = baseInviteReward;\r
                }\r
            }\r
\r
            if (finalInviteReward > 0) {\r
                if (finalInviteReward > toUser) {\r
                    finalInviteReward = toUser;\r
                }\r
\r
                totalInviteReward[inviterAddress] = totalInviteReward[\r
                    inviterAddress\r
                ].add(finalInviteReward);\r
                safeSushiTransfer(inviterAddress, finalInviteReward);\r
                emit InviteReward(\r
                    _pid,\r
                    userAddress,\r
                    inviterAddress,\r
                    finalInviteReward\r
                );\r
            }\r
        }\r
\r
        if (finalInviteReward < baseInviteReward) {\r
            creatorFee += baseInviteReward - finalInviteReward;\r
        }\r
\r
        if (creatorFee > 0) {\r
            safeSushiTransfer(creator, creatorFee);\r
        }\r
\r
        if (toUser > 0) {\r
            userInfo[_pid][userAddress].totalReward = userInfo[_pid][\r
                userAddress\r
            ].totalReward.add(toUser);\r
            safeSushiTransfer(userAddress, toUser);\r
            emit TakeUserReward(_pid, userAddress, toUser);\r
        }\r
    }\r
\r
    // 安全的sushi转账功能,以防万一如果舍入错误导致池没有足够的寿司。\r
    function safeSushiTransfer(address _to, uint256 _amount) internal {\r
        uint256 sushiBal = token.balanceOf(address(this));\r
        if (_amount > sushiBal) {\r
            token.transfer(_to, sushiBal);\r
        } else {\r
            token.transfer(_to, _amount);\r
        }\r
    }\r
\r
    function takeWithdrawFee(uint256 _pid) public {\r
        PoolInfo memory pool = poolInfo[_pid];\r
        uint256 balance = pool.lpToken.balanceOf(address(this));\r
        uint256 totalRefundBalance = (pool.totalPower * pool.decimals) /\r
            powerPerPrice;\r
        if (balance > totalRefundBalance) {\r
            pool.lpToken.safeTransfer(\r
                address(fundAddress),\r
                balance - totalRefundBalance\r
            );\r
        }\r
    }\r
}"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "remappings": [],
    "evmVersion": "prague"
  }
}}

Tags:
ERC20, Multisig, Mintable, Multi-Signature, Factory|addr:0xe85a0d630ce1c69aa9c37802a7dd87045e636d70|verified:true|block:23731606|tx:0x8fe0d4af6753d2b9c1d652fee1e3b7596f50f5e3dab970fab87407af6ce6f1d8|first_check:1762345876

Submitted on: 2025-11-05 13:31:19

Comments

Log in to comment.

No comments yet.