Verified contractExactMIT
StakingRewards
Address0xbe17982fb721484fd0e3707d231b1df85ffe3864
- Balance
0 ETH
- Transactions
211
- Compiler
solc 0.7.0
- Same code
Only this contract
Details
- Compiler
- solc 0.7.0+commit.9e61f92b
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- istanbul
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 12,587,483
- Creation transaction
- 0xb3f0f61f28…66fd7fa38c
contracts/StakingRewards.sol
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, 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 `sender` to `recipient` 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 sender, address recipient, uint256 amount) external returns (bool);
/**
* @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);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// File: contracts/stakingNew1/IStakingRewards.sol
pragma solidity >=0.6.0 <0.8.0;
interface IStakingRewards {
// Views
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerEth(address[] calldata tokenList, uint256[] calldata prices,uint256[] calldata amountsIn) external view returns (uint256);
function earned(address account, address[] calldata tokenList, uint256[] calldata amountsIn) external view returns (uint256);
function totalETHSupply(address[] calldata tokenList, uint256[] calldata prices, uint256[] calldata amountsIn) external view returns (uint256);
function totalTokenSupply(address token) external view returns (uint256);
function getTokenValueForEth(address token) external view returns (uint256);
function forEthPrice(address token) external view returns (uint256[] memory);
function balanceOfToken(address token, address account)
external
view
returns (uint256);
function getIssueCounter() external view returns (uint256);
// Mutative
function stake(address token, uint256 amount) external;
function stakeWithEth(uint256 amount) payable external;
function withdraw(
address token,
uint256 amount,
address recipient
) external;
function getReward() external;
}
// File: contracts/stakingNew1/StakingRewards.sol
pragma solidity >=0.6.0 <0.8.0;
/* ========== INTERFACE ========== */
interface IStakingElection {
function stakingTokensList() external view returns (address[] memory);
function tokenDecimals(address _token) external view returns (uint8 decimals);
}
interface IERC20Permit {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
interface IUniswapV2Router02 {
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor() public {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(
localCounter == _guardCounter,
"ReentrancyGuard: reentrant call"
);
}
}
abstract contract RewardsDistributionRecipient {
address public rewardsDistribution;
function notifyRewardAmount() external virtual;
modifier onlyRewardsDistribution() {
require(
msg.sender == rewardsDistribution,
"Caller is not RewardsDistribution contract"
);
_;
}
}
contract StakingRewards is
IStakingRewards,
RewardsDistributionRecipient,
ReentrancyGuard
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableMap for EnumerableMap.UintToAddressMap;
/* ========== STATE VARIABLES ========== */
EnumerableMap.UintToAddressMap private rewardsTokens;
address[8] public RewardToken;
//0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
address
public constant ROUTER02 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
// uniswap router02 address
address public immutable stakingElectionAddr;
// WETH address
address public immutable WETH;
address public rewardPoolAddress;
//初始奖励
uint256 public immutable initialTotalreward;
//当前奖励
uint256 public currentTotalreward;
//计数器
uint256 private _issueCounter = 0;
//挖矿结束时间
uint256 public periodFinish = 0;
//产量/秒
uint256 public ethRewardRate = 0;
//挖矿周期
uint256 public constant rewardsDuration = 30 days;
uint256 public constant reductionDuration = 6;
//上次更新时间
uint256 public lastUpdateTime;
uint256 public constant REWARD_POOL_MULTIPLE = 13;
//质押挖矿比例
uint256 public constant STAKING_MULTIPLE = 85;
//结算时每个eth所能获得的奖励
mapping(address => uint256) public rewardPerTokenStored;
//可领取奖励
mapping(address => uint256) public rewards;
//各币种总额
mapping(address => uint256) private _totalTokenSupply;
//erc 20 balance
mapping(address => mapping(address => uint256)) private _tokenBalances;
mapping(address => mapping(address => uint256))
private _userRewardPerTokenPaid;
/* ========== CONSTRUCTOR ========== */
constructor(
uint256 _initialTotalreward,
address _rewardsDistribution,
address _WETH,
address _stakingElectionAddr
) public {
initialTotalreward = _initialTotalreward;
rewardsDistribution = _rewardsDistribution;
stakingElectionAddr = _stakingElectionAddr;
WETH = _WETH;
}
fallback() external {}
/* ========== RESTRICTED FUNCTIONS ========== */
//开启奖池
function notifyRewardAmount()
external
override
onlyRewardsDistribution
updateReward(address(0))
{
//上期未结束,不可开启下一期
require(block.timestamp >= periodFinish, "Time is not up");
//本期奖励 【每六期减产30%】
uint256 reduceTimes = _issueCounter.div(reductionDuration);
currentTotalreward = initialTotalreward.mul(70**reduceTimes).div(
100**reduceTimes
);
//产量/秒
ethRewardRate = currentTotalreward.div(rewardsDuration);
//计数器 + 1
_issueCounter = _issueCounter.add(1);
emit Start(currentTotalreward, _issueCounter);
//每个币种的余额要大于本期奖励
uint256 balance;
for (uint256 i = 0; i < RewardToken.length; i++) {
balance = IERC20(RewardToken[i]).balanceOf(address(this));
require(balance >= currentTotalreward, "Provided reward too high");
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
}
//质押eth
function stakeWithEth(uint256 amount)
external
override
payable
nonReentrant
updateReward(msg.sender)
{
require(amount > 0, "Cannot stake 0");
require(amount == msg.value, "Transfer amount error");
//换成weth
IWETH(WETH).deposit{value: amount}();
_totalTokenSupply[WETH] = _totalTokenSupply[WETH].add(amount);
_tokenBalances[WETH][msg.sender] = _tokenBalances[WETH][msg.sender].add(
amount
);
emit Staked(msg.sender, WETH, amount);
}
//其他币种质押
function stake(address token, uint256 amount)
external
override
nonReentrant
updateReward(msg.sender)
{
require(amount > 0, "Cannot stake 0");
_totalTokenSupply[token] = _totalTokenSupply[token].add(amount);
_tokenBalances[token][msg.sender] = _tokenBalances[token][msg.sender]
.add(amount);
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, token, amount);
}
function stakeWithPermit(
address token,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external nonReentrant updateReward(msg.sender) {
require(amount > 0, "Cannot stake 0");
_totalTokenSupply[token] = _totalTokenSupply[token].add(amount);
_tokenBalances[token][msg.sender] = _tokenBalances[token][msg.sender]
.add(amount);
// permit
IERC20Permit(address(token)).permit(
msg.sender,
address(this),
amount,
deadline,
v,
r,
s
);
IERC20(token).transferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, token, amount);
}
//提现
function withdraw(
address token,
uint256 amount,
address recipient
) external override nonReentrant updateReward(msg.sender) {
require(amount > 0, "Cannot withdraw 0");
_totalTokenSupply[token] = _totalTokenSupply[token].sub(amount);
_tokenBalances[token][msg.sender] = _tokenBalances[token][msg.sender]
.sub(amount);
IERC20(token).safeTransfer(recipient, amount);
emit Withdrawn(msg.sender, token, amount, recipient);
}
//领取奖励
function getReward() external override nonReentrant updateReward(msg.sender) {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
for (uint256 i = 0; i < RewardToken.length; i++) {
IERC20(RewardToken[i]).safeTransfer(msg.sender, reward);
}
emit RewardPaid(msg.sender, reward);
}
}
//设置奖励币种
function setRewardAddress(address[] calldata _rewardAddress)
external
onlyRewardsDistribution
{
require(_rewardAddress.length < 9, "The length of the address list should be less than 9");
for (uint256 i = 0; i < _rewardAddress.length; i++) {
RewardToken[i] = _rewardAddress[i];
emit SetRewardAddress(msg.sender, i, _rewardAddress[i]);
}
}
function updateRewardPerToken(
address[] memory tokenList,
uint256[] memory prices,
uint256[] memory amountsIn
) internal {
uint256 _rewardPerEth = rewardPerEth(tokenList, prices, amountsIn);
for (uint256 i = 0; i < tokenList.length; i++) {
rewardPerTokenStored[tokenList[i]] = rewardPerTokenStored[tokenList[i]]
.add(prices[i].mul(_rewardPerEth).div(1e18));
}
}
/* ========== MODIFIERS ========== */
modifier updateReward(address account) {
address[] memory tokenList = IStakingElection(stakingElectionAddr)
.stakingTokensList();
uint256[] memory amountsIn = new uint256[](tokenList.length);
uint256[] memory prices = new uint256[](tokenList.length);
for (uint256 i = 0; i < tokenList.length; i++) {
uint256[] memory price = forEthPrice(tokenList[i]);
amountsIn[i] = price[0];
prices[i] = price[1];
}
updateRewardPerToken(tokenList, prices, amountsIn);
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
uint256 reward = earned(account, tokenList, amountsIn);
for (uint256 i = 0; i < tokenList.length; i++) {
_userRewardPerTokenPaid[account][tokenList[i]] = rewardPerTokenStored[tokenList[i]];
}
rewards[account] = rewards[account].add(
reward.mul(STAKING_MULTIPLE).div(100)
);
rewards[rewardPoolAddress] = rewards[rewardPoolAddress].add(
reward.mul(REWARD_POOL_MULTIPLE).div(100)
);
}
_;
}
/* ========== VIEWS ========== */
function totalTokenSupply(address token)
external
override
view
returns (uint256)
{
return _totalTokenSupply[token];
}
//换算成eth的总市值
function totalETHSupply(address[] memory tokenList, uint256[] memory prices, uint256[] memory amountsIn)
public
override
view
returns (uint256)
{
uint256 total = 0;
for (uint256 i = 0; i < tokenList.length; i++) {
if (_totalTokenSupply[tokenList[i]] > 0) {
total = total.add(
prices[i].mul(_totalTokenSupply[tokenList[i]]).div(amountsIn[i])
);
}
}
return total;
}
//币种余额
function balanceOfToken(address token, address account)
external
override
view
returns (uint256)
{
return _tokenBalances[token][account];
}
//获取奖池计数
function getIssueCounter() external override view returns (uint256) {
if(_issueCounter == 0){
return 0;
}else{
return (_issueCounter - 1) / reductionDuration + 1;
}
}
//奖励结算时间
function lastTimeRewardApplicable() public override view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
//换算成eth价格 【1 ether】
function forEthPrice(address token) public override view returns (uint256[] memory) {
if (token == WETH) {
uint256[] memory prs = new uint256[](2);
prs[0] = 1e18;
prs[1] = 1e18;
return prs;
}
address[] memory path = new address[](2);
path[0] = token;
path[1] = WETH;
uint8 decimals = IStakingElection(stakingElectionAddr).tokenDecimals(token);
uint256 amountIn = 10 ** uint256(decimals);
uint256[] memory prices = IUniswapV2Router02(ROUTER02).getAmountsOut(
amountIn,
path
);
return prices;
}
//每个eth可获得的奖励
function rewardPerEth(address[] memory tokenList, uint256[] memory prices, uint256[] memory amountsIn)
public
override
view
returns (uint256)
{
uint256 totalETH = totalETHSupply(tokenList, prices, amountsIn);
if (totalETH == 0) {
return 0;
}
return
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(ethRewardRate)
.mul(1e18)
.div(totalETH);
}
//获取该币种换算成eth的市值
function getTokenValueForEth(address token)
external
override
view
returns (uint256)
{
uint256[] memory price = forEthPrice(token);
uint256 totalValue = price[1].mul(_totalTokenSupply[token]).div(price[0]);
return totalValue;
}
//结算奖励
function earned(address account, address[] memory tokenList, uint256[] memory amountsIn)
public
override
view
returns (uint256)
{
uint256 reward = 0;
for (uint256 i = 0; i < tokenList.length; i++) {
if (_tokenBalances[tokenList[i]][account] > 0) {
reward = reward.add(
_tokenBalances[tokenList[i]][account]
.mul(
rewardPerTokenStored[tokenList[i]].sub(
_userRewardPerTokenPaid[account][tokenList[i]]
)
)
.div(amountsIn[i])
);
}
}
return reward;
}
function estimateReward(address user, address token) external view returns(uint256){
address[] memory tokenList = IStakingElection(stakingElectionAddr)
.stakingTokensList();
uint256[] memory amountsIn = new uint256[](tokenList.length);
uint256[] memory prices = new uint256[](tokenList.length);
for (uint256 i = 0; i < tokenList.length; i++) {
uint256[] memory price = forEthPrice(tokenList[i]);
amountsIn[i] = price[0];
prices[i] = price[1];
}
uint256 _rewardPerEth = rewardPerEth(tokenList, prices, amountsIn);
uint256[] memory curRewardPerToken = new uint256[](tokenList.length);
for (uint256 i = 0; i < tokenList.length; i++) {
curRewardPerToken[i] = rewardPerTokenStored[tokenList[i]]
.add(prices[i].mul(_rewardPerEth).div(1e18));
}
return calculation(tokenList, amountsIn, curRewardPerToken, user, token);
}
function calculation(address[] memory tokenList, uint256[] memory amountsIn, uint256[] memory curRewardPerToken, address user, address token) public view returns(uint256){
uint256 reward;
for (uint256 i = 0; i < tokenList.length; i++) {
if (_tokenBalances[tokenList[i]][user] > 0) {
if(token == address(0)){
reward = reward.add(
_tokenBalances[tokenList[i]][user]
.mul(
curRewardPerToken[i].sub(
_userRewardPerTokenPaid[user][tokenList[i]]
)
).div(amountsIn[i])
);
}else{
if(token == tokenList[i]){
reward = reward.add(
_tokenBalances[tokenList[i]][user]
.mul(
curRewardPerToken[i].sub(
_userRewardPerTokenPaid[user][tokenList[i]]
)
).div(amountsIn[i])
);
}
}
}
}
return reward;
}
function setRewardPoolAddress(address _address) external onlyRewardsDistribution{
rewardPoolAddress = _address;
emit SetRewardPoolAddress(msg.sender, _address);
}
function userRewardPerTokenPaid(address user, address token)
external
view
returns (uint256)
{
return _userRewardPerTokenPaid[user][token];
}
/* ========== EVENTS ========== */
event Staked(address indexed user, address indexed token, uint256 amount);
event Withdrawn(
address indexed user,
address indexed token,
uint256 amount,
address recipient
);
event RewardPaid(address indexed user, uint256 reward);
event Start(uint256 reward, uint256 round);
event SetRewardAddress(
address indexed user,
uint256 rewardKey,
address rwardAddress
);
event SetOfficialAddress(address indexed user, address officialAddress);
event SetCommunityOperationAddress(
address indexed user,
address communityOperationAddress
);
event SetRewardPoolAddress(
address indexed user,
address rewardPoolAddress
);
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "istanbul",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.