file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/1/0x434bAc5efbE635d1bA4284Cf9Fb0938c489C468F/sources/contracts/dependencies/yoga-labs/ApeCoinStaking.sol | return The amount of ApeCoin rewards to be distributed by pool for a given time range _poolId Available pool values 0-3 _from Whole hour timestamp representation _to Whole hour timestamp representation/ | function rewardsBy(uint256 _poolId, uint256 _from, uint256 _to) public view returns (uint256, uint256) {
Pool memory pool = pools[_poolId];
if(_to < pool.timeRanges[0].startTimestampHour) return (0, pool.lastRewardsRangeIndex);
uint256 currentIndex = pool.lastRewardsRangeIndex;
while(_from > pool.timeRanges[currentIndex].endTimestampHour && _to > pool.timeRanges[currentIndex].endTimestampHour) {
++currentIndex;
}
uint256 rewards;
for(uint256 i = currentIndex; i < pool.timeRanges.length; ++i) {
TimeRange memory current = pool.timeRanges[i];
uint256 startTimestampHour = _from <= current.startTimestampHour ? current.startTimestampHour : _from;
uint256 endTimestampHour = _to <= current.endTimestampHour ? _to : current.endTimestampHour;
rewards = rewards + (endTimestampHour - startTimestampHour) * current.rewardsPerHour / SECONDS_PER_HOUR;
if(_to <= endTimestampHour) {
return (rewards, i);
}
}
return (rewards, pool.timeRanges.length - 1);
}
| 8,328,354 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/// @title Friendship contract
/// @author Mauro Molinari
/// @notice This contract can be use to keep track of friend requests and friends of its users
/// @dev Friend requests and Friends structs contains the pubKey used by Textile to talk with each other in the app
contract Friends is Ownable, Pausable {
// Friend request struct containing the sender address with the associated pubKey used by Textile
struct FriendRequest {
address sender;
string pubKey;
}
// Friend struct containing the dweller address with the associated pubKey used by Textile
struct Friend {
address dweller;
string pubKey;
}
// Constant kept to clear previous requests or friends
uint MAX_UINT = 2**256 - 1;
// All friend requests received by an address
mapping(address => FriendRequest[]) private requests;
// Tracks the index of each friend request inside the mapping
mapping(address => mapping(address => uint)) private requestsTracker;
// All friends that an address has
mapping(address => Friend[]) private friends;
// Tracks the index of each Friend inside the mapping
mapping(address => mapping(address => uint)) private friendsTracker;
/// @notice Request sent event
/// @param to Receiver of the request
event FriendRequestSent(address indexed to);
/// @notice Request accepted event
/// @param from Original sender of the request
event FriendRequestAccepted(address indexed from);
/// @notice Request denied event
/// @param from Original sender of the request
event FriendRequestDenied(address indexed from);
/// @notice Request removed event
/// @param to Receiver of the request
event FriendRequestRemoved(address indexed to);
/// @notice Friend removed event
/// @param friendRemoved Friend removed
event FriendRemoved(address indexed friendRemoved);
/// @notice Returns a friend from the friends mapping
/// @param _from From friend address
/// @param _toGet To friend address
/// @return fr Friend from the mapping
function _getFriend(address _from, address _toGet) private view returns (Friend memory fr) {
uint index = friendsTracker[_from][_toGet];
require(index != 0, "Friend does not exist");
return friends[_from][index - 1];
}
/// @notice Adds a friend to the friends mapping
/// @param _to To friend address
/// @param fr Friend to add
function _addFriend(address _to, Friend memory fr) private {
friends[_to].push(fr);
uint index = friends[_to].length;
friendsTracker[_to][fr.dweller] = index;
}
/// @notice Removes a friend from the friends mapping
/// @param _from From friend address
/// @param _toRemove To remove friend address
function _removeFriend(address _from, address _toRemove) private {
require(friends[_from].length > 0, "There are no friends to remove");
// Index of the element to remove
uint index = friendsTracker[_from][_toRemove] - 1;
uint lastIndex = friends[_from].length - 1;
if(index != lastIndex){
// Last friend inside the array
Friend memory last = friends[_from][lastIndex];
// Change the last with the element to remove
friends[_from][index] = last;
// Update the Index
friendsTracker[_from][last.dweller] = index + 1;
}
// Clear the previous index by setting the maximum integer
friendsTracker[_from][_toRemove] = MAX_UINT;
// Reduce the size of the array by 1
friends[_from].pop();
}
/// @notice Returns a friend request from the requests mapping
/// @param _from From friend address
/// @param _toGet To friend address
/// @return fr FriendRequest from the mapping
function _getRequest(address _from, address _toGet) private view returns (FriendRequest memory fr) {
uint index = requestsTracker[_from][_toGet];
require(index != 0, "Request does not exist");
return requests[_from][index];
}
/// @notice Adds a friend request to the requests mapping
/// @param _to To friend address
/// @param _from From friend address
function _addRequest(address _to, FriendRequest memory _from) private {
requests[_to].push(_from);
uint index = requests[_to].length;
requestsTracker[_to][_from.sender] = index;
requestsTracker[_from.sender][_to] = index;
}
/// @notice Removes a friend request from the requests mapping
/// @param _from From friend address
/// @param _toRemove To remove friend address
function _removeRequest(address _from, address _toRemove) private {
require(requests[_from].length > 0, "There are no requests to remove");
// Index of the element to remove
uint index = requestsTracker[_from][_toRemove] - 1;
uint lastIndex = requests[_from].length - 1;
if(index != lastIndex){
// Last friend inside the array
FriendRequest memory last = requests[_from][lastIndex];
// Change the last with the element to remove
requests[_from][index] = last;
// Update the Index
requestsTracker[_from][last.sender] = index + 1;
}
// Clear the previous index by setting the maximum integer
requestsTracker[_from][_toRemove] = MAX_UINT;
requestsTracker[_toRemove][_from] = MAX_UINT;
// Reduce the size of the array by 1
requests[_from].pop();
}
/// @notice Add a new friend request to the mapping
/// @param _to To friend address
/// @param _pubKey PubKey associated with the request
function makeRequest(address _to, string memory _pubKey) public whenNotPaused {
uint index = requestsTracker[_to][msg.sender];
require(msg.sender != _to, "You cannot send a friend request to yourself");
// You have already sent a friend request to this address
require(index == 0 || index == MAX_UINT, "Friend request already sent");
// You have already received a friend request from this address
require(requestsTracker[msg.sender][_to] == 0 || requestsTracker[msg.sender][_to] == MAX_UINT, "Friend request already sent");
// Must not be friend
require(friendsTracker[msg.sender][_to] == 0 || friendsTracker[msg.sender][_to] == MAX_UINT, "You are already friends");
_addRequest(
_to,
FriendRequest(msg.sender, _pubKey)
);
emit FriendRequestSent(_to);
}
/// @notice Accept a friend request
/// @param _from From friend address
/// @param pubKey PubKey associated with the request
function acceptRequest(address _from, string memory pubKey) public whenNotPaused {
uint friendRequestIndex = requestsTracker[msg.sender][_from];
// Check if the friend request has already been removed
require(friendRequestIndex != MAX_UINT, "Friend request has been removed");
// Check if the request exist
FriendRequest memory friendRequest = requests[msg.sender][friendRequestIndex - 1];
require(friendRequest.sender != address(0), "Request does not exist");
Friend memory senderFriend = Friend(
_from,
friendRequest.pubKey
);
Friend memory receiverFriend = Friend(
msg.sender,
pubKey
);
_removeRequest(msg.sender, friendRequest.sender);
_addFriend(msg.sender, senderFriend);
_addFriend(friendRequest.sender, receiverFriend);
emit FriendRequestAccepted(_from);
}
/// @notice Deny a friend request
/// @param _from From friend address
function denyRequest(address _from) public whenNotPaused {
uint friendRequestIndex = requestsTracker[msg.sender][_from];
// Check if the friend request exist
require(friendRequestIndex != 0, "Friend request does not exist");
// Check if the friend request has already been removed
require(friendRequestIndex != MAX_UINT, "Friend request has been removed");
_removeRequest(msg.sender, _from);
emit FriendRequestDenied(_from);
}
/// @notice Remove a friend request from the mapping
/// @param to To friend address
function removeRequest(address to) public whenNotPaused {
uint index = requestsTracker[to][msg.sender];
require(index != 0, "Friend request does not exist");
_removeRequest(to, msg.sender);
emit FriendRequestRemoved(to);
}
/// @notice Remove a friend from the mapping
/// @param _toRemove To friend address
function removeFriend(address _toRemove) public whenNotPaused {
uint index = friendsTracker[msg.sender][_toRemove];
require(index != 0, "Friend does not exist");
_removeFriend(msg.sender, _toRemove);
_removeFriend(_toRemove, msg.sender);
emit FriendRemoved(_toRemove);
}
/// @notice Returns the friends list related to the msg.sender
/// @return Friends mapping related
function getFriends() public view returns (Friend[] memory) {
return friends[msg.sender];
}
/// @notice Returns the requests list directed to the msg.sender
/// @return Friends requests mapping related
function getRequests() public view returns (FriendRequest[] memory) {
return requests[msg.sender];
}
/// @notice Pause the contract
/// @dev Only the owner can pause the contract
function pauseContract() public onlyOwner whenNotPaused {
_pause();
}
/// @notice Unpause the contract
/// @dev Only the owner can unpause the contract
function unpauseContract() public onlyOwner whenPaused {
_unpause();
}
} | Unpause the contract Only the owner can unpause the contract | function unpauseContract() public onlyOwner whenPaused {
_unpause();
}
| 12,810,994 |
./partial_match/1/0xeC331cBcF9c1C76825FA7CE45a987b80b7689195/sources/Governance.sol | save return variables | function getVoteCount(address _staker) public view returns(uint256) {
uint256 currentTotalVotes = stakerVotes[_staker].totalVotes;
uint256 newTotalVotes;
uint256 dNyan;
uint256 rewards;
uint256 blockChecked;
uint256 blockStaked;
(newTotalVotes,dNyan, rewards, blockChecked, blockStaked) = nyanV2.userStake(_staker);
uint256 votesUsed = stakerVotes[_staker].currentVotesUsed;
if (!stakerVotes[_staker].votesInitialized || block.number.sub(stakerVotes[_staker].lastBlockChecked) > 6500) {
return newTotalVotes;
return currentTotalVotes.sub(votesUsed);
}
}
| 2,881,820 |
/*
* Origin Protocol
* https://originprotocol.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
*
* Copyright 2020 Origin Protocol, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
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.5.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.
*
* _Available since v2.4.0._
*/
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.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
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.
*
* _Available since v2.4.0._
*/
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.5.5;
/**
* @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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @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].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.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 ERC20;` 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));
}
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.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "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/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/interfaces/IStrategy.sol
pragma solidity 0.5.11;
/**
* @title Platform interface to integrate with lending platform like Compound, AAVE etc.
*/
interface IStrategy {
/**
* @dev Deposit the given asset to platform
* @param _asset asset address
* @param _amount Amount to deposit
*/
function deposit(address _asset, uint256 _amount) external;
/**
* @dev Deposit the entire balance of all supported assets in the Strategy
* to the platform
*/
function depositAll() external;
/**
* @dev Withdraw given asset from Lending platform
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external;
/**
* @dev Liquidate all assets in strategy and return them to Vault.
*/
function withdrawAll() external;
/**
* @dev Returns the current balance of the given asset.
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Returns bool indicating whether strategy supports asset.
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Collect reward tokens from the Strategy.
*/
function collectRewardToken() external;
/**
* @dev The address of the reward token for the Strategy.
*/
function rewardTokenAddress() external pure returns (address);
/**
* @dev The threshold (denominated in the reward token) over which the
* vault will auto harvest on allocate calls.
*/
function rewardLiquidationThreshold() external pure returns (uint256);
}
// File: contracts/governance/Governable.sol
pragma solidity 0.5.11;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
// keccak256("OUSD.governor");
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
// keccak256("OUSD.pending.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
// keccak256("OUSD.reentry.status");
bytes32
private constant reentryStatusPosition = 0x53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac4535;
// See OpenZeppelin ReentrancyGuard implementation
uint256 constant _NOT_ENTERED = 1;
uint256 constant _ENTERED = 2;
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
/**
* @dev Returns the address of the current Governor.
*/
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
/**
* @dev Returns the address of the pending Governor.
*/
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @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() {
bytes32 position = reentryStatusPosition;
uint256 _reentry_status;
assembly {
_reentry_status := sload(position)
}
// On the first call to nonReentrant, _notEntered will be true
require(_reentry_status != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
assembly {
sstore(position, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(position, _NOT_ENTERED)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// File: contracts/utils/InitializableERC20Detailed.sol
pragma solidity 0.5.11;
/**
* @dev Optional functions from the ERC20 standard.
* Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
*/
contract InitializableERC20Detailed is IERC20 {
// Storage gap to skip storage from prior to OUSD reset
uint256[100] private _____gap;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/utils/StableMath.sol
pragma solidity 0.5.11;
// Based on StableMath from Stability Labs Pty. Ltd.
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/***************************************
Helpers
****************************************/
/**
* @dev Adjust the scale of an integer
* @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17
*/
function scaleBy(uint256 x, int8 adjustment)
internal
pure
returns (uint256)
{
if (adjustment > 0) {
x = x.mul(10**uint256(adjustment));
} else if (adjustment < 0) {
x = x.div(10**uint256(adjustment * -1));
}
return x;
}
/***************************************
Precise Arithmetic
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
}
// File: contracts/token/OUSD.sol
pragma solidity 0.5.11;
/**
* @title OUSD Token Contract
* @dev ERC20 compatible contract for OUSD
* @dev Implements an elastic supply
* @author Origin Protocol Inc
*/
/**
* NOTE that this is an ERC20 token but the invariant that the sum of
* balanceOf(x) for all x is not >= totalSupply(). This is a consequence of the
* rebasing design. Any integrations with OUSD should be aware.
*/
contract OUSD is Initializable, InitializableERC20Detailed, Governable {
using SafeMath for uint256;
using StableMath for uint256;
event TotalSupplyUpdated(
uint256 totalSupply,
uint256 rebasingCredits,
uint256 rebasingCreditsPerToken
);
enum RebaseOptions { NotSet, OptOut, OptIn }
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 public _totalSupply;
mapping(address => mapping(address => uint256)) private _allowances;
address public vaultAddress = address(0);
mapping(address => uint256) private _creditBalances;
uint256 public rebasingCredits;
uint256 public rebasingCreditsPerToken;
// Frozen address/credits are non rebasing (value is held in contracts which
// do not receive yield unless they explicitly opt in)
uint256 public nonRebasingSupply;
mapping(address => uint256) public nonRebasingCreditsPerToken;
mapping(address => RebaseOptions) public rebaseState;
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _vaultAddress
) external onlyGovernor initializer {
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
rebasingCreditsPerToken = 1e18;
vaultAddress = _vaultAddress;
}
/**
* @dev Verifies that the caller is the Savings Manager contract
*/
modifier onlyVault() {
require(vaultAddress == msg.sender, "Caller is not the Vault");
_;
}
/**
* @return The total supply of OUSD.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param _account Address to query the balance of.
* @return A uint256 representing the _amount of base units owned by the
* specified address.
*/
function balanceOf(address _account) public view returns (uint256) {
if (_creditBalances[_account] == 0) return 0;
return
_creditBalances[_account].divPrecisely(_creditsPerToken(_account));
}
/**
* @dev Gets the credits balance of the specified address.
* @param _account The address to query the balance of.
* @return (uint256, uint256) Credit balance and credits per token of the
* address
*/
function creditsBalanceOf(address _account)
public
view
returns (uint256, uint256)
{
return (_creditBalances[_account], _creditsPerToken(_account));
}
/**
* @dev Transfer tokens to a specified address.
* @param _to the address to transfer to.
* @param _value the _amount to be transferred.
* @return true on success.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(
_value <= balanceOf(msg.sender),
"Transfer greater than balance"
);
_executeTransfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value The _amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(_value <= balanceOf(_from), "Transfer greater than balance");
_allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(
_value
);
_executeTransfer(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Update the count of non rebasing credits in response to a transfer
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value Amount of OUSD to transfer
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value
) internal {
bool isNonRebasingTo = _isNonRebasingAccount(_to);
bool isNonRebasingFrom = _isNonRebasingAccount(_from);
// Credits deducted and credited might be different due to the
// differing creditsPerToken used by each account
uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to));
uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from));
_creditBalances[_from] = _creditBalances[_from].sub(
creditsDeducted,
"Transfer amount exceeds balance"
);
_creditBalances[_to] = _creditBalances[_to].add(creditsCredited);
if (isNonRebasingTo && !isNonRebasingFrom) {
// Transfer to non-rebasing account from rebasing account, credits
// are removed from the non rebasing tally
nonRebasingSupply = nonRebasingSupply.add(_value);
// Update rebasingCredits by subtracting the deducted amount
rebasingCredits = rebasingCredits.sub(creditsDeducted);
} else if (!isNonRebasingTo && isNonRebasingFrom) {
// Transfer to rebasing account from non-rebasing account
// Decreasing non-rebasing credits by the amount that was sent
nonRebasingSupply = nonRebasingSupply.sub(_value);
// Update rebasingCredits by adding the credited amount
rebasingCredits = rebasingCredits.add(creditsCredited);
}
}
/**
* @dev Function to check the _amount of tokens that an owner has allowed to a _spender.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return The number of tokens still available for the _spender.
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @dev Approve the passed address to spend the specified _amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param _spender The address which will spend the funds.
* @param _value The _amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
_allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the _amount of tokens that an owner has allowed to a _spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param _spender The address which will spend the funds.
* @param _addedValue The _amount of tokens to increase the allowance by.
*/
function increaseAllowance(address _spender, uint256 _addedValue)
public
returns (bool)
{
_allowances[msg.sender][_spender] = _allowances[msg.sender][_spender]
.add(_addedValue);
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the _amount of tokens that an owner has allowed to a _spender.
* @param _spender The address which will spend the funds.
* @param _subtractedValue The _amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue)
public
returns (bool)
{
uint256 oldValue = _allowances[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
_allowances[msg.sender][_spender] = 0;
} else {
_allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Mints new tokens, increasing totalSupply.
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _amount);
}
/**
* @dev Creates `_amount` tokens and assigns them to `_account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address _account, uint256 _amount) internal nonReentrant {
require(_account != address(0), "Mint to the zero address");
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
_creditBalances[_account] = _creditBalances[_account].add(creditAmount);
// If the account is non rebasing and doesn't have a set creditsPerToken
// then set it i.e. this is a mint from a fresh contract
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.add(_amount);
} else {
rebasingCredits = rebasingCredits.add(creditAmount);
}
_totalSupply = _totalSupply.add(_amount);
require(_totalSupply < MAX_SUPPLY, "Max supply");
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Burns tokens, decreasing totalSupply.
*/
function burn(address account, uint256 amount) external onlyVault {
_burn(account, amount);
}
/**
* @dev Destroys `_amount` tokens from `_account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `_account` cannot be the zero address.
* - `_account` must have at least `_amount` tokens.
*/
function _burn(address _account, uint256 _amount) internal nonReentrant {
require(_account != address(0), "Burn from the zero address");
if (_amount == 0) {
return;
}
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
uint256 currentCredits = _creditBalances[_account];
// Remove the credits, burning rounding errors
if (
currentCredits == creditAmount || currentCredits - 1 == creditAmount
) {
// Handle dust from rounding
_creditBalances[_account] = 0;
} else if (currentCredits > creditAmount) {
_creditBalances[_account] = _creditBalances[_account].sub(
creditAmount
);
} else {
revert("Remove exceeds balance");
}
// Remove from the credit tallies and non-rebasing supply
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.sub(_amount);
} else {
rebasingCredits = rebasingCredits.sub(creditAmount);
}
_totalSupply = _totalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Get the credits per token for an account. Returns a fixed amount
* if the account is non-rebasing.
* @param _account Address of the account.
*/
function _creditsPerToken(address _account)
internal
view
returns (uint256)
{
if (nonRebasingCreditsPerToken[_account] != 0) {
return nonRebasingCreditsPerToken[_account];
} else {
return rebasingCreditsPerToken;
}
}
/**
* @dev Is an account using rebasing accounting or non-rebasing accounting?
* Also, ensure contracts are non-rebasing if they have not opted in.
* @param _account Address of the account.
*/
function _isNonRebasingAccount(address _account) internal returns (bool) {
bool isContract = Address.isContract(_account);
if (isContract && rebaseState[_account] == RebaseOptions.NotSet) {
_ensureRebasingMigration(_account);
}
return nonRebasingCreditsPerToken[_account] > 0;
}
/**
* @dev Ensures internal account for rebasing and non-rebasing credits and
* supply is updated following deployment of frozen yield change.
*/
function _ensureRebasingMigration(address _account) internal {
if (nonRebasingCreditsPerToken[_account] == 0) {
// Set fixed credits per token for this account
nonRebasingCreditsPerToken[_account] = rebasingCreditsPerToken;
// Update non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(_account));
// Update credit tallies
rebasingCredits = rebasingCredits.sub(_creditBalances[_account]);
}
}
/**
* @dev Add a contract address to the non rebasing exception list. I.e. the
* address's balance will be part of rebases so the account will be exposed
* to upside and downside.
*/
function rebaseOptIn() public nonReentrant {
require(_isNonRebasingAccount(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
// Decreasing non rebasing supply
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
_creditBalances[msg.sender] = newCreditBalance;
// Increase rebasing credits, totalSupply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.add(_creditBalances[msg.sender]);
rebaseState[msg.sender] = RebaseOptions.OptIn;
// Delete any fixed credits per token
delete nonRebasingCreditsPerToken[msg.sender];
}
/**
* @dev Remove a contract address to the non rebasing exception list.
*/
function rebaseOptOut() public nonReentrant {
require(!_isNonRebasingAccount(msg.sender), "Account has not opted in");
// Increase non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender));
// Set fixed credits per token
nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken;
// Decrease rebasing credits, total supply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.sub(_creditBalances[msg.sender]);
// Mark explicitly opted out of rebasing
rebaseState[msg.sender] = RebaseOptions.OptOut;
}
/**
* @dev Modify the supply without minting new tokens. This uses a change in
* the exchange rate between "credits" and OUSD tokens to change balances.
* @param _newTotalSupply New total supply of OUSD.
* @return uint256 representing the new total supply.
*/
function changeSupply(uint256 _newTotalSupply)
external
onlyVault
nonReentrant
{
require(_totalSupply > 0, "Cannot increase 0 supply");
if (_totalSupply == _newTotalSupply) {
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return;
}
_totalSupply = _newTotalSupply > MAX_SUPPLY
? MAX_SUPPLY
: _newTotalSupply;
rebasingCreditsPerToken = rebasingCredits.divPrecisely(
_totalSupply.sub(nonRebasingSupply)
);
require(rebasingCreditsPerToken > 0, "Invalid change in supply");
_totalSupply = rebasingCredits
.divPrecisely(rebasingCreditsPerToken)
.add(nonRebasingSupply);
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
}
}
// File: contracts/interfaces/IBasicToken.sol
pragma solidity 0.5.11;
interface IBasicToken {
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/utils/Helpers.sol
pragma solidity 0.5.11;
library Helpers {
/**
* @notice Fetch the `symbol()` from an ERC20 token
* @dev Grabs the `symbol()` from a contract
* @param _token Address of the ERC20 token
* @return string Symbol of the ERC20 token
*/
function getSymbol(address _token) internal view returns (string memory) {
string memory symbol = IBasicToken(_token).symbol();
return symbol;
}
/**
* @notice Fetch the `decimals()` from an ERC20 token
* @dev Grabs the `decimals()` from a contract and fails if
* the decimal value does not live within a certain range
* @param _token Address of the ERC20 token
* @return uint256 Decimals of the ERC20 token
*/
function getDecimals(address _token) internal view returns (uint256) {
uint256 decimals = IBasicToken(_token).decimals();
require(
decimals >= 4 && decimals <= 18,
"Token must have sufficient decimal places"
);
return decimals;
}
}
// File: contracts/vault/VaultStorage.sol
pragma solidity 0.5.11;
/**
* @title OUSD VaultStorage Contract
* @notice The VaultStorage contract defines the storage for the Vault contracts
* @author Origin Protocol Inc
*/
contract VaultStorage is Initializable, Governable {
using SafeMath for uint256;
using StableMath for uint256;
using SafeMath for int256;
using SafeERC20 for IERC20;
event AssetSupported(address _asset);
event AssetDefaultStrategyUpdated(address _asset, address _strategy);
event StrategyApproved(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event CapitalPaused();
event CapitalUnpaused();
event RebasePaused();
event RebaseUnpaused();
event VaultBufferUpdated(uint256 _vaultBuffer);
event RedeemFeeUpdated(uint256 _redeemFeeBps);
event PriceProviderUpdated(address _priceProvider);
event AllocateThresholdUpdated(uint256 _threshold);
event RebaseThresholdUpdated(uint256 _threshold);
event UniswapUpdated(address _address);
event StrategistUpdated(address _address);
event MaxSupplyDiffChanged(uint256 maxSupplyDiff);
event YieldDistribution(address _to, uint256 _yield, uint256 _fee);
event TrusteeFeeBpsChanged(uint256 _basis);
event TrusteeAddressChanged(address _address);
// Assets supported by the Vault, i.e. Stablecoins
struct Asset {
bool isSupported;
}
mapping(address => Asset) assets;
address[] allAssets;
// Strategies approved for use by the Vault
struct Strategy {
bool isSupported;
uint256 _deprecated; // Deprecated storage slot
}
mapping(address => Strategy) strategies;
address[] allStrategies;
// Address of the Oracle price provider contract
address public priceProvider;
// Pausing bools
bool public rebasePaused = false;
bool public capitalPaused = true;
// Redemption fee in basis points
uint256 public redeemFeeBps;
// Buffer of assets to keep in Vault to handle (most) withdrawals
uint256 public vaultBuffer;
// Mints over this amount automatically allocate funds. 18 decimals.
uint256 public autoAllocateThreshold;
// Mints over this amount automatically rebase. 18 decimals.
uint256 public rebaseThreshold;
OUSD oUSD;
//keccak256("OUSD.vault.governor.admin.impl");
bytes32 constant adminImplPosition = 0xa2bd3d3cf188a41358c8b401076eb59066b09dec5775650c0de4c55187d17bd9;
// Address of the contract responsible for post rebase syncs with AMMs
address private _deprecated_rebaseHooksAddr = address(0);
// Address of Uniswap
address public uniswapAddr = address(0);
// Address of the Strategist
address public strategistAddr = address(0);
// Mapping of asset address to the Strategy that they should automatically
// be allocated to
mapping(address => address) public assetDefaultStrategies;
uint256 public maxSupplyDiff;
// Trustee address that can collect a percentage of yield
address public trusteeAddress;
// Amount of yield collected in basis points
uint256 public trusteeFeeBps;
/**
* @dev set the implementation for the admin, this needs to be in a base class else we cannot set it
* @param newImpl address of the implementation
*/
function setAdminImpl(address newImpl) external onlyGovernor {
require(
Address.isContract(newImpl),
"new implementation is not a contract"
);
bytes32 position = adminImplPosition;
assembly {
sstore(position, newImpl)
}
}
}
// File: contracts/interfaces/IMinMaxOracle.sol
pragma solidity 0.5.11;
interface IMinMaxOracle {
//Assuming 8 decimals
function priceMin(string calldata symbol) external view returns (uint256);
function priceMax(string calldata symbol) external view returns (uint256);
}
// File: contracts/interfaces/uniswap/IUniswapV2Router02.sol
pragma solidity 0.5.11;
interface IUniswapV2Router {
function WETH() external pure returns (address);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
}
// File: contracts/vault/VaultAdmin.sol
pragma solidity 0.5.11;
/**
* @title OUSD Vault Admin Contract
* @notice The VaultAdmin contract makes configuration and admin calls on the vault.
* @author Origin Protocol Inc
*/
contract VaultAdmin is VaultStorage {
/**
* @dev Verifies that the caller is the Vault, Governor, or Strategist.
*/
modifier onlyVaultOrGovernorOrStrategist() {
require(
msg.sender == address(this) ||
msg.sender == strategistAddr ||
isGovernor(),
"Caller is not the Vault, Governor, or Strategist"
);
_;
}
modifier onlyGovernorOrStrategist() {
require(
msg.sender == strategistAddr || isGovernor(),
"Caller is not the Strategist or Governor"
);
_;
}
/***************************************
Configuration
****************************************/
/**
* @dev Set address of price provider.
* @param _priceProvider Address of price provider
*/
function setPriceProvider(address _priceProvider) external onlyGovernor {
priceProvider = _priceProvider;
emit PriceProviderUpdated(_priceProvider);
}
/**
* @dev Set a fee in basis points to be charged for a redeem.
* @param _redeemFeeBps Basis point fee to be charged
*/
function setRedeemFeeBps(uint256 _redeemFeeBps) external onlyGovernor {
redeemFeeBps = _redeemFeeBps;
emit RedeemFeeUpdated(_redeemFeeBps);
}
/**
* @dev Set a buffer of assets to keep in the Vault to handle most
* redemptions without needing to spend gas unwinding assets from a Strategy.
* @param _vaultBuffer Percentage using 18 decimals. 100% = 1e18.
*/
function setVaultBuffer(uint256 _vaultBuffer) external onlyGovernor {
require(_vaultBuffer <= 1e18, "Invalid value");
vaultBuffer = _vaultBuffer;
emit VaultBufferUpdated(_vaultBuffer);
}
/**
* @dev Sets the minimum amount of OUSD in a mint to trigger an
* automatic allocation of funds afterwords.
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setAutoAllocateThreshold(uint256 _threshold)
external
onlyGovernor
{
autoAllocateThreshold = _threshold;
emit AllocateThresholdUpdated(_threshold);
}
/**
* @dev Set a minimum amount of OUSD in a mint or redeem that triggers a
* rebase
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setRebaseThreshold(uint256 _threshold) external onlyGovernor {
rebaseThreshold = _threshold;
emit RebaseThresholdUpdated(_threshold);
}
/**
* @dev Set address of Uniswap for performing liquidation of strategy reward
* tokens
* @param _address Address of Uniswap
*/
function setUniswapAddr(address _address) external onlyGovernor {
uniswapAddr = _address;
emit UniswapUpdated(_address);
}
/**
* @dev Set address of Strategist
* @param _address Address of Strategist
*/
function setStrategistAddr(address _address) external onlyGovernor {
strategistAddr = _address;
emit StrategistUpdated(_address);
}
/**
* @dev Set the default Strategy for an asset, i.e. the one which the asset
will be automatically allocated to and withdrawn from
* @param _asset Address of the asset
* @param _strategy Address of the Strategy
*/
function setAssetDefaultStrategy(address _asset, address _strategy)
external
onlyGovernorOrStrategist
{
emit AssetDefaultStrategyUpdated(_asset, _strategy);
require(strategies[_strategy].isSupported, "Strategy not approved");
IStrategy strategy = IStrategy(_strategy);
require(assets[_asset].isSupported, "Asset is not supported");
require(
strategy.supportsAsset(_asset),
"Asset not supported by Strategy"
);
assetDefaultStrategies[_asset] = _strategy;
}
/**
* @dev Add a supported asset to the contract, i.e. one that can be
* to mint OUSD.
* @param _asset Address of asset
*/
function supportAsset(address _asset) external onlyGovernor {
require(!assets[_asset].isSupported, "Asset already supported");
assets[_asset] = Asset({ isSupported: true });
allAssets.push(_asset);
emit AssetSupported(_asset);
}
/**
* @dev Add a strategy to the Vault.
* @param _addr Address of the strategy to add
*/
function approveStrategy(address _addr) external onlyGovernor {
require(!strategies[_addr].isSupported, "Strategy already approved");
strategies[_addr] = Strategy({ isSupported: true, _deprecated: 0 });
allStrategies.push(_addr);
emit StrategyApproved(_addr);
}
/**
* @dev Remove a strategy from the Vault. Removes all invested assets and
* returns them to the Vault.
* @param _addr Address of the strategy to remove
*/
function removeStrategy(address _addr) external onlyGovernor {
require(strategies[_addr].isSupported, "Strategy not approved");
// Initialize strategyIndex with out of bounds result so function will
// revert if no valid index found
uint256 strategyIndex = allStrategies.length;
for (uint256 i = 0; i < allStrategies.length; i++) {
if (allStrategies[i] == _addr) {
strategyIndex = i;
break;
}
}
if (strategyIndex < allStrategies.length) {
allStrategies[strategyIndex] = allStrategies[allStrategies.length -
1];
allStrategies.pop();
// Withdraw all assets
IStrategy strategy = IStrategy(_addr);
strategy.withdrawAll();
// Call harvest after withdraw in case withdraw triggers
// distribution of additional reward tokens (true for Compound)
_harvest(_addr);
emit StrategyRemoved(_addr);
}
// Clean up struct in mapping, this can be removed later
// See https://github.com/OriginProtocol/origin-dollar/issues/324
strategies[_addr].isSupported = false;
}
/**
* @notice Move assets from one Strategy to another
* @param _strategyFromAddress Address of Strategy to move assets from.
* @param _strategyToAddress Address of Strategy to move assets to.
* @param _assets Array of asset address that will be moved
* @param _amounts Array of amounts of each corresponding asset to move.
*/
function reallocate(
address _strategyFromAddress,
address _strategyToAddress,
address[] calldata _assets,
uint256[] calldata _amounts
) external onlyGovernorOrStrategist {
require(
strategies[_strategyFromAddress].isSupported,
"Invalid from Strategy"
);
require(
strategies[_strategyToAddress].isSupported,
"Invalid to Strategy"
);
require(_assets.length == _amounts.length, "Parameter length mismatch");
IStrategy strategyFrom = IStrategy(_strategyFromAddress);
IStrategy strategyTo = IStrategy(_strategyToAddress);
for (uint256 i = 0; i < _assets.length; i++) {
require(strategyTo.supportsAsset(_assets[i]), "Asset unsupported");
// Withdraw from Strategy and pass other Strategy as recipient
strategyFrom.withdraw(address(strategyTo), _assets[i], _amounts[i]);
}
// Tell new Strategy to deposit into protocol
strategyTo.depositAll();
}
/**
* @dev Sets the maximum allowable difference between
* total supply and backing assets' value.
*/
function setMaxSupplyDiff(uint256 _maxSupplyDiff) external onlyGovernor {
maxSupplyDiff = _maxSupplyDiff;
emit MaxSupplyDiffChanged(_maxSupplyDiff);
}
/**
* @dev Sets the trusteeAddress that can receive a portion of yield.
* Setting to the zero address disables this feature.
*/
function setTrusteeAddress(address _address) external onlyGovernor {
trusteeAddress = _address;
emit TrusteeAddressChanged(_address);
}
/**
* @dev Sets the TrusteeFeeBps to the percentage of yield that should be
* received in basis points.
*/
function setTrusteeFeeBps(uint256 _basis) external onlyGovernor {
require(_basis <= 5000, "basis cannot exceed 50%");
trusteeFeeBps = _basis;
emit TrusteeFeeBpsChanged(_basis);
}
/***************************************
Pause
****************************************/
/**
* @dev Set the deposit paused flag to true to prevent rebasing.
*/
function pauseRebase() external onlyGovernorOrStrategist {
rebasePaused = true;
emit RebasePaused();
}
/**
* @dev Set the deposit paused flag to true to allow rebasing.
*/
function unpauseRebase() external onlyGovernor {
rebasePaused = false;
emit RebaseUnpaused();
}
/**
* @dev Set the deposit paused flag to true to prevent capital movement.
*/
function pauseCapital() external onlyGovernorOrStrategist {
capitalPaused = true;
emit CapitalPaused();
}
/**
* @dev Set the deposit paused flag to false to enable capital movement.
*/
function unpauseCapital() external onlyGovernor {
capitalPaused = false;
emit CapitalUnpaused();
}
/***************************************
Rewards
****************************************/
/**
* @dev Transfer token to governor. Intended for recovering tokens stuck in
* contract, i.e. mistaken sends.
* @param _asset Address for the asset
* @param _amount Amount of the asset to transfer
*/
function transferToken(address _asset, uint256 _amount)
external
onlyGovernor
{
require(!assets[_asset].isSupported, "Only unsupported assets");
IERC20(_asset).safeTransfer(governor(), _amount);
}
/**
* @dev Collect reward tokens from all strategies and swap for supported
* stablecoin via Uniswap
*/
function harvest() external onlyGovernorOrStrategist {
for (uint256 i = 0; i < allStrategies.length; i++) {
_harvest(allStrategies[i]);
}
}
/**
* @dev Collect reward tokens for a specific strategy and swap for supported
* stablecoin via Uniswap. Called from the vault.
* @param _strategyAddr Address of the strategy to collect rewards from
*/
function harvest(address _strategyAddr)
external
onlyVaultOrGovernorOrStrategist
returns (uint256[] memory)
{
return _harvest(_strategyAddr);
}
/**
* @dev Collect reward tokens from a single strategy and swap them for a
* supported stablecoin via Uniswap
* @param _strategyAddr Address of the strategy to collect rewards from
*/
function _harvest(address _strategyAddr)
internal
returns (uint256[] memory)
{
IStrategy strategy = IStrategy(_strategyAddr);
address rewardTokenAddress = strategy.rewardTokenAddress();
if (rewardTokenAddress != address(0)) {
strategy.collectRewardToken();
if (uniswapAddr != address(0)) {
IERC20 rewardToken = IERC20(strategy.rewardTokenAddress());
uint256 rewardTokenAmount = rewardToken.balanceOf(
address(this)
);
if (rewardTokenAmount > 0) {
// Give Uniswap full amount allowance
rewardToken.safeApprove(uniswapAddr, 0);
rewardToken.safeApprove(uniswapAddr, rewardTokenAmount);
// Uniswap redemption path
address[] memory path = new address[](3);
path[0] = strategy.rewardTokenAddress();
path[1] = IUniswapV2Router(uniswapAddr).WETH();
path[2] = allAssets[1]; // USDT
return
IUniswapV2Router(uniswapAddr).swapExactTokensForTokens(
rewardTokenAmount,
uint256(0),
path,
address(this),
now.add(1800)
);
}
}
}
}
/***************************************
Pricing
****************************************/
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Min since min is what we use for mint pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function priceUSDMint(string calldata symbol)
external
view
returns (uint256)
{
return _priceUSDMint(symbol);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Min since min is what we use for mint pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function _priceUSDMint(string memory symbol)
internal
view
returns (uint256)
{
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return IMinMaxOracle(priceProvider).priceMin(symbol).scaleBy(10);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Max since max is what we use for redeem pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function priceUSDRedeem(string calldata symbol)
external
view
returns (uint256)
{
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return _priceUSDRedeem(symbol);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Max since max is what we use for redeem pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function _priceUSDRedeem(string memory symbol)
internal
view
returns (uint256)
{
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return IMinMaxOracle(priceProvider).priceMax(symbol).scaleBy(10);
}
}
| Update the count of non rebasing credits in response to a transfer _from The address you want to send tokens from. _to The address you want to transfer to. _value Amount of OUSD to transfer/ Credits deducted and credited might be different due to the differing creditsPerToken used by each account Transfer to non-rebasing account from rebasing account, credits are removed from the non rebasing tally Update rebasingCredits by subtracting the deducted amount Transfer to rebasing account from non-rebasing account Decreasing non-rebasing credits by the amount that was sent Update rebasingCredits by adding the credited amount | function _executeTransfer(
address _from,
address _to,
uint256 _value
) internal {
bool isNonRebasingTo = _isNonRebasingAccount(_to);
bool isNonRebasingFrom = _isNonRebasingAccount(_from);
uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to));
uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from));
_creditBalances[_from] = _creditBalances[_from].sub(
creditsDeducted,
"Transfer amount exceeds balance"
);
_creditBalances[_to] = _creditBalances[_to].add(creditsCredited);
if (isNonRebasingTo && !isNonRebasingFrom) {
nonRebasingSupply = nonRebasingSupply.add(_value);
rebasingCredits = rebasingCredits.sub(creditsDeducted);
nonRebasingSupply = nonRebasingSupply.sub(_value);
rebasingCredits = rebasingCredits.add(creditsCredited);
}
}
| 483,414 |
./partial_match/3/0x78eDA40ed2F86721871b3FE513147239c88ebD62/sources/lockToken.sol | get total SWAP token staked by pool id | function getTotalStakedByPoolId(uint256 _poolId) public view returns ( uint256 _totalStaked) {
return totalStakedByPoolId[_poolId];
}
| 5,175,455 |
./full_match/137/0x9E40a8A535D4875848e1821e3C59AB5C5dd86135/sources/contracts/core/connext/libraries/SwapUtils.sol | Calculate the price of a token in the pool with given precision-adjusted balances and a particular D. This is accomplished via solving the invariant iteratively. See the StableSwap paper and Curve.fi implementation for further details. x_12 + x1 (sum' - (Ann - 1) D / (A nn)) = D (n + 1) / (n (2 n) prod' A) x_12 + bx_1 = c x_1 = (x_12 + c) / (2x_1 + b) a the amplification coefficient n (n - 1). See the StableSwap paper for details. tokenIndex Index of token we are calculating for. xp a precision-adjusted set of pool balances. Array should be the same cardinality as the pool. d the stableswap invariant return the price of the token, in the same precision as in xp/ If we were to protect the division loss we would have to keep the denominator separate and divide at the end. However this leads to overflow with large numTokens or/and D. c = c D D D ... overflow! | function getYD(
uint256 a,
uint8 tokenIndex,
uint256[] memory xp,
uint256 d
) internal pure returns (uint256) {
uint256 numTokens = xp.length;
require(tokenIndex < numTokens, "Token not found");
uint256 c = d;
uint256 s;
uint256 nA = a * numTokens;
for (uint256 i; i < numTokens; ) {
if (i != tokenIndex) {
s += xp[i];
c = (c * d) / (xp[i] * numTokens);
}
unchecked {
++i;
}
}
c = (c * d * AmplificationUtils.A_PRECISION) / (nA * numTokens);
uint256 b = s + ((d * AmplificationUtils.A_PRECISION) / nA);
uint256 yPrev;
uint256 y = d;
for (uint256 i; i < MAX_LOOP_LIMIT; ) {
yPrev = y;
y = ((y * y) + c) / ((y * 2) + b - d);
if (y.within1(yPrev)) {
return y;
}
unchecked {
++i;
}
}
revert("Approximation did not converge");
}
| 4,795,423 |
/**
*Submitted for verification at Etherscan.io on 2021-12-05
*/
// Sources flattened with hardhat v2.6.2 https://hardhat.org
// File @openzeppelin/contracts/math/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 contracts/omnibridge/upgradeability/EternalStorage.sol
pragma solidity 0.7.5;
/**
* @title EternalStorage
* @dev This contract holds all the necessary state variables to carry out the storage of any contract.
*/
contract EternalStorage {
mapping(bytes32 => uint256) internal uintStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
}
// File contracts/omnibridge/upgradeable_contracts/Initializable.sol
pragma solidity 0.7.5;
contract Initializable is EternalStorage {
bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized"))
function setInitialize() internal {
boolStorage[INITIALIZED] = true;
}
function isInitialized() public view returns (bool) {
return boolStorage[INITIALIZED];
}
}
// File contracts/omnibridge/interfaces/IUpgradeabilityOwnerStorage.sol
pragma solidity 0.7.5;
interface IUpgradeabilityOwnerStorage {
function upgradeabilityOwner() external view returns (address);
}
// File contracts/omnibridge/upgradeable_contracts/Upgradeable.sol
pragma solidity 0.7.5;
contract Upgradeable {
/**
* @dev Throws if called by any account other than the upgradeability owner.
*/
modifier onlyIfUpgradeabilityOwner() {
_onlyIfUpgradeabilityOwner();
_;
}
/**
* @dev Internal function for reducing onlyIfUpgradeabilityOwner modifier bytecode overhead.
*/
function _onlyIfUpgradeabilityOwner() internal view {
require(msg.sender == IUpgradeabilityOwnerStorage(address(this)).upgradeabilityOwner());
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.7.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/utils/[email protected]
pragma solidity ^0.7.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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
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/[email protected]
pragma solidity ^0.7.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 contracts/omnibridge/upgradeable_contracts/Sacrifice.sol
pragma solidity 0.7.5;
contract Sacrifice {
constructor(address payable _recipient) payable {
selfdestruct(_recipient);
}
}
// File contracts/omnibridge/libraries/AddressHelper.sol
pragma solidity 0.7.5;
/**
* @title AddressHelper
* @dev Helper methods for Address type.
*/
library AddressHelper {
/**
* @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract
* @param _receiver address that will receive the native tokens
* @param _value the amount of native tokens to send
*/
function safeSendValue(address payable _receiver, uint256 _value) internal {
if (!(_receiver).send(_value)) {
new Sacrifice{ value: _value }(_receiver);
}
}
}
// File contracts/omnibridge/upgradeable_contracts/Claimable.sol
pragma solidity 0.7.5;
/**
* @title Claimable
* @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations.
*/
contract Claimable {
using SafeERC20 for IERC20;
/**
* Throws if a given address is equal to address(0)
*/
modifier validAddress(address _to) {
require(_to != address(0));
_;
}
/**
* @dev Withdraws the erc20 tokens or native coins from this contract.
* Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()).
* @param _token address of the claimed token or address(0) for native coins.
* @param _to address of the tokens/coins receiver.
*/
function claimValues(address _token, address _to) internal validAddress(_to) {
if (_token == address(0)) {
claimNativeCoins(_to);
} else {
claimErc20Tokens(_token, _to);
}
}
/**
* @dev Internal function for withdrawing all native coins from the contract.
* @param _to address of the coins receiver.
*/
function claimNativeCoins(address _to) internal {
uint256 value = address(this).balance;
AddressHelper.safeSendValue(payable(_to), value);
}
/**
* @dev Internal function for withdrawing all tokens of some particular ERC20 contract from this contract.
* @param _token address of the claimed ERC20 token.
* @param _to address of the tokens receiver.
*/
function claimErc20Tokens(address _token, address _to) internal {
IERC20 token = IERC20(_token);
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(_to, balance);
}
}
// File contracts/omnibridge/upgradeable_contracts/components/bridged/BridgedTokensRegistry.sol
pragma solidity 0.7.5;
/**
* @title BridgedTokensRegistry
* @dev Functionality for keeping track of registered bridged token pairs.
*/
contract BridgedTokensRegistry is EternalStorage {
event NewTokenRegistered(address indexed nativeToken, address indexed bridgedToken);
/**
* @dev Retrieves address of the bridged token contract associated with a specific native token contract on the other side.
* @param _nativeToken address of the native token contract on the other side.
* @return address of the deployed bridged token contract.
*/
function bridgedTokenAddress(address _nativeToken) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))];
}
/**
* @dev Retrieves address of the native token contract associated with a specific bridged token contract.
* @param _bridgedToken address of the created bridged token contract on this side.
* @return address of the native token contract on the other side of the bridge.
*/
function nativeTokenAddress(address _bridgedToken) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))];
}
/**
* @dev Internal function for updating a pair of addresses for the bridged token.
* @param _nativeToken address of the native token contract on the other side.
* @param _bridgedToken address of the created bridged token contract on this side.
*/
function _setTokenAddressPair(address _nativeToken, address _bridgedToken) internal {
addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))] = _bridgedToken;
addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))] = _nativeToken;
emit NewTokenRegistered(_nativeToken, _bridgedToken);
}
}
// File contracts/omnibridge/upgradeable_contracts/components/native/NativeTokensRegistry.sol
pragma solidity 0.7.5;
/**
* @title NativeTokensRegistry
* @dev Functionality for keeping track of registered native tokens.
*/
contract NativeTokensRegistry is EternalStorage {
/**
* @dev Checks if for a given native token, the deployment of its bridged alternative was already acknowledged.
* @param _token address of native token contract.
* @return true, if bridged token was already deployed.
*/
function isBridgedTokenDeployAcknowledged(address _token) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))];
}
/**
* @dev Acknowledges the deployment of bridged token contract on the other side.
* @param _token address of native token contract.
*/
function _ackBridgedTokenDeploy(address _token) internal {
if (!boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))]) {
boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))] = true;
}
}
}
// File contracts/omnibridge/upgradeable_contracts/components/native/MediatorBalanceStorage.sol
pragma solidity 0.7.5;
/**
* @title MediatorBalanceStorage
* @dev Functionality for storing expected mediator balance for native tokens.
*/
contract MediatorBalanceStorage is EternalStorage {
/**
* @dev Tells the expected token balance of the contract.
* @param _token address of token contract.
* @return the current tracked token balance of the contract.
*/
function mediatorBalance(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))];
}
/**
* @dev Updates expected token balance of the contract.
* @param _token address of token contract.
* @param _balance the new token balance of the contract.
*/
function _setMediatorBalance(address _token, uint256 _balance) internal {
uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))] = _balance;
}
}
// File contracts/omnibridge/interfaces/IERC677.sol
pragma solidity 0.7.5;
interface IERC677 is IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// File contracts/omnibridge/libraries/Bytes.sol
pragma solidity 0.7.5;
/**
* @title Bytes
* @dev Helper methods to transform bytes to other solidity types.
*/
library Bytes {
/**
* @dev Truncate bytes array if its size is more than 20 bytes.
* NOTE: This function does not perform any checks on the received parameter.
* Make sure that the _bytes argument has a correct length, not less than 20 bytes.
* A case when _bytes has length less than 20 will lead to the undefined behaviour,
* since assembly will read data from memory that is not related to the _bytes argument.
* @param _bytes to be converted to address type
* @return addr address included in the firsts 20 bytes of the bytes array in parameter.
*/
function bytesToAddress(bytes memory _bytes) internal pure returns (address addr) {
assembly {
addr := mload(add(_bytes, 20))
}
}
}
// File contracts/omnibridge/upgradeable_contracts/ReentrancyGuard.sol
pragma solidity 0.7.5;
contract ReentrancyGuard {
function lock() internal view returns (bool res) {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92) // keccak256(abi.encodePacked("lock"))
}
}
function setLock(bool _lock) internal {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock) // keccak256(abi.encodePacked("lock"))
}
}
}
// File contracts/omnibridge/upgradeable_contracts/Ownable.sol
pragma solidity 0.7.5;
/**
* @title Ownable
* @dev This contract has an owner address providing basic authorization control
*/
contract Ownable is EternalStorage {
bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner()
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_onlyOwner();
_;
}
/**
* @dev Internal function for reducing onlyOwner modifier bytecode overhead.
*/
function _onlyOwner() internal view {
require(msg.sender == owner());
}
/**
* @dev Throws if called through proxy by any account other than contract itself or an upgradeability owner.
*/
modifier onlyRelevantSender() {
(bool isProxy, bytes memory returnData) =
address(this).staticcall(abi.encodeWithSelector(UPGRADEABILITY_OWNER));
require(
!isProxy || // covers usage without calling through storage proxy
(returnData.length == 32 && msg.sender == abi.decode(returnData, (address))) || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
_;
}
bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner"))
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() public view returns (address) {
return addressStorage[OWNER];
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner the address to transfer ownership to.
*/
function transferOwnership(address newOwner) external onlyOwner {
_setOwner(newOwner);
}
/**
* @dev Sets a new owner address
*/
function _setOwner(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(owner(), newOwner);
addressStorage[OWNER] = newOwner;
}
}
// File contracts/omnibridge/interfaces/IAMB.sol
pragma solidity 0.7.5;
interface IAMB {
event UserRequestForAffirmation(bytes32 indexed messageId, bytes encodedData);
event UserRequestForSignature(bytes32 indexed messageId, bytes encodedData);
event AffirmationCompleted(
address indexed sender,
address indexed executor,
bytes32 indexed messageId,
bool status
);
event RelayedMessage(address indexed sender, address indexed executor, bytes32 indexed messageId, bool status);
function messageSender() external view returns (address);
function maxGasPerTx() external view returns (uint256);
function transactionHash() external view returns (bytes32);
function messageId() external view returns (bytes32);
function messageSourceChainId() external view returns (bytes32);
function messageCallStatus(bytes32 _messageId) external view returns (bool);
function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32);
function failedMessageReceiver(bytes32 _messageId) external view returns (address);
function failedMessageSender(bytes32 _messageId) external view returns (address);
function requireToPassMessage(
address _contract,
bytes calldata _data,
uint256 _gas
) external returns (bytes32);
function requireToConfirmMessage(
address _contract,
bytes calldata _data,
uint256 _gas
) external returns (bytes32);
function sourceChainId() external view returns (uint256);
function destinationChainId() external view returns (uint256);
}
// File contracts/omnibridge/upgradeable_contracts/BasicAMBMediator.sol
pragma solidity 0.7.5;
/**
* @title BasicAMBMediator
* @dev Basic storage and methods needed by mediators to interact with AMB bridge.
*/
abstract contract BasicAMBMediator is Ownable {
bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract"))
bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract"))
/**
* @dev Throws if caller on the other side is not an associated mediator.
*/
modifier onlyMediator {
_onlyMediator();
_;
}
/**
* @dev Internal function for reducing onlyMediator modifier bytecode overhead.
*/
function _onlyMediator() internal view {
IAMB bridge = bridgeContract();
require(msg.sender == address(bridge));
require(bridge.messageSender() == mediatorContractOnOtherSide());
}
/**
* @dev Sets the AMB bridge contract address. Only the owner can call this method.
* @param _bridgeContract the address of the bridge contract.
*/
function setBridgeContract(address _bridgeContract) external onlyOwner {
_setBridgeContract(_bridgeContract);
}
/**
* @dev Sets the mediator contract address from the other network. Only the owner can call this method.
* @param _mediatorContract the address of the mediator contract.
*/
function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner {
_setMediatorContractOnOtherSide(_mediatorContract);
}
/**
* @dev Get the AMB interface for the bridge contract address
* @return AMB interface for the bridge contract address
*/
function bridgeContract() public view returns (IAMB) {
return IAMB(addressStorage[BRIDGE_CONTRACT]);
}
/**
* @dev Tells the mediator contract address from the other network.
* @return the address of the mediator contract.
*/
function mediatorContractOnOtherSide() public view virtual returns (address) {
return addressStorage[MEDIATOR_CONTRACT];
}
/**
* @dev Stores a valid AMB bridge contract address.
* @param _bridgeContract the address of the bridge contract.
*/
function _setBridgeContract(address _bridgeContract) internal {
require(Address.isContract(_bridgeContract));
addressStorage[BRIDGE_CONTRACT] = _bridgeContract;
}
/**
* @dev Stores the mediator contract address from the other network.
* @param _mediatorContract the address of the mediator contract.
*/
function _setMediatorContractOnOtherSide(address _mediatorContract) internal {
addressStorage[MEDIATOR_CONTRACT] = _mediatorContract;
}
/**
* @dev Tells the id of the message originated on the other network.
* @return the id of the message originated on the other network.
*/
function messageId() internal view returns (bytes32) {
return bridgeContract().messageId();
}
/**
* @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network.
* @return the maximum gas limit value.
*/
function maxGasPerTx() internal view returns (uint256) {
return bridgeContract().maxGasPerTx();
}
function _passMessage(bytes memory _data, bool _useOracleLane) internal virtual returns (bytes32);
}
// File contracts/omnibridge/upgradeable_contracts/components/common/TokensRelayer.sol
pragma solidity 0.7.5;
/**
* @title TokensRelayer
* @dev Functionality for bridging multiple tokens to the other side of the bridge.
*/
abstract contract TokensRelayer is BasicAMBMediator, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC677;
/**
* @dev ERC677 transfer callback function.
* @param _from address of tokens sender.
* @param _value amount of transferred tokens.
* @param _data additional transfer data, can be used for passing alternative receiver address.
*/
function onTokenTransfer(
address _from,
uint256 _value,
bytes memory _data
) external returns (bool) {
if (!lock()) {
bytes memory data = new bytes(0);
address receiver = _from;
if (_data.length >= 20) {
receiver = Bytes.bytesToAddress(_data);
if (_data.length > 20) {
assembly {
let size := sub(mload(_data), 20)
data := add(_data, 20)
mstore(data, size)
}
}
}
bridgeSpecificActionsOnTokenTransfer(msg.sender, _from, receiver, _value, data);
}
return true;
}
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(
IERC677 token,
address _receiver,
uint256 _value
) external {
_relayTokens(token, _receiver, _value, new bytes(0));
}
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender to msg.sender on the other side.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(IERC677 token, uint256 _value) external {
_relayTokens(token, msg.sender, _value, new bytes(0));
}
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
* @param _data additional transfer data to be used on the other side.
*/
function relayTokensAndCall(
IERC677 token,
address _receiver,
uint256 _value,
bytes memory _data
) external {
_relayTokens(token, _receiver, _value, _data);
}
/**
* @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract
* and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network.
* The user should first call Approve method of the ERC677 token.
* @param token bridge token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
* @param _data additional transfer data to be used on the other side.
*/
function _relayTokens(
IERC677 token,
address _receiver,
uint256 _value,
bytes memory _data
) internal {
// This lock is to prevent calling passMessage twice if a ERC677 token is used.
// When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract
// which will call passMessage.
require(!lock());
uint256 balanceBefore = token.balanceOf(address(this));
setLock(true);
token.safeTransferFrom(msg.sender, address(this), _value);
setLock(false);
uint256 balanceDiff = token.balanceOf(address(this)).sub(balanceBefore);
require(balanceDiff <= _value);
bridgeSpecificActionsOnTokenTransfer(address(token), msg.sender, _receiver, balanceDiff, _data);
}
function bridgeSpecificActionsOnTokenTransfer(
address _token,
address _from,
address _receiver,
uint256 _value,
bytes memory _data
) internal virtual;
}
// File contracts/omnibridge/upgradeable_contracts/VersionableBridge.sol
pragma solidity 0.7.5;
interface VersionableBridge {
function getBridgeInterfacesVersion()
external
pure
returns (
uint64 major,
uint64 minor,
uint64 patch
);
function getBridgeMode() external pure returns (bytes4);
}
// File contracts/omnibridge/upgradeable_contracts/components/common/OmnibridgeInfo.sol
pragma solidity 0.7.5;
/**
* @title OmnibridgeInfo
* @dev Functionality for versioning Omnibridge mediator.
*/
contract OmnibridgeInfo is VersionableBridge {
event TokensBridgingInitiated(
address indexed token,
address indexed sender,
uint256 value,
bytes32 indexed messageId
);
event TokensBridged(address indexed token, address indexed recipient, uint256 value, bytes32 indexed messageId);
/**
* @dev Tells the bridge interface version that this contract supports.
* @return major value of the version
* @return minor value of the version
* @return patch value of the version
*/
function getBridgeInterfacesVersion()
external
pure
override
returns (
uint64 major,
uint64 minor,
uint64 patch
)
{
return (3, 3, 0);
}
/**
* @dev Tells the bridge mode that this contract supports.
* @return _data 4 bytes representing the bridge mode
*/
function getBridgeMode() external pure override returns (bytes4 _data) {
return 0xb1516c26; // bytes4(keccak256(abi.encodePacked("multi-erc-to-erc-amb")))
}
}
// File contracts/omnibridge/upgradeable_contracts/components/common/TokensBridgeLimits.sol
pragma solidity 0.7.5;
/**
* @title TokensBridgeLimits
* @dev Functionality for keeping track of bridging limits for multiple tokens.
*/
contract TokensBridgeLimits is EternalStorage, Ownable {
using SafeMath for uint256;
// token == 0x00..00 represents default limits (assuming decimals == 18) for all newly created tokens
event DailyLimitChanged(address indexed token, uint256 newLimit);
event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit);
/**
* @dev Checks if specified token was already bridged at least once.
* @param _token address of the token contract.
* @return true, if token address is address(0) or token was already bridged.
*/
function isTokenRegistered(address _token) public view returns (bool) {
return minPerTx(_token) > 0;
}
/**
* @dev Retrieves the total spent amount for particular token during specific day.
* @param _token address of the token contract.
* @param _day day number for which spent amount if requested.
* @return amount of tokens sent through the bridge to the other side.
*/
function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))];
}
/**
* @dev Retrieves the total executed amount for particular token during specific day.
* @param _token address of the token contract.
* @param _day day number for which spent amount if requested.
* @return amount of tokens received from the bridge from the other side.
*/
function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))];
}
/**
* @dev Retrieves current daily limit for a particular token contract.
* @param _token address of the token contract.
* @return daily limit on tokens that can be sent through the bridge per day.
*/
function dailyLimit(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))];
}
/**
* @dev Retrieves current execution daily limit for a particular token contract.
* @param _token address of the token contract.
* @return daily limit on tokens that can be received from the bridge on the other side per day.
*/
function executionDailyLimit(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))];
}
/**
* @dev Retrieves current maximum amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return maximum amount on tokens that can be sent through the bridge in one transfer.
*/
function maxPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))];
}
/**
* @dev Retrieves current maximum execution amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return maximum amount on tokens that can received from the bridge on the other side in one transaction.
*/
function executionMaxPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))];
}
/**
* @dev Retrieves current minimum amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return minimum amount on tokens that can be sent through the bridge in one transfer.
*/
function minPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("minPerTx", _token))];
}
/**
* @dev Checks that bridged amount of tokens conforms to the configured limits.
* @param _token address of the token contract.
* @param _amount amount of bridge tokens.
* @return true, if specified amount can be bridged.
*/
function withinLimit(address _token, uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalSpentPerDay(_token, getCurrentDay()).add(_amount);
return
dailyLimit(address(0)) > 0 &&
dailyLimit(_token) >= nextLimit &&
_amount <= maxPerTx(_token) &&
_amount >= minPerTx(_token);
}
/**
* @dev Checks that bridged amount of tokens conforms to the configured execution limits.
* @param _token address of the token contract.
* @param _amount amount of bridge tokens.
* @return true, if specified amount can be processed and executed.
*/
function withinExecutionLimit(address _token, uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalExecutedPerDay(_token, getCurrentDay()).add(_amount);
return
executionDailyLimit(address(0)) > 0 &&
executionDailyLimit(_token) >= nextLimit &&
_amount <= executionMaxPerTx(_token);
}
/**
* @dev Returns current day number.
* @return day number.
*/
function getCurrentDay() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp / 1 days;
}
/**
* @dev Updates daily limit for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the efault limit.
* @param _dailyLimit daily allowed amount of bridged tokens, should be greater than maxPerTx.
* 0 value is also allowed, will stop the bridge operations in outgoing direction.
*/
function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
require(isTokenRegistered(_token));
require(_dailyLimit > maxPerTx(_token) || _dailyLimit == 0);
uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit;
emit DailyLimitChanged(_token, _dailyLimit);
}
/**
* @dev Updates execution daily limit for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _dailyLimit daily allowed amount of executed tokens, should be greater than executionMaxPerTx.
* 0 value is also allowed, will stop the bridge operations in incoming direction.
*/
function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
require(isTokenRegistered(_token));
require(_dailyLimit > executionMaxPerTx(_token) || _dailyLimit == 0);
uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit;
emit ExecutionDailyLimitChanged(_token, _dailyLimit);
}
/**
* @dev Updates execution maximum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _maxPerTx maximum amount of executed tokens per one transaction, should be less than executionDailyLimit.
* 0 value is also allowed, will stop the bridge operations in incoming direction.
*/
function setExecutionMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > 0 && _maxPerTx < executionDailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _maxPerTx;
}
/**
* @dev Updates maximum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx.
* 0 value is also allowed, will stop the bridge operations in outgoing direction.
*/
function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx;
}
/**
* @dev Updates minimum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _minPerTx minimum amount of tokens per one transaction, should be less than maxPerTx and dailyLimit.
*/
function setMinPerTx(address _token, uint256 _minPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_minPerTx > 0 && _minPerTx < dailyLimit(_token) && _minPerTx < maxPerTx(_token));
uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _minPerTx;
}
/**
* @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters.
* @param _token address of the token contract, or address(0) for the default limit.
* @return minimum of maxPerTx parameter and remaining daily quota.
*/
function maxAvailablePerTx(address _token) public view returns (uint256) {
uint256 _maxPerTx = maxPerTx(_token);
uint256 _dailyLimit = dailyLimit(_token);
uint256 _spent = totalSpentPerDay(_token, getCurrentDay());
uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0;
return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily;
}
/**
* @dev Internal function for adding spent amount for some token.
* @param _token address of the token contract.
* @param _day day number, when tokens are processed.
* @param _value amount of bridge tokens.
*/
function addTotalSpentPerDay(
address _token,
uint256 _day,
uint256 _value
) internal {
uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))] = totalSpentPerDay(_token, _day).add(
_value
);
}
/**
* @dev Internal function for adding executed amount for some token.
* @param _token address of the token contract.
* @param _day day number, when tokens are processed.
* @param _value amount of bridge tokens.
*/
function addTotalExecutedPerDay(
address _token,
uint256 _day,
uint256 _value
) internal {
uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))] = totalExecutedPerDay(
_token,
_day
)
.add(_value);
}
/**
* @dev Internal function for initializing limits for some token.
* @param _token address of the token contract.
* @param _limits [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ].
*/
function _setLimits(address _token, uint256[3] memory _limits) internal {
require(
_limits[2] > 0 && // minPerTx > 0
_limits[1] > _limits[2] && // maxPerTx > minPerTx
_limits[0] > _limits[1] // dailyLimit > maxPerTx
);
uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _limits[0];
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _limits[1];
uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _limits[2];
emit DailyLimitChanged(_token, _limits[0]);
}
/**
* @dev Internal function for initializing execution limits for some token.
* @param _token address of the token contract.
* @param _limits [ 0 = executionDailyLimit, 1 = executionMaxPerTx ].
*/
function _setExecutionLimits(address _token, uint256[2] memory _limits) internal {
require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit
uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0];
uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1];
emit ExecutionDailyLimitChanged(_token, _limits[0]);
}
/**
* @dev Internal function for initializing limits for some token relative to its decimals parameter.
* @param _token address of the token contract.
* @param _decimals token decimals parameter.
*/
function _initializeTokenBridgeLimits(address _token, uint256 _decimals) internal {
uint256 factor;
if (_decimals < 18) {
factor = 10**(18 - _decimals);
uint256 _minPerTx = minPerTx(address(0)).div(factor);
uint256 _maxPerTx = maxPerTx(address(0)).div(factor);
uint256 _dailyLimit = dailyLimit(address(0)).div(factor);
uint256 _executionMaxPerTx = executionMaxPerTx(address(0)).div(factor);
uint256 _executionDailyLimit = executionDailyLimit(address(0)).div(factor);
// such situation can happen when calculated limits relative to the token decimals are too low
// e.g. minPerTx(address(0)) == 10 ** 14, _decimals == 3. _minPerTx happens to be 0, which is not allowed.
// in this case, limits are raised to the default values
if (_minPerTx == 0) {
// Numbers 1, 100, 10000 are chosen in a semi-random way,
// so that any token with small decimals can still be bridged in some amounts.
// It is possible to override limits for the particular token later if needed.
_minPerTx = 1;
if (_maxPerTx <= _minPerTx) {
_maxPerTx = 100;
_executionMaxPerTx = 100;
if (_dailyLimit <= _maxPerTx || _executionDailyLimit <= _executionMaxPerTx) {
_dailyLimit = 10000;
_executionDailyLimit = 10000;
}
}
}
_setLimits(_token, [_dailyLimit, _maxPerTx, _minPerTx]);
_setExecutionLimits(_token, [_executionDailyLimit, _executionMaxPerTx]);
} else {
factor = 10**(_decimals - 18);
_setLimits(
_token,
[dailyLimit(address(0)).mul(factor), maxPerTx(address(0)).mul(factor), minPerTx(address(0)).mul(factor)]
);
_setExecutionLimits(
_token,
[executionDailyLimit(address(0)).mul(factor), executionMaxPerTx(address(0)).mul(factor)]
);
}
}
}
// File contracts/omnibridge/upgradeable_contracts/components/common/BridgeOperationsStorage.sol
pragma solidity 0.7.5;
/**
* @title BridgeOperationsStorage
* @dev Functionality for storing processed bridged operations.
*/
abstract contract BridgeOperationsStorage is EternalStorage {
/**
* @dev Stores the bridged token of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _token bridged token address.
*/
function setMessageToken(bytes32 _messageId, address _token) internal {
addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token;
}
/**
* @dev Tells the bridged token address of a message sent to the AMB bridge.
* @return address of a token contract.
*/
function messageToken(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))];
}
/**
* @dev Stores the value of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _value amount of tokens bridged.
*/
function setMessageValue(bytes32 _messageId, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value;
}
/**
* @dev Tells the amount of tokens of a message sent to the AMB bridge.
* @return value representing amount of tokens.
*/
function messageValue(bytes32 _messageId) internal view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))];
}
/**
* @dev Stores the receiver of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _recipient receiver of the tokens bridged.
*/
function setMessageRecipient(bytes32 _messageId, address _recipient) internal {
addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient;
}
/**
* @dev Tells the receiver of a message sent to the AMB bridge.
* @return address of the receiver.
*/
function messageRecipient(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))];
}
}
// File contracts/omnibridge/upgradeable_contracts/components/common/FailedMessagesProcessor.sol
pragma solidity 0.7.5;
/**
* @title FailedMessagesProcessor
* @dev Functionality for fixing failed bridging operations.
*/
abstract contract FailedMessagesProcessor is BasicAMBMediator, BridgeOperationsStorage {
event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value);
/**
* @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to
* fix/roll back the transferred assets on the other network.
* @param _messageId id of the message which execution failed.
*/
function requestFailedMessageFix(bytes32 _messageId) external {
IAMB bridge = bridgeContract();
require(!bridge.messageCallStatus(_messageId));
require(bridge.failedMessageReceiver(_messageId) == address(this));
require(bridge.failedMessageSender(_messageId) == mediatorContractOnOtherSide());
bytes4 methodSelector = this.fixFailedMessage.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _messageId);
_passMessage(data, true);
}
/**
* @dev Handles the request to fix transferred assets which bridged message execution failed on the other network.
* It uses the information stored by passMessage method when the assets were initially transferred
* @param _messageId id of the message which execution failed on the other network.
*/
function fixFailedMessage(bytes32 _messageId) public onlyMediator {
require(!messageFixed(_messageId));
address token = messageToken(_messageId);
address recipient = messageRecipient(_messageId);
uint256 value = messageValue(_messageId);
setMessageFixed(_messageId);
executeActionOnFixedTokens(token, recipient, value);
emit FailedMessageFixed(_messageId, token, recipient, value);
}
/**
* @dev Tells if a message sent to the AMB bridge has been fixed.
* @return bool indicating the status of the message.
*/
function messageFixed(bytes32 _messageId) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))];
}
/**
* @dev Sets that the message sent to the AMB bridge has been fixed.
* @param _messageId of the message sent to the bridge.
*/
function setMessageFixed(bytes32 _messageId) internal {
boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true;
}
function executeActionOnFixedTokens(
address _token,
address _recipient,
uint256 _value
) internal virtual;
}
// File contracts/omnibridge/upgradeability/Proxy.sol
pragma solidity 0.7.5;
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
abstract contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view virtual returns (address);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback() external payable {
// solhint-disable-previous-line no-complex-fallback
address _impl = implementation();
require(_impl != address(0));
assembly {
/*
0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40)
loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty
memory. It's needed because we're going to write the return data of delegatecall to the
free memory slot.
*/
let ptr := mload(0x40)
/*
`calldatacopy` is copy calldatasize bytes from calldata
First argument is the destination to which data is copied(ptr)
Second argument specifies the start position of the copied data.
Since calldata is sort of its own unique location in memory,
0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata.
That's always going to be the zeroth byte of the function selector.
Third argument, calldatasize, specifies how much data will be copied.
calldata is naturally calldatasize bytes long (same thing as msg.data.length)
*/
calldatacopy(ptr, 0, calldatasize())
/*
delegatecall params explained:
gas: the amount of gas to provide for the call. `gas` is an Opcode that gives
us the amount of gas still available to execution
_impl: address of the contract to delegate to
ptr: to pass copied data
calldatasize: loads the size of `bytes memory data`, same as msg.data.length
0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic,
these are set to 0, 0 so the output data will not be written to memory. The output
data will be read using `returndatasize` and `returdatacopy` instead.
result: This will be 0 if the call fails and 1 if it succeeds
*/
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
/*
*/
/*
ptr current points to the value stored at 0x40,
because we assigned it like ptr := mload(0x40).
Because we use 0x40 as a free memory pointer,
we want to make sure that the next time we want to allocate memory,
we aren't overwriting anything important.
So, by adding ptr and returndatasize,
we get a memory location beyond the end of the data we will be copying to ptr.
We place this in at 0x40, and any reads from 0x40 will now read from free memory
*/
mstore(0x40, add(ptr, returndatasize()))
/*
`returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the
slot it will copy to, 0 means copy from the beginning of the return data, and size is
the amount of data to copy.
`returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall
*/
returndatacopy(ptr, 0, returndatasize())
/*
if `result` is 0, revert.
if `result` is 1, return `size` amount of data from `ptr`. This is the data that was
copied to `ptr` from the delegatecall return data
*/
switch result
case 0 {
revert(ptr, returndatasize())
}
default {
return(ptr, returndatasize())
}
}
}
}
// File contracts/omnibridge/upgradeable_contracts/modules/factory/TokenProxy.sol
pragma solidity 0.7.5;
interface IPermittableTokenVersion {
function version() external pure returns (string memory);
}
/**
* @title TokenProxy
* @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract.
*/
contract TokenProxy is Proxy {
// storage layout is copied from PermittableToken.sol
string internal name;
string internal symbol;
uint8 internal decimals;
mapping(address => uint256) internal balances;
uint256 internal totalSupply;
mapping(address => mapping(address => uint256)) internal allowed;
address internal owner;
bool internal mintingFinished;
address internal bridgeContractAddr;
// string public constant version = "1";
bytes32 internal DOMAIN_SEPARATOR;
// bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
mapping(address => uint256) internal nonces;
mapping(address => mapping(address => uint256)) internal expirations;
/**
* @dev Creates a non-upgradeable token proxy for PermitableToken.sol, initializes its eternalStorage.
* @param _tokenImage address of the token image used for mirroring all functions.
* @param _name token name.
* @param _symbol token symbol.
* @param _decimals token decimals.
* @param _chainId chain id for current network.
* @param _owner address of the owner for this contract.
*/
constructor(
address _tokenImage,
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _chainId,
address _owner
) {
string memory version = IPermittableTokenVersion(_tokenImage).version();
assembly {
// EIP 1967
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _tokenImage)
}
name = _name;
symbol = _symbol;
decimals = _decimals;
owner = _owner; // _owner == HomeOmnibridge/ForeignOmnibridge mediator
bridgeContractAddr = _owner;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(_name)),
keccak256(bytes(version)),
_chainId,
address(this)
)
);
}
/**
* @dev Retrieves the implementation contract address, mirrored token image.
* @return impl token image address.
*/
function implementation() public view override returns (address impl) {
assembly {
impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
}
}
/**
* @dev Tells the current version of the token proxy interfaces.
*/
function getTokenProxyInterfacesVersion()
external
pure
returns (
uint64 major,
uint64 minor,
uint64 patch
)
{
return (1, 0, 0);
}
}
// File contracts/omnibridge/upgradeable_contracts/modules/OwnableModule.sol
pragma solidity 0.7.5;
/**
* @title OwnableModule
* @dev Common functionality for multi-token extension non-upgradeable module.
*/
contract OwnableModule {
address public owner;
/**
* @dev Initializes this contract.
* @param _owner address of the owner that is allowed to perform additional actions on the particular module.
*/
constructor(address _owner) {
owner = _owner;
}
/**
* @dev Throws if sender is not the owner of this contract.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev Changes the owner of this contract.
* @param _newOwner address of the new owner.
*/
function transferOwnership(address _newOwner) external onlyOwner {
owner = _newOwner;
}
}
// File contracts/omnibridge/upgradeable_contracts/modules/factory/TokenFactory.sol
pragma solidity 0.7.5;
/**
* @title TokenFactory
* @dev Factory contract for deployment of new TokenProxy contracts.
*/
contract TokenFactory is OwnableModule {
address public tokenImage;
/**
* @dev Initializes this contract
* @param _owner of this factory contract.
* @param _tokenImage address of the token image contract that should be used for creation of new tokens.
*/
constructor(address _owner, address _tokenImage) OwnableModule(_owner) {
tokenImage = _tokenImage;
}
/**
* @dev Tells the module interface version that this contract supports.
* @return major value of the version
* @return minor value of the version
* @return patch value of the version
*/
function getModuleInterfacesVersion()
external
pure
returns (
uint64 major,
uint64 minor,
uint64 patch
)
{
return (1, 0, 0);
}
/**
* @dev Updates the address of the used token image contract.
* Only owner can call this method.
* @param _tokenImage address of the new token image used for further deployments.
*/
function setTokenImage(address _tokenImage) external onlyOwner {
require(Address.isContract(_tokenImage));
tokenImage = _tokenImage;
}
/**
* @dev Deploys a new TokenProxy contract, using saved token image contract as a template.
* @param _name deployed token name.
* @param _symbol deployed token symbol.
* @param _decimals deployed token decimals.
* @param _chainId chain id of the current environment.
* @return address of a newly created contract.
*/
function deploy(
string calldata _name,
string calldata _symbol,
uint8 _decimals,
uint256 _chainId
) external returns (address) {
return address(new TokenProxy(tokenImage, _name, _symbol, _decimals, _chainId, msg.sender));
}
}
// File contracts/omnibridge/upgradeable_contracts/modules/factory/TokenFactoryConnector.sol
pragma solidity 0.7.5;
/**
* @title TokenFactoryConnector
* @dev Connectivity functionality for working with TokenFactory contract.
*/
contract TokenFactoryConnector is Ownable {
bytes32 internal constant TOKEN_FACTORY_CONTRACT =
0x269c5905f777ee6391c7a361d17039a7d62f52ba9fffeb98c5ade342705731a3; // keccak256(abi.encodePacked("tokenFactoryContract"))
/**
* @dev Updates an address of the used TokenFactory contract used for creating new tokens.
* @param _tokenFactory address of TokenFactory contract.
*/
function setTokenFactory(address _tokenFactory) external onlyOwner {
_setTokenFactory(_tokenFactory);
}
/**
* @dev Retrieves an address of the token factory contract.
* @return address of the TokenFactory contract.
*/
function tokenFactory() public view returns (TokenFactory) {
return TokenFactory(addressStorage[TOKEN_FACTORY_CONTRACT]);
}
/**
* @dev Internal function for updating an address of the token factory contract.
* @param _tokenFactory address of the deployed TokenFactory contract.
*/
function _setTokenFactory(address _tokenFactory) internal {
require(Address.isContract(_tokenFactory));
addressStorage[TOKEN_FACTORY_CONTRACT] = _tokenFactory;
}
}
// File contracts/omnibridge/interfaces/IBurnableMintableERC677Token.sol
pragma solidity 0.7.5;
interface IBurnableMintableERC677Token is IERC677 {
function mint(address _to, uint256 _amount) external returns (bool);
function burn(uint256 _value) external;
function claimTokens(address _token, address _to) external;
}
// File contracts/omnibridge/interfaces/IERC20Metadata.sol
pragma solidity 0.7.5;
interface IERC20Metadata {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File contracts/omnibridge/interfaces/IERC20Receiver.sol
pragma solidity 0.7.5;
interface IERC20Receiver {
function onTokenBridged(
address token,
uint256 value,
bytes calldata data
) external;
}
// File contracts/omnibridge/libraries/TokenReader.sol
pragma solidity 0.7.5;
// solhint-disable
interface ITokenDetails {
function name() external view;
function NAME() external view;
function symbol() external view;
function SYMBOL() external view;
function decimals() external view;
function DECIMALS() external view;
}
// solhint-enable
/**
* @title TokenReader
* @dev Helper methods for reading name/symbol/decimals parameters from ERC20 token contracts.
*/
library TokenReader {
/**
* @dev Reads the name property of the provided token.
* Either name() or NAME() method is used.
* Both, string and bytes32 types are supported.
* @param _token address of the token contract.
* @return token name as a string or an empty string if none of the methods succeeded.
*/
function readName(address _token) internal view returns (string memory) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.name.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.NAME.selector));
if (!status) {
return "";
}
}
return _convertToString(data);
}
/**
* @dev Reads the symbol property of the provided token.
* Either symbol() or SYMBOL() method is used.
* Both, string and bytes32 types are supported.
* @param _token address of the token contract.
* @return token symbol as a string or an empty string if none of the methods succeeded.
*/
function readSymbol(address _token) internal view returns (string memory) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.symbol.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.SYMBOL.selector));
if (!status) {
return "";
}
}
return _convertToString(data);
}
/**
* @dev Reads the decimals property of the provided token.
* Either decimals() or DECIMALS() method is used.
* @param _token address of the token contract.
* @return token decimals or 0 if none of the methods succeeded.
*/
function readDecimals(address _token) internal view returns (uint8) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.decimals.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.DECIMALS.selector));
if (!status) {
return 0;
}
}
return abi.decode(data, (uint8));
}
/**
* @dev Internal function for converting returned value of name()/symbol() from bytes32/string to string.
* @param returnData data returned by the token contract.
* @return string with value obtained from returnData.
*/
function _convertToString(bytes memory returnData) private pure returns (string memory) {
if (returnData.length > 32) {
return abi.decode(returnData, (string));
} else if (returnData.length == 32) {
bytes32 data = abi.decode(returnData, (bytes32));
string memory res = new string(32);
assembly {
let len := 0
mstore(add(res, 32), data) // save value in result string
// solhint-disable
for { } gt(data, 0) { len := add(len, 1) } { // until string is empty
data := shl(8, data) // shift left by one symbol
}
// solhint-enable
mstore(res, len) // save result string length
}
return res;
} else {
return "";
}
}
}
// File contracts/omnibridge/libraries/SafeMint.sol
pragma solidity 0.7.5;
/**
* @title SafeMint
* @dev Wrapper around the mint() function in all mintable tokens that verifies the return value.
*/
library SafeMint {
/**
* @dev Wrapper around IBurnableMintableERC677Token.mint() that verifies that output value is true.
* @param _token token contract.
* @param _to address of the tokens receiver.
* @param _value amount of tokens to mint.
*/
function safeMint(
IBurnableMintableERC677Token _token,
address _to,
uint256 _value
) internal {
require(_token.mint(_to, _value));
}
}
// File contracts/omnibridge/upgradeable_contracts/BasicOmnibridge.sol
pragma solidity 0.7.5;
/**
* @title BasicOmnibridge
* @dev Common functionality for multi-token mediator intended to work on top of AMB bridge.
*/
abstract contract BasicOmnibridge is
Initializable,
Upgradeable,
Claimable,
OmnibridgeInfo,
TokensRelayer,
FailedMessagesProcessor,
BridgedTokensRegistry,
NativeTokensRegistry,
MediatorBalanceStorage,
TokenFactoryConnector,
TokensBridgeLimits
{
using SafeERC20 for IERC677;
using SafeMint for IBurnableMintableERC677Token;
using SafeMath for uint256;
// Workaround for storing variable up-to-32 bytes suffix
uint256 private immutable SUFFIX_SIZE;
bytes32 private immutable SUFFIX;
// Since contract is intended to be deployed under EternalStorageProxy, only constant and immutable variables can be set here
constructor(string memory _suffix) {
require(bytes(_suffix).length <= 32);
bytes32 suffix;
assembly {
suffix := mload(add(_suffix, 32))
}
SUFFIX = suffix;
SUFFIX_SIZE = bytes(_suffix).length;
}
/**
* @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract.
* Checks that the value is inside the execution limits and invokes the Mint or Unlock accordingly.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead.
* @param _symbol symbol of the bridged token, if empty, name will be used instead.
* @param _decimals decimals of the bridge foreign token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function deployAndHandleBridgedTokens(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals,
address _recipient,
uint256 _value
) external onlyMediator {
address bridgedToken = _getBridgedTokenOrDeploy(_token, _name, _symbol, _decimals);
_handleTokens(bridgedToken, false, _recipient, _value);
}
/**
* @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract.
* Executes a callback on the receiver.
* Checks that the value is inside the execution limits and invokes the Mint accordingly.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead.
* @param _symbol symbol of the bridged token, if empty, name will be used instead.
* @param _decimals decimals of the bridge foreign token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
* @param _data additional data passed from the other chain.
*/
function deployAndHandleBridgedTokensAndCall(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals,
address _recipient,
uint256 _value,
bytes calldata _data
) external onlyMediator {
address bridgedToken = _getBridgedTokenOrDeploy(_token, _name, _symbol, _decimals);
_handleTokens(bridgedToken, false, _recipient, _value);
_receiverCallback(_recipient, bridgedToken, _value, _data);
}
/**
* @dev Handles the bridged tokens for the already registered token pair.
* Checks that the value is inside the execution limits and invokes the Mint accordingly.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function handleBridgedTokens(
address _token,
address _recipient,
uint256 _value
) external onlyMediator {
address token = bridgedTokenAddress(_token);
require(isTokenRegistered(token));
_handleTokens(token, false, _recipient, _value);
}
/**
* @dev Handles the bridged tokens for the already registered token pair.
* Checks that the value is inside the execution limits and invokes the Unlock accordingly.
* Executes a callback on the receiver.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
* @param _data additional transfer data passed from the other side.
*/
function handleBridgedTokensAndCall(
address _token,
address _recipient,
uint256 _value,
bytes memory _data
) external onlyMediator {
address token = bridgedTokenAddress(_token);
require(isTokenRegistered(token));
_handleTokens(token, false, _recipient, _value);
_receiverCallback(_recipient, token, _value, _data);
}
/**
* @dev Handles the bridged tokens that are native to this chain.
* Checks that the value is inside the execution limits and invokes the Unlock accordingly.
* @param _token native ERC20 token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function handleNativeTokens(
address _token,
address _recipient,
uint256 _value
) external onlyMediator {
_ackBridgedTokenDeploy(_token);
_handleTokens(_token, true, _recipient, _value);
}
/**
* @dev Handles the bridged tokens that are native to this chain.
* Checks that the value is inside the execution limits and invokes the Unlock accordingly.
* Executes a callback on the receiver.
* @param _token native ERC20 token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
* @param _data additional transfer data passed from the other side.
*/
function handleNativeTokensAndCall(
address _token,
address _recipient,
uint256 _value,
bytes memory _data
) external onlyMediator {
_ackBridgedTokenDeploy(_token);
_handleTokens(_token, true, _recipient, _value);
_receiverCallback(_recipient, _token, _value, _data);
}
/**
* @dev Checks if a given token is a bridged token that is native to this side of the bridge.
* @param _token address of token contract.
* @return message id of the send message.
*/
function isRegisteredAsNativeToken(address _token) public view returns (bool) {
return isTokenRegistered(_token) && nativeTokenAddress(_token) == address(0);
}
/**
* @dev Unlock back the amount of tokens that were bridged to the other network but failed.
* @param _token address that bridged token contract.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function executeActionOnFixedTokens(
address _token,
address _recipient,
uint256 _value
) internal override {
_releaseTokens(nativeTokenAddress(_token) == address(0), _token, _recipient, _value, _value);
}
/**
* @dev Allows to pre-set the bridged token contract for not-yet bridged token.
* Only the owner can call this method.
* @param _nativeToken address of the token contract on the other side that was not yet bridged.
* @param _bridgedToken address of the bridged token contract.
*/
function setCustomTokenAddressPair(address _nativeToken, address _bridgedToken) external onlyOwner {
require(!isTokenRegistered(_bridgedToken));
require(nativeTokenAddress(_bridgedToken) == address(0));
require(bridgedTokenAddress(_nativeToken) == address(0));
// Unfortunately, there is no simple way to verify that the _nativeToken address
// does not belong to the bridged token on the other side,
// since information about bridged tokens addresses is not transferred back.
// Therefore, owner account calling this function SHOULD manually verify on the other side of the bridge that
// nativeTokenAddress(_nativeToken) == address(0) && isTokenRegistered(_nativeToken) == false.
IBurnableMintableERC677Token(_bridgedToken).safeMint(address(this), 1);
IBurnableMintableERC677Token(_bridgedToken).burn(1);
_setTokenAddressPair(_nativeToken, _bridgedToken);
}
/**
* @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract
* without the invocation of the required methods. (e. g. regular transfer without a call to onTokenTransfer)
* @param _token address of the token contract.
* Before calling this method, it must be carefully investigated how imbalance happened
* in order to avoid an attempt to steal the funds from a token with double addresses
* (e.g. TUSD is accessible at both 0x8dd5fbCe2F6a956C3022bA3663759011Dd51e73E and 0x0000000000085d4780B73119b644AE5ecd22b376)
* @param _receiver the address that will receive the tokens on the other network.
*/
function fixMediatorBalance(address _token, address _receiver)
external
onlyIfUpgradeabilityOwner
validAddress(_receiver)
{
require(isRegisteredAsNativeToken(_token));
uint256 diff = _unaccountedBalance(_token);
require(diff > 0);
uint256 available = maxAvailablePerTx(_token);
require(available > 0);
if (diff > available) {
diff = available;
}
addTotalSpentPerDay(_token, getCurrentDay(), diff);
bytes memory data = _prepareMessage(address(0), _token, _receiver, diff, new bytes(0));
bytes32 _messageId = _passMessage(data, true);
_recordBridgeOperation(_messageId, _token, _receiver, diff);
}
/**
* @dev Claims stuck tokens. Only unsupported tokens can be claimed.
* When dealing with already supported tokens, fixMediatorBalance can be used instead.
* @param _token address of claimed token, address(0) for native
* @param _to address of tokens receiver
*/
function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner {
// Only unregistered tokens and native coins are allowed to be claimed with the use of this function
require(_token == address(0) || !isTokenRegistered(_token));
claimValues(_token, _to);
}
/**
* @dev Withdraws erc20 tokens or native coins from the bridged token contract.
* Only the proxy owner is allowed to call this method.
* @param _bridgedToken address of the bridged token contract.
* @param _token address of the claimed token or address(0) for native coins.
* @param _to address of the tokens/coins receiver.
*/
function claimTokensFromTokenContract(
address _bridgedToken,
address _token,
address _to
) external onlyIfUpgradeabilityOwner {
IBurnableMintableERC677Token(_bridgedToken).claimTokens(_token, _to);
}
/**
* @dev Internal function for recording bridge operation for further usage.
* Recorded information is used for fixing failed requests on the other side.
* @param _messageId id of the sent message.
* @param _token bridged token address.
* @param _sender address of the tokens sender.
* @param _value bridged value.
*/
function _recordBridgeOperation(
bytes32 _messageId,
address _token,
address _sender,
uint256 _value
) internal {
setMessageToken(_messageId, _token);
setMessageRecipient(_messageId, _sender);
setMessageValue(_messageId, _value);
emit TokensBridgingInitiated(_token, _sender, _value, _messageId);
}
/**
* @dev Constructs the message to be sent to the other side. Burns/locks bridged amount of tokens.
* @param _nativeToken address of the native token contract.
* @param _token bridged token address.
* @param _receiver address of the tokens receiver on the other side.
* @param _value bridged value.
* @param _data additional transfer data passed from the other side.
*/
function _prepareMessage(
address _nativeToken,
address _token,
address _receiver,
uint256 _value,
bytes memory _data
) internal returns (bytes memory) {
bool withData = _data.length > 0 || msg.sig == this.relayTokensAndCall.selector;
// process token is native with respect to this side of the bridge
if (_nativeToken == address(0)) {
_setMediatorBalance(_token, mediatorBalance(_token).add(_value));
// process token which bridged alternative was already ACKed to be deployed
if (isBridgedTokenDeployAcknowledged(_token)) {
return
withData
? abi.encodeWithSelector(
this.handleBridgedTokensAndCall.selector,
_token,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, _receiver, _value);
}
uint8 decimals = TokenReader.readDecimals(_token);
string memory name = TokenReader.readName(_token);
string memory symbol = TokenReader.readSymbol(_token);
require(bytes(name).length > 0 || bytes(symbol).length > 0);
return
withData
? abi.encodeWithSelector(
this.deployAndHandleBridgedTokensAndCall.selector,
_token,
name,
symbol,
decimals,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(
this.deployAndHandleBridgedTokens.selector,
_token,
name,
symbol,
decimals,
_receiver,
_value
);
}
// process already known token that is bridged from other chain
IBurnableMintableERC677Token(_token).burn(_value);
return
withData
? abi.encodeWithSelector(
this.handleNativeTokensAndCall.selector,
_nativeToken,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(this.handleNativeTokens.selector, _nativeToken, _receiver, _value);
}
/**
* @dev Internal function for getting minter proxy address.
* @param _token address of the token to mint.
* @return address of the minter contract that should be used for calling mint(address,uint256)
*/
function _getMinterFor(address _token) internal pure virtual returns (IBurnableMintableERC677Token) {
return IBurnableMintableERC677Token(_token);
}
/**
* Internal function for unlocking some amount of tokens.
* @param _isNative true, if token is native w.r.t. to this side of the bridge.
* @param _token address of the token contract.
* @param _recipient address of the tokens receiver.
* @param _value amount of tokens to unlock.
* @param _balanceChange amount of balance to subtract from the mediator balance.
*/
function _releaseTokens(
bool _isNative,
address _token,
address _recipient,
uint256 _value,
uint256 _balanceChange
) internal virtual {
if (_isNative) {
IERC677(_token).safeTransfer(_recipient, _value);
_setMediatorBalance(_token, mediatorBalance(_token).sub(_balanceChange));
} else {
_getMinterFor(_token).safeMint(_recipient, _value);
}
}
/**
* Internal function for getting address of the bridged token. Deploys new token if necessary.
* @param _token address of the token contract on the other side of the bridge.
* @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead.
* @param _symbol symbol of the bridged token, if empty, name will be used instead.
* @param _decimals decimals of the bridge foreign token.
*/
function _getBridgedTokenOrDeploy(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals
) internal returns (address) {
address bridgedToken = bridgedTokenAddress(_token);
if (bridgedToken == address(0)) {
string memory name = _name;
string memory symbol = _symbol;
require(bytes(name).length > 0 || bytes(symbol).length > 0);
if (bytes(name).length == 0) {
name = symbol;
} else if (bytes(symbol).length == 0) {
symbol = name;
}
name = _transformName(name);
bridgedToken = tokenFactory().deploy(name, symbol, _decimals, bridgeContract().sourceChainId());
_setTokenAddressPair(_token, bridgedToken);
_initializeTokenBridgeLimits(bridgedToken, _decimals);
} else if (!isTokenRegistered(bridgedToken)) {
require(IERC20Metadata(bridgedToken).decimals() == _decimals);
_initializeTokenBridgeLimits(bridgedToken, _decimals);
}
return bridgedToken;
}
/**
* Notifies receiving contract about the completed bridging operation.
* @param _recipient address of the tokens receiver.
* @param _token address of the bridged token.
* @param _value amount of tokens transferred.
* @param _data additional data passed to the callback.
*/
function _receiverCallback(
address _recipient,
address _token,
uint256 _value,
bytes memory _data
) internal {
if (Address.isContract(_recipient)) {
_recipient.call(abi.encodeWithSelector(IERC20Receiver.onTokenBridged.selector, _token, _value, _data));
}
}
/**
* @dev Internal function for transforming the bridged token name. Appends a side-specific suffix.
* @param _name bridged token from the other side.
* @return token name for this side of the bridge.
*/
function _transformName(string memory _name) internal view returns (string memory) {
string memory result = string(abi.encodePacked(_name, SUFFIX));
uint256 size = SUFFIX_SIZE;
assembly {
mstore(result, add(mload(_name), size))
}
return result;
}
/**
* @dev Internal function for counting excess balance which is not tracked within the bridge.
* Represents the amount of forced tokens on this contract.
* @param _token address of the token contract.
* @return amount of excess tokens.
*/
function _unaccountedBalance(address _token) internal view virtual returns (uint256) {
return IERC677(_token).balanceOf(address(this)).sub(mediatorBalance(_token));
}
function _handleTokens(
address _token,
bool _isNative,
address _recipient,
uint256 _value
) internal virtual;
}
// File contracts/omnibridge/upgradeable_contracts/components/common/GasLimitManager.sol
pragma solidity 0.7.5;
/**
* @title GasLimitManager
* @dev Functionality for determining the request gas limit for AMB execution.
*/
abstract contract GasLimitManager is BasicAMBMediator {
bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit"))
/**
* @dev Sets the default gas limit to be used in the message execution by the AMB bridge on the other network.
* This value can't exceed the parameter maxGasPerTx defined on the AMB bridge.
* Only the owner can call this method.
* @param _gasLimit the gas limit for the message execution.
*/
function setRequestGasLimit(uint256 _gasLimit) external onlyOwner {
_setRequestGasLimit(_gasLimit);
}
/**
* @dev Tells the default gas limit to be used in the message execution by the AMB bridge on the other network.
* @return the gas limit for the message execution.
*/
function requestGasLimit() public view returns (uint256) {
return uintStorage[REQUEST_GAS_LIMIT];
}
/**
* @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network.
* @param _gasLimit the gas limit for the message execution.
*/
function _setRequestGasLimit(uint256 _gasLimit) internal {
require(_gasLimit <= maxGasPerTx());
uintStorage[REQUEST_GAS_LIMIT] = _gasLimit;
}
}
// File contracts/omnibridge/interfaces/IInterestReceiver.sol
pragma solidity 0.7.5;
interface IInterestReceiver {
function onInterestReceived(address _token) external;
}
// File contracts/omnibridge/interfaces/IInterestImplementation.sol
pragma solidity 0.7.5;
interface IInterestImplementation {
event InterestEnabled(address indexed token, address xToken);
event InterestDustUpdated(address indexed token, uint96 dust);
event InterestReceiverUpdated(address indexed token, address receiver);
event MinInterestPaidUpdated(address indexed token, uint256 amount);
event PaidInterest(address indexed token, address to, uint256 value);
event ForceDisable(address indexed token, uint256 tokensAmount, uint256 xTokensAmount, uint256 investedAmount);
function isInterestSupported(address _token) external view returns (bool);
function invest(address _token, uint256 _amount) external;
function withdraw(address _token, uint256 _amount) external;
function investedAmount(address _token) external view returns (uint256);
}
// File contracts/omnibridge/upgradeable_contracts/components/common/InterestConnector.sol
pragma solidity 0.7.5;
/**
* @title InterestConnector
* @dev This contract gives an abstract way of receiving interest on locked tokens.
*/
contract InterestConnector is Ownable, MediatorBalanceStorage {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Tells address of the interest earning implementation for the specific token contract.
* If interest earning is disabled, will return 0x00..00.
* Can be an address of the deployed CompoundInterestERC20 contract.
* @param _token address of the locked token contract.
* @return address of the implementation contract.
*/
function interestImplementation(address _token) public view returns (IInterestImplementation) {
return IInterestImplementation(addressStorage[keccak256(abi.encodePacked("interestImpl", _token))]);
}
/**
* @dev Initializes interest receiving functionality for the particular locked token.
* Only owner can call this method.
* @param _token address of the token for interest earning.
* @param _impl address of the interest earning implementation contract.
* @param _minCashThreshold minimum amount of underlying tokens that are not invested.
*/
function initializeInterest(
address _token,
address _impl,
uint256 _minCashThreshold
) external onlyOwner {
require(address(interestImplementation(_token)) == address(0));
_setInterestImplementation(_token, _impl);
_setMinCashThreshold(_token, _minCashThreshold);
}
/**
* @dev Sets minimum amount of tokens that cannot be invested.
* Only owner can call this method.
* @param _token address of the token contract.
* @param _minCashThreshold minimum amount of underlying tokens that are not invested.
*/
function setMinCashThreshold(address _token, uint256 _minCashThreshold) external onlyOwner {
_setMinCashThreshold(_token, _minCashThreshold);
}
/**
* @dev Tells minimum amount of tokens that are not being invested.
* @param _token address of the invested token contract.
* @return amount of tokens.
*/
function minCashThreshold(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("minCashThreshold", _token))];
}
/**
* @dev Disables interest for locked funds.
* Only owner can call this method.
* Prior to calling this function, consider to call payInterest and claimCompAndPay.
* @param _token of token to disable interest for.
*/
function disableInterest(address _token) external onlyOwner {
interestImplementation(_token).withdraw(_token, uint256(-1));
_setInterestImplementation(_token, address(0));
}
/**
* @dev Invests all excess tokens. Leaves only minCashThreshold in underlying tokens.
* Requires interest for the given token to be enabled first.
* @param _token address of the token contract considered.
*/
function invest(address _token) external {
IInterestImplementation impl = interestImplementation(_token);
// less than _token.balanceOf(this), since it does not take into account mistakenly locked tokens that should be processed via fixMediatorBalance.
uint256 balance = mediatorBalance(_token).sub(impl.investedAmount(_token));
uint256 minCash = minCashThreshold(_token);
require(balance > minCash);
uint256 amount = balance - minCash;
IERC20(_token).safeTransfer(address(impl), amount);
impl.invest(_token, amount);
}
/**
* @dev Internal function for setting interest earning implementation contract for some token.
* Also acts as an interest enabled flag.
* @param _token address of the token contract.
* @param _impl address of the implementation contract.
*/
function _setInterestImplementation(address _token, address _impl) internal {
require(_impl == address(0) || IInterestImplementation(_impl).isInterestSupported(_token));
addressStorage[keccak256(abi.encodePacked("interestImpl", _token))] = _impl;
}
/**
* @dev Internal function for setting minimum amount of tokens that cannot be invested.
* @param _token address of the token contract.
* @param _minCashThreshold minimum amount of underlying tokens that are not invested.
*/
function _setMinCashThreshold(address _token, uint256 _minCashThreshold) internal {
uintStorage[keccak256(abi.encodePacked("minCashThreshold", _token))] = _minCashThreshold;
}
}
// File contracts/omnibridge/upgradeable_contracts/ForeignOmnibridge.sol
pragma solidity 0.7.5;
/**
* @title ForeignOmnibridge
* @dev Foreign side implementation for multi-token mediator intended to work on top of AMB bridge.
* It is designed to be used as an implementation contract of EternalStorageProxy contract.
*/
contract ForeignOmnibridge is BasicOmnibridge, GasLimitManager, InterestConnector {
using SafeERC20 for IERC677;
using SafeMint for IBurnableMintableERC677Token;
using SafeMath for uint256;
constructor(string memory _suffix) BasicOmnibridge(_suffix) {}
/**
* @dev Stores the initial parameters of the mediator.
* @param _bridgeContract the address of the AMB bridge contract.
* @param _mediatorContract the address of the mediator contract on the other network.
* @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network.
* [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]
* @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network.
* [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]
* @param _requestGasLimit the gas limit for the message execution.
* @param _owner address of the owner of the mediator contract.
* @param _tokenFactory address of the TokenFactory contract that will be used for the deployment of new tokens.
*/
function initialize(
address _bridgeContract,
address _mediatorContract,
uint256[3] calldata _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ]
uint256[2] calldata _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ]
uint256 _requestGasLimit,
address _owner,
address _tokenFactory
) external onlyRelevantSender returns (bool) {
require(!isInitialized());
_setBridgeContract(_bridgeContract);
_setMediatorContractOnOtherSide(_mediatorContract);
_setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray);
_setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray);
_setRequestGasLimit(_requestGasLimit);
_setOwner(_owner);
_setTokenFactory(_tokenFactory);
setInitialize();
return isInitialized();
}
/**
* One-time function to be used together with upgradeToAndCall method.
* Sets the token factory contract.
* @param _tokenFactory address of the deployed TokenFactory contract.
*/
function upgradeToReverseMode(address _tokenFactory) external {
require(msg.sender == address(this));
_setTokenFactory(_tokenFactory);
}
/**
* @dev Handles the bridged tokens.
* Checks that the value is inside the execution limits and invokes the Mint or Unlock accordingly.
* @param _token token contract address on this side of the bridge.
* @param _isNative true, if given token is native to this chain and Unlock should be used.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function _handleTokens(
address _token,
bool _isNative,
address _recipient,
uint256 _value
) internal override {
// prohibit withdrawal of tokens during other bridge operations (e.g. relayTokens)
// such reentrant withdrawal can lead to an incorrect balanceDiff calculation
require(!lock());
require(withinExecutionLimit(_token, _value));
addTotalExecutedPerDay(_token, getCurrentDay(), _value);
_releaseTokens(_isNative, _token, _recipient, _value, _value);
emit TokensBridged(_token, _recipient, _value, messageId());
}
/**
* @dev Executes action on deposit of bridged tokens
* @param _token address of the token contract
* @param _from address of tokens sender
* @param _receiver address of tokens receiver on the other side
* @param _value requested amount of bridged tokens
* @param _data additional transfer data to be used on the other side
*/
function bridgeSpecificActionsOnTokenTransfer(
address _token,
address _from,
address _receiver,
uint256 _value,
bytes memory _data
) internal virtual override {
require(_receiver != address(0) && _receiver != mediatorContractOnOtherSide());
// native unbridged token
if (!isTokenRegistered(_token)) {
uint8 decimals = TokenReader.readDecimals(_token);
_initializeTokenBridgeLimits(_token, decimals);
}
require(withinLimit(_token, _value));
addTotalSpentPerDay(_token, getCurrentDay(), _value);
bytes memory data = _prepareMessage(nativeTokenAddress(_token), _token, _receiver, _value, _data);
bytes32 _messageId = _passMessage(data, true);
_recordBridgeOperation(_messageId, _token, _from, _value);
}
/**
* Internal function for unlocking some amount of tokens.
* @param _isNative true, if token is native w.r.t. to this side of the bridge.
* @param _token address of the token contract.
* @param _recipient address of the tokens receiver.
* @param _value amount of tokens to unlock.
* @param _balanceChange amount of balance to subtract from the mediator balance.
*/
function _releaseTokens(
bool _isNative,
address _token,
address _recipient,
uint256 _value,
uint256 _balanceChange
) internal override {
if (_isNative) {
// There are two edge cases related to withdrawals on the foreign side of the bridge.
// 1) Minting of extra STAKE tokens, if supply on the Home side exceeds total bridge amount on the Foreign side.
// 2) Withdrawal of the invested tokens back from the Compound-like protocol, if currently available funds are insufficient.
// Most of the time, these cases do not intersect. However, in case STAKE tokens are also invested (e.g. via EasyStaking),
// the situation can be the following:
// - 20 STAKE are bridged through the OB. 15 STAKE of which are invested into EasyStaking, and 5 STAKE are locked directly on the bridge.
// - 5 STAKE are mistakenly locked on the bridge via regular transfer, they are not accounted in mediatorBalance(STAKE)
// - User requests withdrawal of 30 STAKE from the Home side.
// Correct sequence of actions should be the following:
// - Mint new STAKE tokens (value - mediatorBalance(STAKE) = 30 STAKE - 20 STAKE = 10 STAKE)
// - Set local variable balance to 30 STAKE
// - Withdraw all invested STAKE tokens (value - (balance - investedAmount(STAKE)) = 30 STAKE - (30 STAKE - 15 STAKE) = 15 STAKE)
uint256 balance = mediatorBalance(_token);
if (_token == address(0x0Ae055097C6d159879521C384F1D2123D1f195e6) && balance < _value) {
IBurnableMintableERC677Token(_token).safeMint(address(this), _value - balance);
balance = _value;
}
IInterestImplementation impl = interestImplementation(_token);
// can be used instead of Address.isContract(address(impl)),
// since _setInterestImplementation guarantees that impl is either a contract or zero address
// and interest implementation does not contain any selfdestruct opcode
if (address(impl) != address(0)) {
uint256 availableBalance = balance.sub(impl.investedAmount(_token));
if (_value > availableBalance) {
impl.withdraw(_token, (_value - availableBalance).add(minCashThreshold(_token)));
}
}
_setMediatorBalance(_token, balance.sub(_balanceChange));
IERC677(_token).safeTransfer(_recipient, _value);
} else {
_getMinterFor(_token).safeMint(_recipient, _value);
}
}
/**
* @dev Internal function for sending an AMB message to the mediator on the other side.
* @param _data data to be sent to the other side of the bridge.
* @param _useOracleLane always true, not used on this side of the bridge.
* @return id of the sent message.
*/
function _passMessage(bytes memory _data, bool _useOracleLane) internal override returns (bytes32) {
(_useOracleLane);
return bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), _data, requestGasLimit());
}
/**
* @dev Internal function for counting excess balance which is not tracked within the bridge.
* Represents the amount of forced tokens on this contract.
* @param _token address of the token contract.
* @return amount of excess tokens.
*/
function _unaccountedBalance(address _token) internal view override returns (uint256) {
IInterestImplementation impl = interestImplementation(_token);
uint256 invested = Address.isContract(address(impl)) ? impl.investedAmount(_token) : 0;
return IERC677(_token).balanceOf(address(this)).sub(mediatorBalance(_token).sub(invested));
}
} | Tells address of the interest earning implementation for the specific token contract. If interest earning is disabled, will return 0x00..00. Can be an address of the deployed CompoundInterestERC20 contract. _token address of the locked token contract. return address of the implementation contract./ | function interestImplementation(address _token) public view returns (IInterestImplementation) {
return IInterestImplementation(addressStorage[keccak256(abi.encodePacked("interestImpl", _token))]);
}
| 6,580,920 |
./full_match/1/0xc905E74BEb8229E258c3C6E5bC0D6Cc54C534688/sources/contracts/chainlink/ChainlinkOracleClient.sol | set/update chainlink jobid data | function setJob(uint16 _chain, address _oracle, bytes32 _id, uint _fee) public onlyOwner {
jobs[_chain] = Job(_oracle, _id, _fee, getBlockForOracleJob() - 1);
}
| 2,930,675 |
pragma solidity ^0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
modifier nonZeroEth(uint _value) {
require(_value > 0);
_;
}
modifier onlyPayloadSize() {
require(msg.data.length >= 68);
_;
}
event Transfer(address indexed from, address indexed to, uint256 value);
event Allocate(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) nonZeroEth(_value) onlyPayloadSize returns (bool) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]){
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}else{
return false;
}
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) nonZeroEth(_value) onlyPayloadSize returns (bool) {
if(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]){
uint256 _allowance = allowed[_from][msg.sender];
allowed[_from][msg.sender] = _allowance.sub(_value);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
Transfer(_from, _to, _value);
return true;
}else{
return false;
}
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract BoonTech is BasicToken, Ownable{
using SafeMath for uint256;
//token attributes
string public name = "Boon Tech"; //name of the token
string public symbol = "BOON"; // symbol of the token
uint8 public decimals = 18; // decimals
uint256 public totalSupply = 500000000 * 10**uint256(decimals); // total supply of BOON Tokens
uint256 private constant decimalFactor = 10**uint256(decimals);
bool public transfersAreLocked = true;
mapping (address => Allocation) public allocations;
// Allocation with vesting information
// 25% Released at Token Distribution +0.5 year -> 100% at Token Distribution +2 years
struct Allocation {
uint256 startTime;
uint256 endCliff; // Tokens are locked until
uint256 endVesting; // This is when the tokens are fully unvested
uint256 totalAllocated; // Total tokens allocated
uint256 amountClaimed; // Total tokens claimed
}
uint256 public grandTotalClaimed = 0;
uint256 tokensForDistribution = totalSupply.div(2);
uint256 ethPrice = 960;
uint256 tokenPrice = 4;
//events
event LogNewAllocation(address indexed _recipient, uint256 _totalAllocated);
event LogBoonReleased(address indexed _recipient, uint256 _amountClaimed, uint256 _totalAllocated, uint256 _grandTotalClaimed);
///////////////////////////////////////// CONSTRUCTOR for Distribution //////////////////////////////////////////////////
function BoonTech () {
balances[msg.sender] = totalSupply;
}
///////////////////////////////////////// MODIFIERS /////////////////////////////////////////////////
// Checks whether it can transfer or otherwise throws.
modifier canTransfer() {
require(transfersAreLocked == false);
_;
}
modifier nonZeroAddress(address _to) {
require(_to != 0x0);
_;
}
////////////////////////////////////////// FUNCTIONS //////////////////////////////////////////////
// Returns current token Owner
function tokenOwner() public view returns (address) {
return owner;
}
// Checks modifier and allows transfer if tokens are not locked.
function transfer(address _to, uint _value) canTransfer() public returns (bool success) {
return super.transfer(_to, _value);
}
// Checks modifier and allows transfer if tokens are not locked.
function transferFrom(address _from, address _to, uint _value) canTransfer() public returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
// lock/unlock transfers
function transferLock() onlyOwner public{
transfersAreLocked = true;
}
function transferUnlock() onlyOwner public{
transfersAreLocked = false;
}
function setFounderAllocation(address _recipient, uint256 _totalAllocated) onlyOwner public {
require(allocations[_recipient].totalAllocated == 0 && _totalAllocated > 0);
require(_recipient != address(0));
allocations[_recipient] = Allocation(now, now + 0.5 years, now + 2 years, _totalAllocated, 0);
//allocations[_recipient] = Allocation(now, now + 2 minutes, now + 4 minutes, _totalAllocated, 0);
LogNewAllocation(_recipient, _totalAllocated);
}
function releaseVestedTokens(address _tokenAddress) onlyOwner public{
require(allocations[_tokenAddress].amountClaimed < allocations[_tokenAddress].totalAllocated);
require(now >= allocations[_tokenAddress].endCliff);
require(now >= allocations[_tokenAddress].startTime);
uint256 newAmountClaimed;
if (allocations[_tokenAddress].endVesting > now) {
// Transfer available amount based on vesting schedule and allocation
newAmountClaimed = allocations[_tokenAddress].totalAllocated.mul(now.sub(allocations[_tokenAddress].startTime)).div(allocations[_tokenAddress].endVesting.sub(allocations[_tokenAddress].startTime));
} else {
// Transfer total allocated (minus previously claimed tokens)
newAmountClaimed = allocations[_tokenAddress].totalAllocated;
}
uint256 tokensToTransfer = newAmountClaimed.sub(allocations[_tokenAddress].amountClaimed);
allocations[_tokenAddress].amountClaimed = newAmountClaimed;
if(transfersAreLocked == true){
transfersAreLocked = false;
require(transfer(_tokenAddress, tokensToTransfer * decimalFactor));
transfersAreLocked = true;
}else{
require(transfer(_tokenAddress, tokensToTransfer * decimalFactor));
}
grandTotalClaimed = grandTotalClaimed.add(tokensToTransfer);
LogBoonReleased(_tokenAddress, tokensToTransfer, newAmountClaimed, grandTotalClaimed);
}
function distributeToken(address[] _addresses, uint256[] _value) onlyOwner public {
for (uint i = 0; i < _addresses.length; i++) {
transfersAreLocked = false;
require(transfer(_addresses[i], _value[i] * decimalFactor));
transfersAreLocked = true;
}
}
// Buy token function call only in duration of crowdfund active
function getNoOfTokensTransfer(uint32 _exchangeRate , uint256 _amount) internal returns (uint256) {
uint256 noOfToken = _amount.mul(_exchangeRate);
uint256 noOfTokenWithBonus =(100 * noOfToken ) / 100;
return noOfTokenWithBonus;
}
function setEthPrice(uint256 value)
external
onlyOwner
{
ethPrice = value;
}
function calcToken(uint256 value)
internal
returns(uint256 amount){
amount = ethPrice.mul(100).mul(value).div(tokenPrice);
return amount;
}
function buyTokens()
external
payable
returns (uint256 amount)
{
amount = calcToken(msg.value);
require(msg.value > 0);
require(balanceOf(owner) >= amount);
balances[owner] = balances[owner].sub(msg.value);
balances[msg.sender] = balances[msg.sender].add(msg.value);
return amount;
}
} | allocations[_recipient] = Allocation(now, now + 2 minutes, now + 4 minutes, _totalAllocated, 0); | function setFounderAllocation(address _recipient, uint256 _totalAllocated) onlyOwner public {
require(allocations[_recipient].totalAllocated == 0 && _totalAllocated > 0);
require(_recipient != address(0));
allocations[_recipient] = Allocation(now, now + 0.5 years, now + 2 years, _totalAllocated, 0);
LogNewAllocation(_recipient, _totalAllocated);
}
| 12,651,171 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.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);
function decimals() external view returns (uint8);
/**
* @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;
/**
* @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;
/**
* @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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
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;
/**
* @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/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _governance;
event GovernanceTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_governance = msgSender;
emit GovernanceTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _governance;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_governance == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit GovernanceTransferred(_governance, newOwner);
_governance = newOwner;
}
}
// File: contracts/strategies/StabilizeStrategyTSBTCArbV1.sol
pragma solidity =0.6.6;
// This is a strategy that takes advantage of arb opportunities for tbtc and sbtc
// Strat will constantly trade between synthetic tokens using Curve
interface StabilizeStakingPool {
function notifyRewardAmount(uint256) external;
}
interface UniswapRouter {
function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory);
function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint, uint, address[] calldata, address, uint) external;
function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out
}
interface CurvePool {
function get_dy_underlying(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange_underlying(int128, int128, uint256, uint256) external; // Exchange tokens
function get_dy(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange(int128, int128, uint256, uint256) external; // Exchange tokens
}
interface AggregatorV3Interface {
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
contract StabilizeStrategyTSBTCArbV1 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
address public treasuryAddress; // Address of the treasury
address public stakingAddress; // Address to the STBZ staking pool
address public zsTokenAddress; // The address of the controlling zs-Token
uint256 constant DIVISION_FACTOR = 100000;
uint256 public lastTradeTime = 0;
uint256 public lastActionBalance = 0; // Balance before last deposit or withdraw
uint256 public percentTradeTrigger = 1000; // 1% change in value will trigger a trade
uint256 public maxPercentSell = 80000; // Up to 80% of the tokens are sold to the cheapest token
uint256 public maxAmountSell = 100e18; // The maximum amount of tokens that can be sold at once
uint256 public minTradeSplit = 1e14; // If the balance is less than or equal to this, it trades the entire balance
uint256 public gasStipend = 1500000; // This is the gas units that are covered by executing a trade taken from the WETH profit
uint256 public minGain = 1e13; // Minimum amount of gain (normalized) needed before paying executors
uint256 public maxPercentStipend = 30000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent
uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains
uint256 public percentExecutor = 10000; // 10000 = 10% of WETH goes to executor, 5% of total profit. This is on top of gas stipend
uint256 public percentStakers = 50000; // 50% of non-depositors WETH goes to stakers, can be changed
uint256 private lastTradeID = 0;
// Token information
// This strategy accepts tbtc and sbtc
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
int128 curveID; // ID in curve pool
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
// Strategy specific variables
address constant UNISWAP_ROUTER_ADDRESS = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Address of Uniswap
address constant THREE_BTC_ADDRESS = address(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714);
address constant TBTC_CURVE_ADDRESS = address(0xC25099792E9349C7DD09759744ea681C7de2cb66);
address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant WBTC_ADDRESS = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle
uint256 constant WETH_ID = 2;
constructor(
address _treasury,
address _staking,
address _zsToken
) public {
treasuryAddress = _treasury;
stakingAddress = _staking;
zsTokenAddress = _zsToken;
setupWithdrawTokens();
}
// Initialization functions
function setupWithdrawTokens() internal {
// Start with tBTC
IERC20 _token = IERC20(address(0x8dAEBADE922dF735c38C80C7eBD708Af50815fAa));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curveID: 0
})
);
// sBTC from Synthetix
_token = IERC20(address(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curveID: 3
})
);
}
// Modifier
modifier onlyZSToken() {
require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token");
_;
}
// Read functions
function rewardTokensCount() external view returns (uint256) {
return tokenList.length;
}
function rewardTokenAddress(uint256 _pos) external view returns (address) {
require(_pos < tokenList.length,"No token at that position");
return address(tokenList[_pos].token);
}
function balance() public view returns (uint256) {
return getNormalizedTotalBalance(address(this));
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
// Get the balance of the atokens+tokens at this address
uint256 _balance = 0;
uint256 _length = tokenList.length;
for(uint256 i = 0; i < _length; i++){
uint256 _bal = tokenList[i].token.balanceOf(_address);
_bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
_balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
}
return _balance;
}
function withdrawTokenReserves() public view returns (address, uint256) {
(uint256 targetID, uint256 _bal) = withdrawTokenReservesID();
if(_bal == 0){
return (address(0), _bal);
}else{
return (address(tokenList[targetID].token), _bal);
}
}
function withdrawTokenReservesID() internal view returns (uint256, uint256) {
// This function will return the address and amount of the token with the highest balance
uint256 length = tokenList.length;
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normBal > 0){
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i;
}
}
}
if(targetNormBalance > 0){
return (targetID, tokenList[targetID].token.balanceOf(address(this)));
}else{
return (0, 0); // No balance
}
}
// Write functions
function enter() external onlyZSToken {
deposit(false);
}
function exit() external onlyZSToken {
// The ZS token vault is removing all tokens from this strategy
withdraw(_msgSender(),1,1, false);
}
function deposit(bool nonContract) public onlyZSToken {
// Only the ZS token can call the function
// No trading is performed on deposit
if(nonContract == true){ }
lastActionBalance = balance();
}
function simulateExchange(uint256 _inID, uint256 _outID, uint256 _amount) internal view returns (uint256) {
if(_outID == WETH_ID){
// Sending for weth, calculate route
if(_inID == 0){
// tBTC -> WETH via Uniswap
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path = new address[](2);
path[0] = address(tokenList[0].token);
path[1] = WETH_ADDRESS;
uint256[] memory estimates = router.getAmountsOut(_amount, path);
_amount = estimates[estimates.length - 1];
return _amount;
}else{
// sBTC -> wBTC -> WETH
CurvePool pool = CurvePool(THREE_BTC_ADDRESS);
_amount = pool.get_dy(2, 1, _amount); // returns wBTC amount
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path = new address[](2);
path[0] = WBTC_ADDRESS;
path[1] = WETH_ADDRESS;
uint256[] memory estimates = router.getAmountsOut(_amount, path);
_amount = estimates[estimates.length - 1];
return _amount;
}
}else{
// Easy swap
CurvePool pool = CurvePool(TBTC_CURVE_ADDRESS);
_amount = pool.get_dy_underlying(tokenList[_inID].curveID, tokenList[_outID].curveID, _amount);
return _amount;
}
}
function exchange(uint256 _inID, uint256 _outID, uint256 _amount) internal {
if(_outID == WETH_ID){
// Sending for weth, calculate route
if(_inID == 0){
// tBTC -> WETH via Uniswap
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path = new address[](2);
path[0] = address(tokenList[0].token);
path[1] = WETH_ADDRESS;
tokenList[0].token.safeApprove(UNISWAP_ROUTER_ADDRESS, 0);
tokenList[0].token.safeApprove(UNISWAP_ROUTER_ADDRESS, _amount);
router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token
return;
}else{
// sBTC -> wBTC -> WETH
CurvePool pool = CurvePool(THREE_BTC_ADDRESS);
tokenList[1].token.safeApprove(THREE_BTC_ADDRESS, 0);
tokenList[1].token.safeApprove(THREE_BTC_ADDRESS, _amount);
uint256 _before = IERC20(WBTC_ADDRESS).balanceOf(address(this));
pool.exchange(2, 1, _amount, 1);
_amount = IERC20(WBTC_ADDRESS).balanceOf(address(this)).sub(_before); // Get wbtc amount
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path = new address[](2);
path[0] = WBTC_ADDRESS;
path[1] = WETH_ADDRESS;
IERC20(WBTC_ADDRESS).safeApprove(UNISWAP_ROUTER_ADDRESS, 0);
IERC20(WBTC_ADDRESS).safeApprove(UNISWAP_ROUTER_ADDRESS, _amount);
router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token
return;
}
}else{
// Easy swap
CurvePool pool = CurvePool(TBTC_CURVE_ADDRESS);
tokenList[_inID].token.safeApprove(TBTC_CURVE_ADDRESS, 0);
tokenList[_inID].token.safeApprove(TBTC_CURVE_ADDRESS, _amount);
pool.exchange_underlying(tokenList[_inID].curveID, tokenList[_outID].curveID, _amount, 1);
return;
}
}
function getCheaperToken() internal view returns (uint256) {
// This will give us the ID of the cheapest token on Curve
// We will estimate the return for trading 0.001
// The higher the return, the lower the price of the other token
uint256 targetID = 0;
uint256 mainAmount = minTradeSplit.mul(10**tokenList[0].decimals).div(1e18);
// Estimate sell tBTC for sBTC
uint256 estimate = 0;
estimate = simulateExchange(0,1,mainAmount);
estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[1].decimals); // Convert to main decimals
if(estimate > mainAmount){
// This token is worth less than the other token
targetID = 1;
}
return targetID;
}
function estimateSellAtMaximumProfit(uint256 originID, uint256 targetID, uint256 _tokenBalance) internal view returns (uint256) {
// This will estimate the amount that can be sold for the maximum profit possible
// We discover the price then compare it to the actual return
// The return must be positive to return a positive amount
uint256 originDecimals = tokenList[originID].decimals;
uint256 targetDecimals = tokenList[targetID].decimals;
// Discover the price with near 0 slip
uint256 _minAmount = _tokenBalance.mul(maxPercentSell.div(1000)).div(DIVISION_FACTOR);
if(_minAmount == 0){ return 0; } // Nothing to sell, can't calculate
uint256 _minReturn = _minAmount.mul(10**targetDecimals).div(10**originDecimals); // Convert decimals
uint256 _return = simulateExchange(originID, targetID, _minAmount);
if(_return <= _minReturn){
return 0; // We are not going to gain from this trade
}
_return = _return.mul(10**originDecimals).div(10**targetDecimals); // Convert to origin decimals
uint256 _startPrice = _return.mul(1e18).div(_minAmount);
// Now get the price at a higher amount, expected to be lower due to slippage
uint256 _bigAmount = _tokenBalance.mul(maxPercentSell).div(DIVISION_FACTOR);
_return = simulateExchange(originID, targetID, _bigAmount);
_return = _return.mul(10**originDecimals).div(10**targetDecimals); // Convert to origin decimals
uint256 _endPrice = _return.mul(1e18).div(_bigAmount);
if(_endPrice >= _startPrice){
// Really good liquidity
return _bigAmount;
}
// Else calculate amount at max profit
uint256 scaleFactor = uint256(1).mul(10**originDecimals);
uint256 _targetAmount = _startPrice.sub(1e18).mul(scaleFactor).div(_startPrice.sub(_endPrice).mul(scaleFactor).div(_bigAmount.sub(_minAmount))).div(2);
if(_targetAmount > _bigAmount){
// Cannot create an estimate larger than what we want to sell
return _bigAmount;
}
return _targetAmount;
}
function getFastGasPrice() internal view returns (uint256) {
AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS);
( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer
return uint256(intGasPrice);
}
function checkAndSwapTokens(address _executor, uint256 targetID) internal {
lastTradeTime = now;
uint256 gain = 0;
uint256 length = tokenList.length;
// Now sell all the other tokens into this token
uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase
bool _expectIncrease = false;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 sellBalance = 0;
uint256 _bal = tokenList[i].token.balanceOf(address(this));
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals).div(1e18);
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals).div(1e18); // Determine the maximum amount of tokens to sell at once
if(_bal <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = _bal;
}else{
sellBalance = estimateSellAtMaximumProfit(i, targetID, _bal);
}
if(sellBalance > _maxTradeTarget){
// If greater than the maximum trade allowed, match it
sellBalance = _maxTradeTarget;
}
if(sellBalance > 0){
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
uint256 estimate = simulateExchange(i, targetID, sellBalance);
if(estimate > minReceiveBalance){
_expectIncrease = true;
lastTradeID = targetID;
exchange(i, targetID, sellBalance);
}
}
}
}
uint256 _newBalance = balance();
if(_expectIncrease == true){
// There may be rare scenarios where we don't gain any by calling this function
require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
}
gain = _newBalance.sub(_totalBalance);
IERC20 weth = IERC20(WETH_ADDRESS);
uint256 _wethBalance = weth.balanceOf(address(this));
if(gain >= minGain){
// Buy WETH from Uniswap with tokens
uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
sellBalance = sellBalance.mul(DIVISION_FACTOR.sub(percentDepositor)).div(DIVISION_FACTOR);
if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){
// Sell some of our gained token for WETH
exchange(targetID, WETH_ID, sellBalance);
_wethBalance = weth.balanceOf(address(this));
}
}
if(_wethBalance > 0){
// Split the rest between the stakers and such
// This is pure profit, figure out allocation
// Split the amount sent to the treasury, stakers and executor if one exists
if(_executor != address(0)){
// Executors will get a gas reimbursement in WETH and a percent of the remaining
uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested
if(gasFee > maxGasFee){
gasFee = maxGasFee; // Gas fee cannot be greater than the maximum
}
uint256 executorAmount = gasFee;
if(gasFee >= _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR)){
executorAmount = _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point
}else{
// Add the executor percent on top of gas fee
executorAmount = _wethBalance.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee);
}
if(executorAmount > 0){
weth.safeTransfer(_executor, executorAmount);
_wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract
}
}
if(_wethBalance > 0){
uint256 stakersAmount = _wethBalance.mul(percentStakers).div(DIVISION_FACTOR);
uint256 treasuryAmount = _wethBalance.sub(stakersAmount);
if(treasuryAmount > 0){
weth.safeTransfer(treasuryAddress, treasuryAmount);
}
if(stakersAmount > 0){
if(stakingAddress != address(0)){
weth.safeTransfer(stakingAddress, stakersAmount);
StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount);
}else{
// No staking pool selected, just send to the treasury
weth.safeTransfer(treasuryAddress, stakersAmount);
}
}
}
}
}
function expectedProfit(bool inWETHForExecutor) external view returns (uint256, uint256) {
// This view will return the amount of gain a forced swap or loan will make on next call
// Now find our target token to sell into
uint256 targetID = 0;
uint256 _normalizedGain = 0;
targetID = getCheaperToken();
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 sellBalance = 0;
uint256 _bal = tokenList[i].token.balanceOf(address(this));
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals).div(1e18);
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals).div(1e18); // Determine the maximum amount of tokens to sell at once
if(_bal <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = _bal;
}else{
sellBalance = estimateSellAtMaximumProfit(i, targetID, _bal);
}
if(sellBalance > _maxTradeTarget){
// If greater than the maximum trade allowed, match it
sellBalance = _maxTradeTarget;
}
if(sellBalance > 0){
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
uint256 estimate = simulateExchange(i, targetID, sellBalance);
if(estimate > minReceiveBalance){
uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[targetID].decimals); // Normalized gain
_normalizedGain = _normalizedGain.add(_gain);
}
}
}
}
if(inWETHForExecutor == false){
return (_normalizedGain, 0); // This will be in stablecoins regardless of whether flash loan or not
}else{
if(_normalizedGain == 0){
return (0, 0);
}
// Calculate how much WETH the executor would make as profit
uint256 estimate = 0;
if(_normalizedGain > 0){
uint256 sellBalance = _normalizedGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
sellBalance = sellBalance.mul(DIVISION_FACTOR.sub(percentDepositor)).div(DIVISION_FACTOR);
// Estimate output
estimate = simulateExchange(targetID, WETH_ID, sellBalance);
}
// Now calculate the amount going to the executor
uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total
return (estimate.mul(maxPercentStipend).div(DIVISION_FACTOR), targetID); // The executor will get max percent of total
}else{
estimate = estimate.sub(gasFee); // Subtract fee from remaining balance
return (estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee), targetID); // Executor amount with fee added
}
}
}
function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) {
require(balance() > 0, "There are no tokens in this strategy");
if(nonContract == true){
if(_share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){
checkAndSwapTokens(address(0), lastTradeID);
}
}
uint256 withdrawAmount = 0;
uint256 _balance = balance();
if(_share < _total){
uint256 _myBalance = _balance.mul(_share).div(_total);
withdrawPerBalance(_depositor, _myBalance, false); // This will withdraw based on token balance
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
withdrawPerBalance(_depositor, _balance, true);
withdrawAmount = _balance;
}
lastActionBalance = balance();
return withdrawAmount;
}
// This will withdraw the tokens from the contract based on their balance, from highest balance to lowest
function withdrawPerBalance(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
uint256 length = tokenList.length;
if(_takeAll == true){
// Send the entire balance
for(uint256 i = 0; i < length; i++){
uint256 _bal = tokenList[i].token.balanceOf(address(this));
if(_bal > 0){
tokenList[i].token.safeTransfer(_receiver, _bal);
}
}
return;
}
bool[] memory done = new bool[](length);
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
targetNormBalance = 0; // Reset the target balance
// Find the highest balanced token to withdraw
for(uint256 i2 = 0; i2 < length; i2++){
if(done[i2] == false){
uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals);
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i2;
}
}
}
done[targetID] = true;
// Determine the balance left
uint256 _normalizedBalance = tokenList[targetID].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this)));
}
}else{
// Withdraw a partial amount of this token
if(_withdrawAmount > 0){
// Convert the withdraw amount to the token's decimal amount
uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18);
_withdrawAmount = 0;
tokenList[targetID].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade, uint256 _buyID) external {
// Function designed to promote trading with incentive. Users get 20% of WETH from profitable trades
require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent");
require(_msgSender() == tx.origin, "Contracts cannot interact with this function");
checkAndSwapTokens(_executor, _buyID);
}
// Governance functions
function governanceSwapTokens(uint256 _buyID) external onlyGovernance {
// This is function that force trade tokens at anytime. It can only be called by governance
checkAndSwapTokens(governance(), _buyID);
}
// Change the trading conditions used by the strategy without timelock
// --------------------
function changeTradingConditions(uint256 _pTradeTrigger,
uint256 _minSplit,
uint256 _pSellPercent,
uint256 _maxSell,
uint256 _pStipend,
uint256 _maxStipend,
uint256 _minGain) external onlyGovernance {
// Changes a lot of trading parameters in one call
require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pStipend <= 100000,"Percent cannot be greater than 100%");
percentTradeTrigger = _pTradeTrigger;
minTradeSplit = _minSplit;
maxPercentSell = _pSellPercent;
maxAmountSell = _maxSell;
maxPercentStipend = _pStipend;
gasStipend = _maxStipend;
minGain = _minGain;
}
// --------------------
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
uint256[3] private _timelock_data;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(balance() > 0){ // Timelock only applies when balance exists
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeTreasury(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
}
function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) {
treasuryAddress = _timelock_address;
}
// --------------------
// Change the staking address
// --------------------
function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) {
stakingAddress = _timelock_address;
}
// --------------------
// Change the zsToken address
// --------------------
function startChangeZSToken(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 4;
_timelock_address = _address;
}
function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) {
zsTokenAddress = _timelock_address;
}
// --------------------
// Change the strategy allocations between the parties
// --------------------
function startChangeStrategyAllocations(uint256 _pDepositors,
uint256 _pExecutor, uint256 _pStakers) external onlyGovernance {
// Changes strategy allocations in one call
require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 5;
_timelock_data[0] = _pDepositors;
_timelock_data[1] = _pExecutor;
_timelock_data[2] = _pStakers;
}
function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(5) {
percentDepositor = _timelock_data[0];
percentExecutor = _timelock_data[1];
percentStakers = _timelock_data[2];
}
// --------------------
} | -------------------- Change the staking address -------------------- | function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
| 5,721,397 |
pragma solidity ^0.6.12;
// ----------------------------------------------------------------------------
// DreamFrames Crowdsale Contract - Purchase FrameRush Tokens with ETH
//
// Deployed to : {TBA}
//
// Enjoy.
//
// (c) BokkyPooBah / Bok Consulting Pty Ltd for GazeCoin 2018. The MIT Licence.
// (c) Adrian Guerrera / Deepyr Pty Ltd for Dreamframes 2019. The MIT Licence.
// ----------------------------------------------------------------------------
import "../Shared/Operated.sol";
import "../Shared/SafeMath.sol";
import "../../interfaces/BTTSTokenInterface120.sol";
import "../../interfaces/PriceFeedInterface.sol";
import "../../interfaces/WhiteListInterface.sol";
// ----------------------------------------------------------------------------
// DreamFramesToken Crowdsale Contract
// ----------------------------------------------------------------------------
contract DreamFramesCrowdsale is Operated {
using SafeMath for uint256;
uint256 private constant TENPOW18 = 10 ** 18;
BTTSTokenInterface public dreamFramesToken;
PriceFeedInterface public ethUsdPriceFeed;
WhiteListInterface public bonusList;
address payable public wallet;
uint256 public startDate;
uint256 public endDate;
uint256 public producerPct;
uint256 public frameUsd;
uint256 public framesSold;
bool public finalised;
uint256 public bonusOffList;
uint256 public bonusOnList;
uint256 public contributedUsd;
uint256 public softCapUsd;
uint256 public hardCapUsd;
uint256 public lockedAccountThresholdUsd;
mapping(address => uint256) public accountUsdAmount;
event WalletUpdated(address indexed oldWallet, address indexed newWallet);
event StartDateUpdated(uint256 oldStartDate, uint256 newStartDate);
event EndDateUpdated(uint256 oldEndDate, uint256 newEndDate);
event FrameUsdUpdated(uint256 oldFrameUsd, uint256 newFrameUsd);
event BonusOffListUpdated(uint256 oldBonusOffList, uint256 newBonusOffList);
event BonusOnListUpdated(uint256 oldBonusOnList, uint256 newBonusOnList);
event BonusListUpdated(address oldBonusList, address newBonusList);
event Purchased(address indexed addr, uint256 frames, uint256 ethToTransfer, uint256 framesSold, uint256 contributedUsd);
constructor() public {
}
/// @notice
function init(address _dreamFramesToken, address _ethUsdPriceFeed, address payable _wallet, uint256 _startDate, uint256 _endDate, uint256 _producerPct, uint256 _frameUsd, uint256 _bonusOffList,uint256 _bonusOnList, uint256 _hardCapUsd, uint256 _softCapUsd) public {
require(_wallet != address(0));
require(_endDate > _startDate);
require(_startDate >= now);
require(_producerPct < 100);
require(_dreamFramesToken != address(0));
require(_ethUsdPriceFeed != address(0) );
initOperated(msg.sender);
dreamFramesToken = BTTSTokenInterface(_dreamFramesToken);
ethUsdPriceFeed = PriceFeedInterface(_ethUsdPriceFeed);
lockedAccountThresholdUsd = 10000;
hardCapUsd = _hardCapUsd;
softCapUsd = _softCapUsd;
frameUsd = _frameUsd;
wallet = _wallet;
startDate = _startDate;
endDate = _endDate;
producerPct = _producerPct;
bonusOffList = _bonusOffList;
bonusOnList = _bonusOnList;
}
// ----------------------------------------------------------------------------
// Setter functions
// ----------------------------------------------------------------------------
function setWallet(address payable _wallet) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_wallet != address(0));
emit WalletUpdated(wallet, _wallet);
wallet = _wallet;
}
function setStartDate(uint256 _startDate) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_startDate >= now); // dev: Already started
emit StartDateUpdated(startDate, _startDate);
startDate = _startDate;
}
function setEndDate(uint256 _endDate) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(endDate >= now); // dev: Already ended
require(_endDate > startDate); // dev: End before the start
emit EndDateUpdated(endDate, _endDate);
endDate = _endDate;
}
function setFrameUsd(uint256 _frameUsd) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_frameUsd > 0); // dev: Frame eq 0
emit FrameUsdUpdated(frameUsd, _frameUsd);
frameUsd = _frameUsd;
}
function setBonusOffList(uint256 _bonusOffList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_bonusOffList < 100); // dev: Bonus over 100
emit BonusOffListUpdated(bonusOffList, _bonusOffList);
bonusOffList = _bonusOffList;
}
function setBonusOnList(uint256 _bonusOnList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_bonusOnList < 100); // dev: Bonus over 100
emit BonusOnListUpdated(bonusOnList, _bonusOnList);
bonusOnList = _bonusOnList;
}
function setBonusList(address _bonusList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
emit BonusListUpdated(address(bonusList), _bonusList);
bonusList = WhiteListInterface(_bonusList);
}
// ----------------------------------------------------------------------------
// Getter functions
// ----------------------------------------------------------------------------
function symbol() public view returns (string memory _symbol) {
_symbol = dreamFramesToken.symbol();
}
function name() public view returns (string memory _name) {
_name = dreamFramesToken.name();
}
function usdRemaining() public view returns (uint256) {
return hardCapUsd.sub(contributedUsd);
}
function pctSold() public view returns (uint256) {
return contributedUsd.mul(100).div(hardCapUsd);
}
function pctRemaining() public view returns (uint256) {
return hardCapUsd.sub(contributedUsd).mul(100).div(hardCapUsd);
}
function getBonus(address _address) public view returns (uint256) {
if (bonusList.isInWhiteList(_address) && bonusOnList > bonusOffList ) {
return bonusOnList;
}
return bonusOffList;
}
/// @notice USD per frame, with bonus
/// @dev e.g., 128.123412344122 * 10^18
function frameUsdWithBonus(address _address) public view returns (uint256 _rate) {
uint256 bonus = getBonus(_address);
_rate = frameUsd.mul(100).div(bonus.add(100));
}
/// @notice USD per Eth from price feed
/// @dev e.g., 171.123232454415 * 10^18
function ethUsd() public view returns (uint256 _rate, bool _live) {
return ethUsdPriceFeed.getRate();
}
/// @dev ETH per frame, e.g., 2.757061128879679264 * 10^18
function frameEth() public view returns (uint256 _rate, bool _live) {
uint256 _ethUsd;
(_ethUsd, _live) = ethUsd();
if (_live) {
_rate = frameUsd.mul(TENPOW18).div(_ethUsd);
}
}
/// @dev ETH per frame, e.g., 2.757061128879679264 * 10^18 - including any bonuses
function frameEthBonus(address _address) public view returns (uint256 _rate, bool _live) {
uint256 _ethUsd;
(_ethUsd, _live) = ethUsd();
if (_live) {
_rate = frameUsdWithBonus(_address).mul(TENPOW18).div(_ethUsd);
}
}
function calculateFrames(uint256 _ethAmount) public view returns (uint256 frames, uint256 ethToTransfer) {
return calculateEthFrames(_ethAmount, msg.sender);
}
function calculateUsdFrames(uint256 _usdAmount, address _tokenOwner) public view returns (uint256 frames, uint256 usdToTransfer) {
usdToTransfer = _usdAmount;
if (contributedUsd.add(usdToTransfer) > hardCapUsd) {
usdToTransfer = hardCapUsd.sub(contributedUsd);
}
// Get number of frames available to be purchased
frames = usdToTransfer.div(frameUsdWithBonus(_tokenOwner));
}
/// @notice Get frameEth rate including any bonuses
function calculateEthFrames(uint256 _ethAmount, address _tokenOwner) public view returns (uint256 frames, uint256 ethToTransfer) {
uint256 _frameEth;
uint256 _ethUsd;
bool _live;
(_ethUsd, _live) = ethUsd();
require(_live); // dev: Pricefeed not live
(_frameEth, _live) = frameEthBonus(_tokenOwner);
require(_live); // dev: Pricefeed not live
// USD able to be spent on available frames
uint256 usdAmount = _ethAmount.mul(_ethUsd).div(TENPOW18);
(frames, usdAmount) = calculateUsdFrames(usdAmount,_tokenOwner);
// Return ETH required for available frames
ethToTransfer = frames.mul(_frameEth);
}
// ----------------------------------------------------------------------------
// Crowd sale payments
// ----------------------------------------------------------------------------
/// @notice Buy FrameTokens by sending ETH to this contract address
receive() external payable {
buyFramesEth();
}
/// @notice Or calling this function and sending ETH
function buyFramesEth() public payable {
// Get number of frames remaining
uint256 ethToTransfer;
uint256 frames;
(frames, ethToTransfer) = calculateEthFrames( msg.value, msg.sender);
// Accept ETH Payments
uint256 ethToRefund = msg.value.sub(ethToTransfer);
if (ethToTransfer > 0) {
wallet.transfer(ethToTransfer);
}
// Return any ETH to be refundedf
if (ethToRefund > 0) {
msg.sender.transfer(ethToRefund);
}
// Claim FrameTokens
claimFrames(msg.sender,frames);
emit Purchased(msg.sender, frames, ethToTransfer, framesSold, contributedUsd);
}
/// @notice Operator allocates frames to tokenOwner for offchain purchases
function offlineFramesPurchase(address _tokenOwner, uint256 _frames) external {
// Only operator and owner can allocate frames offline
require(operators[msg.sender] || owner == msg.sender); // dev: Not operator
claimFrames(_tokenOwner,_frames);
emit Purchased(_tokenOwner, _frames, 0, framesSold, contributedUsd);
}
/// @notice Contract allocates frames to tokenOwner
function claimFrames(address _tokenOwner, uint256 _frames) internal {
require(!finalised, "Sale Finalised");
require(_frames > 0, "No frames available");
require(now >= startDate && now <= endDate, "Sale ended");
// Update crowdsale state
uint256 usdToTransfer = _frames.mul(frameUsdWithBonus(_tokenOwner));
require(contributedUsd.add(usdToTransfer) <= hardCapUsd, "Exceeds Hardcap");
contributedUsd = contributedUsd.add(usdToTransfer);
// Tokens locked and KYC check required if over AccountThresholdUsd
accountUsdAmount[_tokenOwner] = accountUsdAmount[_tokenOwner].add(usdToTransfer);
bool lockAccount = accountUsdAmount[_tokenOwner] > lockedAccountThresholdUsd;
// Mint FrameTokens
require(dreamFramesToken.mint(_tokenOwner, _frames.mul(TENPOW18), lockAccount)); // dev: Not Mintable
framesSold = framesSold.add(_frames);
if (contributedUsd >= hardCapUsd) {
finalised = true;
}
}
/// @notice Contract owner finalises crowdsale
function finalise(address _producer) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised || dreamFramesToken.mintable()); // dev: Already Finalised
require(now > endDate || contributedUsd >= hardCapUsd); // dev: Not Finished
finalised = true;
uint256 totalFrames = framesSold.mul(100).div(uint256(100).sub(producerPct));
uint256 producerFrames = totalFrames.sub(framesSold);
if (producerFrames > 0 && contributedUsd >= softCapUsd ) {
require(dreamFramesToken.mint(_producer, producerFrames.mul(TENPOW18), false)); // dev: Failed final mint
}
dreamFramesToken.disableMinting();
}
}
| USD per frame, with bonus e.g., 128.123412344122 10^18 | function frameUsdWithBonus(address _address) public view returns (uint256 _rate) {
uint256 bonus = getBonus(_address);
_rate = frameUsd.mul(100).div(bonus.add(100));
}
| 7,285,657 |
pragma solidity 0.4.23;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address internal owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping(address => mapping(address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/// @title Token
/// @author Jose Perez - <[email protected]>
/// @notice ERC20 token
/// @dev The contract allows to perform a number of token sales in different periods in time.
/// allowing participants in previous token sales to transfer tokens to other accounts.
/// Additionally, token locking logic for KYC/AML compliance checking is supported.
contract Token is StandardToken, Ownable {
using SafeMath for uint256;
string public constant name = "EGB";
string public constant symbol = "EGB";
uint256 public constant decimals = 9;
// Using same number of decimal figures as ETH (i.e. 18).
uint256 public constant TOKEN_UNIT = 10 ** uint256(decimals);
// Maximum number of tokens in circulation
uint256 public constant MAX_TOKEN_SUPPLY = 1000000000 * TOKEN_UNIT;
// Maximum size of the batch functions input arrays.
uint256 public constant MAX_BATCH_SIZE = 400;
// address public assigner; // The address allowed to assign or mint tokens during token sale.
address public locker; // The address allowed to lock/unlock addresses.
mapping(address => bool) public locked; // If true, address' tokens cannot be transferred.
mapping(address => bool) public alwLockTx;
mapping(address => TxRecord[]) public txRecordPerAddress;
mapping(address => uint) public chainStartIdxPerAddress;
mapping(address => uint) public chainEndIdxPerAddress;
struct TxRecord {
uint amount;
uint releaseTime;
uint nextIdx;
uint prevIdx;
}
event Lock(address indexed addr);
event Unlock(address indexed addr);
event Assign(address indexed to, uint256 amount);
event LockerTransferred(address indexed previousLocker, address indexed newLocker);
// event AssignerTransferred(address indexed previousAssigner, address indexed newAssigner);
/// @dev Constructor that initializes the contract.
constructor() public {
locker = owner;
balances[owner] = balances[owner].add(MAX_TOKEN_SUPPLY);
recop(owner, MAX_TOKEN_SUPPLY, 0);
totalSupply_ = MAX_TOKEN_SUPPLY;
alwLT(owner, true);
}
/// @dev Throws if called by any account other than the locker.
modifier onlyLocker() {
require(msg.sender == locker);
_;
}
function isLocker() public view returns (bool) {
return msg.sender == locker;
}
/// @dev Allows the current owner to change the locker.
/// @param _newLocker The address of the new locker.
/// @return True if the operation was successful.
function transferLocker(address _newLocker) external onlyOwner returns (bool) {
require(_newLocker != address(0));
emit LockerTransferred(locker, _newLocker);
locker = _newLocker;
return true;
}
function alwLT(address _address, bool _enable) public onlyLocker returns (bool) {
alwLockTx[_address] = _enable;
return true;
}
function alwLTBatches(address[] _addresses, bool _enable) external onlyLocker returns (bool) {
require(_addresses.length > 0);
require(_addresses.length <= MAX_BATCH_SIZE);
for (uint i = 0; i < _addresses.length; i++) {
alwLT(_addresses[i], _enable);
}
return true;
}
/// @dev Locks an address. A locked address cannot transfer its tokens or other addresses' tokens out.
/// Only addresses participating in the current token sale can be locked.
/// Only the locker account can lock addresses and only during the token sale.
/// @param _address address The address to lock.
/// @return True if the operation was successful.
function lockAddress(address _address) public onlyLocker returns (bool) {
require(!locked[_address]);
locked[_address] = true;
emit Lock(_address);
return true;
}
/// @dev Unlocks an address so that its owner can transfer tokens out again.
/// Addresses can be unlocked any time. Only the locker account can unlock addresses
/// @param _address address The address to unlock.
/// @return True if the operation was successful.
function unlockAddress(address _address) public onlyLocker returns (bool) {
require(locked[_address]);
locked[_address] = false;
emit Unlock(_address);
return true;
}
/// @dev Locks several addresses in one single call.
/// @param _addresses address[] The addresses to lock.
/// @return True if the operation was successful.
function lockInBatches(address[] _addresses) external onlyLocker returns (bool) {
require(_addresses.length > 0);
require(_addresses.length <= MAX_BATCH_SIZE);
for (uint i = 0; i < _addresses.length; i++) {
lockAddress(_addresses[i]);
}
return true;
}
/// @dev Unlocks several addresses in one single call.
/// @param _addresses address[] The addresses to unlock.
/// @return True if the operation was successful.
function unlockInBatches(address[] _addresses) external onlyLocker returns (bool) {
require(_addresses.length > 0);
require(_addresses.length <= MAX_BATCH_SIZE);
for (uint i = 0; i < _addresses.length; i++) {
unlockAddress(_addresses[i]);
}
return true;
}
/// @dev Checks whether or not the given address is locked.
/// @param _address address The address to be checked.
/// @return Boolean indicating whether or not the address is locked.
function isLocked(address _address) external view returns (bool) {
return locked[_address];
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(!locked[msg.sender]);
require(_to != address(0));
return transferFT(msg.sender, _to, _value, 0);
}
function transferL(address _to, uint256 _value, uint256 lTime) public returns (bool) {
require(alwLockTx[msg.sender]);
require(!locked[msg.sender]);
require(_to != address(0));
return transferFT(msg.sender, _to, _value, lTime);
}
function getRecordInfo(address addr, uint256 index) external onlyOwner view returns (uint, uint, uint, uint) {
TxRecord memory tr = txRecordPerAddress[addr][index];
return (tr.amount, tr.prevIdx, tr.nextIdx, tr.releaseTime);
}
function delr(address _address, uint256 index) public onlyOwner returns (bool) {
require(index < txRecordPerAddress[_address].length);
TxRecord memory tr = txRecordPerAddress[_address][index];
if (index == chainStartIdxPerAddress[_address]) {
chainStartIdxPerAddress[_address] = tr.nextIdx;
} else if (index == chainEndIdxPerAddress[_address]) {
chainEndIdxPerAddress[_address] = tr.prevIdx;
} else {
txRecordPerAddress[_address][tr.prevIdx].nextIdx = tr.nextIdx;
txRecordPerAddress[_address][tr.nextIdx].prevIdx = tr.prevIdx;
}
delete txRecordPerAddress[_address][index];
balances[_address] = balances[_address].sub(tr.amount);
return true;
}
function resetTime(address _address, uint256 index, uint256 lTime) external onlyOwner returns (bool) {
require(index < txRecordPerAddress[_address].length);
TxRecord memory tr = txRecordPerAddress[_address][index];
delr(_address, index);
recop(_address, tr.amount, lTime);
balances[_address] = balances[_address].add(tr.amount);
return true;
}
function payop(address _from, uint needTakeout) private {
TxRecord memory txRecord;
for (uint idx = chainEndIdxPerAddress[_from]; true; idx = txRecord.prevIdx) {
txRecord = txRecordPerAddress[_from][idx];
if (now < txRecord.releaseTime)
break;
if (txRecord.amount <= needTakeout) {
chainEndIdxPerAddress[_from] = txRecord.prevIdx;
delete txRecordPerAddress[_from][idx];
needTakeout = needTakeout.sub(txRecord.amount);
} else {
txRecordPerAddress[_from][idx].amount = txRecord.amount.sub(needTakeout);
needTakeout = 0;
break;
}
if (idx == chainStartIdxPerAddress[_from]) {
break;
}
}
require(needTakeout == 0);
}
function recop(address _to, uint256 _value, uint256 lTime) private {
if (txRecordPerAddress[_to].length < 1) {
txRecordPerAddress[_to].push(TxRecord({amount : _value, releaseTime : now.add(lTime), nextIdx : 0, prevIdx : 0}));
chainStartIdxPerAddress[_to] = 0;
chainEndIdxPerAddress[_to] = 0;
return;
}
uint startIndex = chainStartIdxPerAddress[_to];
uint endIndex = chainEndIdxPerAddress[_to];
if (lTime == 0 && txRecordPerAddress[_to][endIndex].releaseTime < now) {
txRecordPerAddress[_to][endIndex].amount = txRecordPerAddress[_to][endIndex].amount.add(_value);
return;
}
TxRecord memory utxo = TxRecord({amount : _value, releaseTime : now.add(lTime), nextIdx : 0, prevIdx : 0});
for (uint idx = startIndex; true; idx = txRecordPerAddress[_to][idx].nextIdx) {
if (utxo.releaseTime < txRecordPerAddress[_to][idx].releaseTime) {
if (idx == chainEndIdxPerAddress[_to]) {
utxo.prevIdx = idx;
txRecordPerAddress[_to].push(utxo);
txRecordPerAddress[_to][idx].nextIdx = txRecordPerAddress[_to].length - 1;
chainEndIdxPerAddress[_to] = txRecordPerAddress[_to].length - 1;
return;
} else if (utxo.releaseTime >= txRecordPerAddress[_to][txRecordPerAddress[_to][idx].nextIdx].releaseTime) {
utxo.prevIdx = idx;
utxo.nextIdx = txRecordPerAddress[_to][idx].nextIdx;
txRecordPerAddress[_to].push(utxo);
txRecordPerAddress[_to][txRecordPerAddress[_to][idx].nextIdx].prevIdx = txRecordPerAddress[_to].length - 1;
txRecordPerAddress[_to][idx].nextIdx = txRecordPerAddress[_to].length - 1;
return;
}
} else {
if (idx == startIndex) {
utxo.nextIdx = idx;
txRecordPerAddress[_to].push(utxo);
txRecordPerAddress[_to][idx].prevIdx = txRecordPerAddress[_to].length - 1;
chainStartIdxPerAddress[_to] = txRecordPerAddress[_to].length - 1;
return;
}
}
if (idx == chainEndIdxPerAddress[_to]) {
return;
}
}
}
function transferFT(address _from, address _to, uint256 _value, uint256 lTime) private returns (bool) {
payop(_from, _value);
balances[_from] = balances[_from].sub(_value);
recop(_to, _value, lTime);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function txRecordCount(address add) public onlyOwner view returns (uint){
return txRecordPerAddress[add].length;
}
/// @dev Transfers tokens from one address to another. It prevents transferring tokens if the caller is locked or
/// if the allowed address is locked.
/// Locked addresses can receive tokens.
/// Current token sale's addresses cannot receive or send tokens until the token sale ends.
/// @param _from address The address to transfer tokens from.
/// @param _to address The address to transfer tokens to.
/// @param _value The number of tokens to be transferred.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(!locked[msg.sender]);
require(!locked[_from]);
require(_to != address(0));
require(_from != _to);
super.transferFrom(_from, _to, _value);
return transferFT(_from, _to, _value, 0);
}
function kill() onlyOwner {
selfdestruct(owner);
}
} | Checks whether or not the given address is locked. _address address The address to be checked. return Boolean indicating whether or not the address is locked. | function isLocked(address _address) external view returns (bool) {
return locked[_address];
}
| 14,092,824 |
// SPDX-License-Identifier: AGPL-3.0-only
/*
Bounty.sol - SKALE Manager
Copyright (C) 2020-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./delegation/DelegationController.sol";
import "./delegation/PartialDifferences.sol";
import "./delegation/TimeHelpers.sol";
import "./delegation/ValidatorService.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./Permissions.sol";
contract BountyV2 is Permissions {
using PartialDifferences for PartialDifferences.Value;
using PartialDifferences for PartialDifferences.Sequence;
struct BountyHistory {
uint month;
uint bountyPaid;
}
uint public constant YEAR1_BOUNTY = 3850e5 * 1e18;
uint public constant YEAR2_BOUNTY = 3465e5 * 1e18;
uint public constant YEAR3_BOUNTY = 3080e5 * 1e18;
uint public constant YEAR4_BOUNTY = 2695e5 * 1e18;
uint public constant YEAR5_BOUNTY = 2310e5 * 1e18;
uint public constant YEAR6_BOUNTY = 1925e5 * 1e18;
uint public constant EPOCHS_PER_YEAR = 12;
uint public constant SECONDS_PER_DAY = 24 * 60 * 60;
uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY;
uint private _nextEpoch;
uint private _epochPool;
uint private _bountyWasPaidInCurrentEpoch;
bool public bountyReduction;
uint public nodeCreationWindowSeconds;
PartialDifferences.Value private _effectiveDelegatedSum;
// validatorId amount of nodes
mapping (uint => uint) public nodesByValidator; // deprecated
// validatorId => BountyHistory
mapping (uint => BountyHistory) private _bountyHistory;
bytes32 public constant BOUNTY_REDUCTION_MANAGER_ROLE = keccak256("BOUNTY_REDUCTION_MANAGER_ROLE");
modifier onlyBountyReductionManager() {
require(hasRole(BOUNTY_REDUCTION_MANAGER_ROLE, msg.sender), "BOUNTY_REDUCTION_MANAGER_ROLE is required");
_;
}
function calculateBounty(uint nodeIndex)
external
allow("SkaleManager")
returns (uint)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
require(
_getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now,
"Transaction is sent too early"
);
uint validatorId = nodes.getValidatorId(nodeIndex);
if (nodesByValidator[validatorId] > 0) {
delete nodesByValidator[validatorId];
}
uint currentMonth = timeHelpers.getCurrentMonth();
_refillEpochPool(currentMonth, timeHelpers, constantsHolder);
_prepareBountyHistory(validatorId, currentMonth);
uint bounty = _calculateMaximumBountyAmount(
_epochPool,
_effectiveDelegatedSum.getAndUpdateValue(currentMonth),
_bountyWasPaidInCurrentEpoch,
nodeIndex,
_bountyHistory[validatorId].bountyPaid,
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getAndUpdateDelegatedToValidatorNow(validatorId),
constantsHolder,
nodes
);
_bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty);
bounty = _reduceBounty(
bounty,
nodeIndex,
nodes,
constantsHolder
);
_epochPool = _epochPool.sub(bounty);
_bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty);
return bounty;
}
function enableBountyReduction() external onlyBountyReductionManager {
bountyReduction = true;
}
function disableBountyReduction() external onlyBountyReductionManager {
bountyReduction = false;
}
function setNodeCreationWindowSeconds(uint window) external allow("Nodes") {
nodeCreationWindowSeconds = window;
}
function handleDelegationAdd(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.addToValue(amount, month);
}
function handleDelegationRemoving(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.subtractFromValue(amount, month);
}
function estimateBounty(uint nodeIndex) external view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint currentMonth = timeHelpers.getCurrentMonth();
uint validatorId = nodes.getValidatorId(nodeIndex);
uint stagePoolSize;
(stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
return _calculateMaximumBountyAmount(
stagePoolSize,
_effectiveDelegatedSum.getValue(currentMonth),
_nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0,
nodeIndex,
_getBountyPaid(validatorId, currentMonth),
delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getDelegatedToValidator(validatorId, currentMonth),
constantsHolder,
nodes
);
}
function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) {
return _getNextRewardTimestamp(
nodeIndex,
Nodes(contractManager.getContract("Nodes")),
TimeHelpers(contractManager.getContract("TimeHelpers"))
);
}
function getEffectiveDelegatedSum() external view returns (uint[] memory) {
return _effectiveDelegatedSum.getValues();
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
_nextEpoch = 0;
_epochPool = 0;
_bountyWasPaidInCurrentEpoch = 0;
bountyReduction = false;
nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY;
}
// private
function _calculateMaximumBountyAmount(
uint epochPoolSize,
uint effectiveDelegatedSum,
uint bountyWasPaidInCurrentEpoch,
uint nodeIndex,
uint bountyPaidToTheValidator,
uint effectiveDelegated,
uint delegated,
ConstantsHolder constantsHolder,
Nodes nodes
)
private
view
returns (uint)
{
if (nodes.isNodeLeft(nodeIndex)) {
return 0;
}
if (now < constantsHolder.launchTimestamp()) {
// network is not launched
// bounty is turned off
return 0;
}
if (effectiveDelegatedSum == 0) {
// no delegations in the system
return 0;
}
if (constantsHolder.msr() == 0) {
return 0;
}
uint bounty = _calculateBountyShare(
epochPoolSize.add(bountyWasPaidInCurrentEpoch),
effectiveDelegated,
effectiveDelegatedSum,
delegated.div(constantsHolder.msr()),
bountyPaidToTheValidator
);
return bounty;
}
function _calculateBountyShare(
uint monthBounty,
uint effectiveDelegated,
uint effectiveDelegatedSum,
uint maxNodesAmount,
uint paidToValidator
)
private
pure
returns (uint)
{
if (maxNodesAmount > 0) {
uint totalBountyShare = monthBounty
.mul(effectiveDelegated)
.div(effectiveDelegatedSum);
return _min(
totalBountyShare.div(maxNodesAmount),
totalBountyShare.sub(paidToValidator)
);
} else {
return 0;
}
}
function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) {
return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp());
}
function _getEpochPool(
uint currentMonth,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint epochPool, uint nextEpoch)
{
epochPool = _epochPool;
for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) {
epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder));
}
}
function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private {
uint epochPool;
uint nextEpoch;
(epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
if (_nextEpoch < nextEpoch) {
(_epochPool, _nextEpoch) = (epochPool, nextEpoch);
_bountyWasPaidInCurrentEpoch = 0;
}
}
function _getEpochReward(
uint epoch,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint)
{
uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder);
if (epoch < firstEpoch) {
return 0;
}
uint epochIndex = epoch.sub(firstEpoch);
uint year = epochIndex.div(EPOCHS_PER_YEAR);
if (year >= 6) {
uint power = year.sub(6).div(3).add(1);
if (power < 256) {
return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR);
} else {
return 0;
}
} else {
uint[6] memory customBounties = [
YEAR1_BOUNTY,
YEAR2_BOUNTY,
YEAR3_BOUNTY,
YEAR4_BOUNTY,
YEAR5_BOUNTY,
YEAR6_BOUNTY
];
return customBounties[year].div(EPOCHS_PER_YEAR);
}
}
function _reduceBounty(
uint bounty,
uint nodeIndex,
Nodes nodes,
ConstantsHolder constants
)
private
returns (uint reducedBounty)
{
if (!bountyReduction) {
return bounty;
}
reducedBounty = bounty;
if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) {
reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT());
}
}
function _prepareBountyHistory(uint validatorId, uint currentMonth) private {
if (_bountyHistory[validatorId].month < currentMonth) {
_bountyHistory[validatorId].month = currentMonth;
delete _bountyHistory[validatorId].bountyPaid;
}
}
function _getBountyPaid(uint validatorId, uint month) private view returns (uint) {
require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid");
if (_bountyHistory[validatorId].month == month) {
return _bountyHistory[validatorId].bountyPaid;
} else {
return 0;
}
}
function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) {
uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex);
uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp);
uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth);
uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart);
uint currentMonth = timeHelpers.getCurrentMonth();
assert(lastRewardMonth <= currentMonth);
if (lastRewardMonth == currentMonth) {
uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1));
uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2));
if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) {
return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS);
} else {
return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS));
}
} else if (lastRewardMonth.add(1) == currentMonth) {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1));
return _min(
currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)),
currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS)
);
} else {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
return currentMonthStart.add(nodeCreationWindowSeconds);
}
}
function _min(uint a, uint b) private pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
function _max(uint a, uint b) private pure returns (uint) {
if (a < b) {
return b;
} else {
return a;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationController.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../BountyV2.sol";
import "../Nodes.sol";
import "../Permissions.sol";
import "../utils/FractionUtils.sol";
import "../utils/MathUtils.sol";
import "./DelegationPeriodManager.sol";
import "./PartialDifferences.sol";
import "./Punisher.sol";
import "./TokenState.sol";
import "./ValidatorService.sol";
/**
* @title Delegation Controller
* @dev This contract performs all delegation functions including delegation
* requests, and undelegation, etc.
*
* Delegators and validators may both perform delegations. Validators who perform
* delegations to themselves are effectively self-delegating or self-bonding.
*
* IMPORTANT: Undelegation may be requested at any time, but undelegation is only
* performed at the completion of the current delegation period.
*
* Delegated tokens may be in one of several states:
*
* - PROPOSED: token holder proposes tokens to delegate to a validator.
* - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation.
* - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator.
* - REJECTED: token proposal expires at the UTC start of the next month.
* - DELEGATED: accepted delegations are delegated at the UTC start of the month.
* - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator.
* - COMPLETED: undelegation request is completed at the end of the delegation period.
*/
contract DelegationController is Permissions, ILocker {
using MathUtils for uint;
using PartialDifferences for PartialDifferences.Sequence;
using PartialDifferences for PartialDifferences.Value;
using FractionUtils for FractionUtils.Fraction;
uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60;
enum State {
PROPOSED,
ACCEPTED,
CANCELED,
REJECTED,
DELEGATED,
UNDELEGATION_REQUESTED,
COMPLETED
}
struct Delegation {
address holder; // address of token owner
uint validatorId;
uint amount;
uint delegationPeriod;
uint created; // time of delegation creation
uint started; // month when a delegation becomes active
uint finished; // first month after a delegation ends
string info;
}
struct SlashingLogEvent {
FractionUtils.Fraction reducingCoefficient;
uint nextMonth;
}
struct SlashingLog {
// month => slashing event
mapping (uint => SlashingLogEvent) slashes;
uint firstMonth;
uint lastMonth;
}
struct DelegationExtras {
uint lastSlashingMonthBeforeDelegation;
}
struct SlashingEvent {
FractionUtils.Fraction reducingCoefficient;
uint validatorId;
uint month;
}
struct SlashingSignal {
address holder;
uint penalty;
}
struct LockedInPending {
uint amount;
uint month;
}
struct FirstDelegationMonth {
// month
uint value;
//validatorId => month
mapping (uint => uint) byValidator;
}
struct ValidatorsStatistics {
// number of validators
uint number;
//validatorId => bool - is Delegated or not
mapping (uint => uint) delegated;
}
/**
* @dev Emitted when a delegation is proposed to a validator.
*/
event DelegationProposed(
uint delegationId
);
/**
* @dev Emitted when a delegation is accepted by a validator.
*/
event DelegationAccepted(
uint delegationId
);
/**
* @dev Emitted when a delegation is cancelled by the delegator.
*/
event DelegationRequestCanceledByUser(
uint delegationId
);
/**
* @dev Emitted when a delegation is requested to undelegate.
*/
event UndelegationRequested(
uint delegationId
);
/// @dev delegations will never be deleted to index in this array may be used like delegation id
Delegation[] public delegations;
// validatorId => delegationId[]
mapping (uint => uint[]) public delegationsByValidator;
// holder => delegationId[]
mapping (address => uint[]) public delegationsByHolder;
// delegationId => extras
mapping(uint => DelegationExtras) private _delegationExtras;
// validatorId => sequence
mapping (uint => PartialDifferences.Value) private _delegatedToValidator;
// validatorId => sequence
mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator;
// validatorId => slashing log
mapping (uint => SlashingLog) private _slashesOfValidator;
// holder => sequence
mapping (address => PartialDifferences.Value) private _delegatedByHolder;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator;
SlashingEvent[] private _slashes;
// holder => index in _slashes;
mapping (address => uint) private _firstUnprocessedSlashByHolder;
// holder => validatorId => month
mapping (address => FirstDelegationMonth) private _firstDelegationMonth;
// holder => locked in pending
mapping (address => LockedInPending) private _lockedInPendingDelegations;
mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator;
/**
* @dev Modifier to make a function callable only if delegation exists.
*/
modifier checkDelegationExists(uint delegationId) {
require(delegationId < delegations.length, "Delegation does not exist");
_;
}
/**
* @dev Update and return a validator's delegations.
*/
function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth());
}
/**
* @dev Update and return the amount delegated.
*/
function getAndUpdateDelegatedAmount(address holder) external returns (uint) {
return _getAndUpdateDelegatedByHolder(holder);
}
/**
* @dev Update and return the effective amount delegated (minus slash) for
* the given month.
*/
function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external
allow("Distributor") returns (uint effectiveDelegated)
{
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder);
effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId]
.getAndUpdateValueInSequence(month);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev Allows a token holder to create a delegation proposal of an `amount`
* and `delegationPeriod` to a `validatorId`. Delegation must be accepted
* by the validator before the UTC start of the month, otherwise the
* delegation will be rejected.
*
* The token holder may add additional information in each proposal.
*
* Emits a {DelegationProposed} event.
*
* Requirements:
*
* - Holder must have sufficient delegatable tokens.
* - Delegation must be above the validator's minimum delegation amount.
* - Delegation period must be allowed.
* - Validator must be authorized if trusted list is enabled.
* - Validator must be accepting new delegation requests.
*/
function delegate(
uint validatorId,
uint amount,
uint delegationPeriod,
string calldata info
)
external
{
require(
_getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod),
"This delegation period is not allowed");
_getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount);
_checkIfDelegationIsAllowed(msg.sender, validatorId);
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender);
uint delegationId = _addDelegation(
msg.sender,
validatorId,
amount,
delegationPeriod,
info);
// check that there is enough money
uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender);
uint forbiddenForDelegation = TokenState(contractManager.getTokenState())
.getAndUpdateForbiddenForDelegationAmount(msg.sender);
require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate");
emit DelegationProposed(delegationId);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows token holder to cancel a delegation proposal.
*
* Emits a {DelegationRequestCanceledByUser} event.
*
* Requirements:
*
* - `msg.sender` must be the token holder of the delegation proposal.
* - Delegation state must be PROPOSED.
*/
function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request");
require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations");
delegations[delegationId].finished = _getCurrentMonth();
_subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
emit DelegationRequestCanceledByUser(delegationId);
}
/**
* @dev Allows a validator to accept a proposed delegation.
* Successful acceptance of delegations transition the tokens from a
* PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the
* delegation period.
*
* Emits a {DelegationAccepted} event.
*
* Requirements:
*
* - Validator must be recipient of proposal.
* - Delegation state must be PROPOSED.
*/
function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(
_getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId),
"No permissions to accept request");
_accept(delegationId);
}
/**
* @dev Allows delegator to undelegate a specific delegation.
*
* Emits UndelegationRequested event.
*
* Requirements:
*
* - `msg.sender` must be the delegator.
* - Delegation state must be DELEGATED.
*/
function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation");
ValidatorService validatorService = _getValidatorService();
require(
delegations[delegationId].holder == msg.sender ||
(validatorService.validatorAddressExists(msg.sender) &&
delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)),
"Permission denied to request undelegation");
_removeValidatorFromValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId);
processAllSlashes(msg.sender);
delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId);
require(
now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS)
< _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished),
"Undelegation requests must be sent 3 days before the end of delegation period"
);
_subtractFromAllStatistics(delegationId);
emit UndelegationRequested(delegationId);
}
/**
* @dev Allows Punisher contract to slash an `amount` of stake from
* a validator. This slashes an amount of delegations of the validator,
* which reduces the amount that the validator has staked. This consequence
* may force the SKALE Manager to reduce the number of nodes a validator is
* operating so the validator can meet the Minimum Staking Requirement.
*
* Emits a {SlashingEvent}.
*
* See {Punisher}.
*/
function confiscate(uint validatorId, uint amount) external allow("Punisher") {
uint currentMonth = _getCurrentMonth();
FractionUtils.Fraction memory coefficient =
_delegatedToValidator[validatorId].reduceValue(amount, currentMonth);
uint initialEffectiveDelegated =
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth);
uint[] memory initialSubtractions = new uint[](0);
if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) {
initialSubtractions = new uint[](
_effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth)
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId]
.subtractDiff[currentMonth.add(i).add(1)];
}
}
_effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth);
_putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth);
_slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth}));
BountyV2 bounty = _getBounty();
bounty.handleDelegationRemoving(
initialEffectiveDelegated.sub(
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth)
),
currentMonth
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
bounty.handleDelegationAdd(
initialSubtractions[i].sub(
_effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)]
),
currentMonth.add(i).add(1)
);
}
}
/**
* @dev Allows Distributor contract to return and update the effective
* amount delegated (minus slash) to a validator for a given month.
*/
function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month)
external allowTwo("Bounty", "Distributor") returns (uint)
{
return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month);
}
/**
* @dev Return and update the amount delegated to a validator for the
* current month.
*/
function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth());
}
function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) {
return _effectiveDelegatedToValidator[validatorId].getValuesInSequence();
}
function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month);
}
function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _delegatedToValidator[validatorId].getValue(month);
}
/**
* @dev Return Delegation struct.
*/
function getDelegation(uint delegationId)
external view checkDelegationExists(delegationId) returns (Delegation memory)
{
return delegations[delegationId];
}
/**
* @dev Returns the first delegation month.
*/
function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) {
return _firstDelegationMonth[holder].byValidator[validatorId];
}
/**
* @dev Returns a validator's total number of delegations.
*/
function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) {
return delegationsByValidator[validatorId].length;
}
/**
* @dev Returns a holder's total number of delegations.
*/
function getDelegationsByHolderLength(address holder) external view returns (uint) {
return delegationsByHolder[holder].length;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
/**
* @dev Process slashes up to the given limit.
*/
function processSlashes(address holder, uint limit) public {
_sendSlashingSignals(_processSlashesWithoutSignals(holder, limit));
}
/**
* @dev Process all slashes.
*/
function processAllSlashes(address holder) public {
processSlashes(holder, 0);
}
/**
* @dev Returns the token state of a given delegation.
*/
function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) {
if (delegations[delegationId].started == 0) {
if (delegations[delegationId].finished == 0) {
if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) {
return State.PROPOSED;
} else {
return State.REJECTED;
}
} else {
return State.CANCELED;
}
} else {
if (_getCurrentMonth() < delegations[delegationId].started) {
return State.ACCEPTED;
} else {
if (delegations[delegationId].finished == 0) {
return State.DELEGATED;
} else {
if (_getCurrentMonth() < delegations[delegationId].finished) {
return State.UNDELEGATION_REQUESTED;
} else {
return State.COMPLETED;
}
}
}
}
}
/**
* @dev Returns the amount of tokens in PENDING delegation state.
*/
function getLockedInPendingDelegations(address holder) public view returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
return 0;
} else {
return _lockedInPendingDelegations[holder].amount;
}
}
/**
* @dev Checks whether there are any unprocessed slashes.
*/
function hasUnprocessedSlashes(address holder) public view returns (bool) {
return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length;
}
// private
/**
* @dev Allows Nodes contract to get and update the amount delegated
* to validator for a given month.
*/
function _getAndUpdateDelegatedToValidator(uint validatorId, uint month)
private returns (uint)
{
return _delegatedToValidator[validatorId].getAndUpdateValue(month);
}
/**
* @dev Adds a new delegation proposal.
*/
function _addDelegation(
address holder,
uint validatorId,
uint amount,
uint delegationPeriod,
string memory info
)
private
returns (uint delegationId)
{
delegationId = delegations.length;
delegations.push(Delegation(
holder,
validatorId,
amount,
delegationPeriod,
now,
0,
0,
info
));
delegationsByValidator[validatorId].push(delegationId);
delegationsByHolder[holder].push(delegationId);
_addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
}
/**
* @dev Returns the month when a delegation ends.
*/
function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) {
uint currentMonth = _getCurrentMonth();
uint started = delegations[delegationId].started;
if (currentMonth < started) {
return started.add(delegations[delegationId].delegationPeriod);
} else {
uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod);
return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod));
}
}
function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].addToValue(amount, month);
}
function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month);
}
function _addToDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].addToValue(amount, month);
}
function _addToDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month);
}
function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1);
}
function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].subtractFromValue(amount, month);
}
function _removeFromDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month);
}
function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1);
}
function _addToEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month);
}
function _removeFromEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month);
}
function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) {
uint currentMonth = _getCurrentMonth();
processAllSlashes(holder);
return _delegatedByHolder[holder].getAndUpdateValue(currentMonth);
}
function _getAndUpdateDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint month)
private returns (uint)
{
return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month);
}
function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
_lockedInPendingDelegations[holder].amount = amount;
_lockedInPendingDelegations[holder].month = currentMonth;
} else {
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount);
}
}
function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount);
}
function _getCurrentMonth() private view returns (uint) {
return _getTimeHelpers().getCurrentMonth();
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet));
}
function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private {
if (_firstDelegationMonth[holder].value == 0) {
_firstDelegationMonth[holder].value = month;
_firstUnprocessedSlashByHolder[holder] = _slashes.length;
}
if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) {
_firstDelegationMonth[holder].byValidator[validatorId] = month;
}
}
/**
* @dev Checks whether the holder has performed a delegation.
*/
function _everDelegated(address holder) private view returns (bool) {
return _firstDelegationMonth[holder].value > 0;
}
function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].subtractFromValue(amount, month);
}
function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month);
}
/**
* @dev Returns the delegated amount after a slashing event.
*/
function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) {
uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation;
uint validatorId = delegations[delegationId].validatorId;
uint amount = delegations[delegationId].amount;
if (startMonth == 0) {
startMonth = _slashesOfValidator[validatorId].firstMonth;
if (startMonth == 0) {
return amount;
}
}
for (uint i = startMonth;
i > 0 && i < delegations[delegationId].finished;
i = _slashesOfValidator[validatorId].slashes[i].nextMonth) {
if (i >= delegations[delegationId].started) {
amount = amount
.mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator)
.div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator);
}
}
return amount;
}
function _putToSlashingLog(
SlashingLog storage log,
FractionUtils.Fraction memory coefficient,
uint month)
private
{
if (log.firstMonth == 0) {
log.firstMonth = month;
log.lastMonth = month;
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
} else {
require(log.lastMonth <= month, "Cannot put slashing event in the past");
if (log.lastMonth == month) {
log.slashes[month].reducingCoefficient =
log.slashes[month].reducingCoefficient.multiplyFraction(coefficient);
} else {
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
log.slashes[log.lastMonth].nextMonth = month;
log.lastMonth = month;
}
}
}
function _processSlashesWithoutSignals(address holder, uint limit)
private returns (SlashingSignal[] memory slashingSignals)
{
if (hasUnprocessedSlashes(holder)) {
uint index = _firstUnprocessedSlashByHolder[holder];
uint end = _slashes.length;
if (limit > 0 && index.add(limit) < end) {
end = index.add(limit);
}
slashingSignals = new SlashingSignal[](end.sub(index));
uint begin = index;
for (; index < end; ++index) {
uint validatorId = _slashes[index].validatorId;
uint month = _slashes[index].month;
uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month);
if (oldValue.muchGreater(0)) {
_delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum(
_delegatedByHolder[holder],
_slashes[index].reducingCoefficient,
month);
_effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence(
_slashes[index].reducingCoefficient,
month);
slashingSignals[index.sub(begin)].holder = holder;
slashingSignals[index.sub(begin)].penalty
= oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month));
}
}
_firstUnprocessedSlashByHolder[holder] = end;
}
}
function _processAllSlashesWithoutSignals(address holder)
private returns (SlashingSignal[] memory slashingSignals)
{
return _processSlashesWithoutSignals(holder, 0);
}
function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private {
Punisher punisher = Punisher(contractManager.getPunisher());
address previousHolder = address(0);
uint accumulatedPenalty = 0;
for (uint i = 0; i < slashingSignals.length; ++i) {
if (slashingSignals[i].holder != previousHolder) {
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
previousHolder = slashingSignals[i].holder;
accumulatedPenalty = slashingSignals[i].penalty;
} else {
accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty);
}
}
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
}
function _addToAllStatistics(uint delegationId) private {
uint currentMonth = _getCurrentMonth();
delegations[delegationId].started = currentMonth.add(1);
if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) {
_delegationExtras[delegationId].lastSlashingMonthBeforeDelegation =
_slashesOfValidator[delegations[delegationId].validatorId].lastMonth;
}
_addToDelegatedToValidator(
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolder(
delegations[delegationId].holder,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_updateFirstDelegationMonth(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
currentMonth.add(1));
uint effectiveAmount = delegations[delegationId].amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_addToEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addToEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addValidatorToValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId
);
}
function _subtractFromAllStatistics(uint delegationId) private {
uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId);
_removeFromDelegatedToValidator(
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolder(
delegations[delegationId].holder,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
uint effectiveAmount = amountAfterSlashing.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_removeFromEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_removeFromEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_getBounty().handleDelegationRemoving(
effectiveAmount,
delegations[delegationId].finished);
}
/**
* @dev Checks whether delegation to a validator is allowed.
*
* Requirements:
*
* - Delegator must not have reached the validator limit.
* - Delegation must be made in or after the first delegation month.
*/
function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) {
require(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 ||
(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 &&
_numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator()
),
"Limit of validators is reached"
);
}
function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) {
return DelegationPeriodManager(contractManager.getDelegationPeriodManager());
}
function _getBounty() private view returns (BountyV2) {
return BountyV2(contractManager.getBounty());
}
function _getValidatorService() private view returns (ValidatorService) {
return ValidatorService(contractManager.getValidatorService());
}
function _getTimeHelpers() private view returns (TimeHelpers) {
return TimeHelpers(contractManager.getTimeHelpers());
}
function _getConstantsHolder() private view returns (ConstantsHolder) {
return ConstantsHolder(contractManager.getConstantsHolder());
}
function _accept(uint delegationId) private {
_checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId);
State currentState = getState(delegationId);
if (currentState != State.PROPOSED) {
if (currentState == State.ACCEPTED ||
currentState == State.DELEGATED ||
currentState == State.UNDELEGATION_REQUESTED ||
currentState == State.COMPLETED)
{
revert("The delegation has been already accepted");
} else if (currentState == State.CANCELED) {
revert("The delegation has been cancelled by token holder");
} else if (currentState == State.REJECTED) {
revert("The delegation request is outdated");
}
}
require(currentState == State.PROPOSED, "Cannot set delegation state to accepted");
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder);
_addToAllStatistics(delegationId);
uint amount = delegations[delegationId].amount;
uint effectiveAmount = amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)
);
_getBounty().handleDelegationAdd(
effectiveAmount,
delegations[delegationId].started
);
_sendSlashingSignals(slashingSignals);
emit DelegationAccepted(delegationId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
PartialDifferences.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../utils/MathUtils.sol";
import "../utils/FractionUtils.sol";
/**
* @title Partial Differences Library
* @dev This library contains functions to manage Partial Differences data
* structure. Partial Differences is an array of value differences over time.
*
* For example: assuming an array [3, 6, 3, 1, 2], partial differences can
* represent this array as [_, 3, -3, -2, 1].
*
* This data structure allows adding values on an open interval with O(1)
* complexity.
*
* For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3),
* instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows
* performing [_, 3, -3+5, -2, 1]. The original array can be restored by
* adding values from partial differences.
*/
library PartialDifferences {
using SafeMath for uint;
using MathUtils for uint;
struct Sequence {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
// month => value
mapping (uint => uint) value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
struct Value {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
uint value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
// functions for sequence
function addToSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.value[i] != nextValue) {
sequence.value[i] = nextValue;
}
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value[month];
}
function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value[month];
}
}
function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceSequence(
Sequence storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValueInSequence(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
sequence.value[month] = sequence.value[month]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
sequence.subtractDiff[i] = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
}
}
// functions for value
function addToValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
} else {
sequence.value = sequence.value.add(diff);
}
}
function subtractFromValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
} else {
sequence.value = sequence.value.boundedSub(diff);
}
}
function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value != value) {
sequence.value = value;
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value;
}
function getValue(Value storage sequence, uint month) internal view returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value;
}
}
function getValues(Value storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value;
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceValue(
Value storage sequence,
uint amount,
uint month)
internal returns (FractionUtils.Fraction memory)
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return FractionUtils.createFraction(0);
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return FractionUtils.createFraction(0);
}
uint _amount = amount;
if (value < amount) {
_amount = value;
}
FractionUtils.Fraction memory reducingCoefficient =
FractionUtils.createFraction(value.boundedSub(_amount), value);
reduceValueByCoefficient(sequence, reducingCoefficient, month);
return reducingCoefficient;
}
function reduceValueByCoefficient(
Value storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month)
internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sequence,
reducingCoefficient,
month,
false);
}
function reduceValueByCoefficientAndUpdateSum(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sumSequence,
reducingCoefficient,
month,
true);
}
function reduceValueByCoefficientAndUpdateSumIfNeeded(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month,
bool hasSumSequence) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (hasSumSequence) {
require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past");
}
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator);
if (hasSumSequence) {
subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month);
}
sequence.value = newValue;
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
uint newDiff = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
if (hasSumSequence) {
sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i]
.boundedSub(sequence.subtractDiff[i].boundedSub(newDiff));
}
sequence.subtractDiff[i] = newDiff;
}
}
function clear(Value storage sequence) internal {
for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) {
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value > 0) {
delete sequence.value;
}
if (sequence.firstUnprocessedMonth > 0) {
delete sequence.firstUnprocessedMonth;
}
if (sequence.lastChangedMonth > 0) {
delete sequence.lastChangedMonth;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TimeHelpers.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol";
/**
* @title TimeHelpers
* @dev The contract performs time operations.
*
* These functions are used to calculate monthly and Proof of Use epochs.
*/
contract TimeHelpers {
using SafeMath for uint;
uint constant private _ZERO_YEAR = 2020;
function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) {
timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays);
}
function addDays(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n);
}
function addMonths(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n);
}
function addYears(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n);
}
function getCurrentMonth() external view virtual returns (uint) {
return timestampToMonth(now);
}
function timestampToDay(uint timestamp) external view returns (uint) {
uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) /
BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
require(wholeDays >= zeroDay, "Timestamp is too far in the past");
return wholeDays - zeroDay;
}
function timestampToYear(uint timestamp) external view virtual returns (uint) {
uint year;
(year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
return year - _ZERO_YEAR;
}
function timestampToMonth(uint timestamp) public view virtual returns (uint) {
uint year;
uint month;
(year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12));
require(month > 0, "Timestamp is too far in the past");
return month;
}
function monthToTimestamp(uint month) public view virtual returns (uint timestamp) {
uint year = _ZERO_YEAR;
uint _month = month;
year = year.add(_month.div(12));
_month = _month.mod(12);
_month = _month.add(1);
return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ValidatorService.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title ValidatorService
* @dev This contract handles all validator operations including registration,
* node management, validator-specific delegation parameters, and more.
*
* TIP: For more information see our main instructions
* https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ].
*
* Validators register an address, and use this address to accept delegations and
* register nodes.
*/
contract ValidatorService is Permissions {
using ECDSA for bytes32;
struct Validator {
string name;
address validatorAddress;
address requestedAddress;
string description;
uint feeRate;
uint registrationTime;
uint minimumDelegationAmount;
bool acceptNewRequests;
}
/**
* @dev Emitted when a validator registers.
*/
event ValidatorRegistered(
uint validatorId
);
/**
* @dev Emitted when a validator address changes.
*/
event ValidatorAddressChanged(
uint validatorId,
address newAddress
);
/**
* @dev Emitted when a validator is enabled.
*/
event ValidatorWasEnabled(
uint validatorId
);
/**
* @dev Emitted when a validator is disabled.
*/
event ValidatorWasDisabled(
uint validatorId
);
/**
* @dev Emitted when a node address is linked to a validator.
*/
event NodeAddressWasAdded(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when a node address is unlinked from a validator.
*/
event NodeAddressWasRemoved(
uint validatorId,
address nodeAddress
);
mapping (uint => Validator) public validators;
mapping (uint => bool) private _trustedValidators;
uint[] public trustedValidatorsList;
// address => validatorId
mapping (address => uint) private _validatorAddressToId;
// address => validatorId
mapping (address => uint) private _nodeAddressToValidatorId;
// validatorId => nodeAddress[]
mapping (uint => address[]) private _nodeAddresses;
uint public numberOfValidators;
bool public useWhitelist;
bytes32 public constant VALIDATOR_MANAGER_ROLE = keccak256("VALIDATOR_MANAGER_ROLE");
modifier onlyValidatorManager() {
require(hasRole(VALIDATOR_MANAGER_ROLE, msg.sender), "VALIDATOR_MANAGER_ROLE is required");
_;
}
modifier checkValidatorExists(uint validatorId) {
require(validatorExists(validatorId), "Validator with such ID does not exist");
_;
}
/**
* @dev Creates a new validator ID that includes a validator name, description,
* commission or fee rate, and a minimum delegation amount accepted by the validator.
*
* Emits a {ValidatorRegistered} event.
*
* Requirements:
*
* - Sender must not already have registered a validator ID.
* - Fee rate must be between 0 - 1000‰. Note: in per mille.
*/
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId)
{
require(!validatorAddressExists(msg.sender), "Validator with such address already exists");
require(feeRate <= 1000, "Fee rate of validator should be lower than 100%");
validatorId = ++numberOfValidators;
validators[validatorId] = Validator(
name,
msg.sender,
address(0),
description,
feeRate,
now,
minimumDelegationAmount,
true
);
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorRegistered(validatorId);
}
/**
* @dev Allows Admin to enable a validator by adding their ID to the
* trusted list.
*
* Emits a {ValidatorWasEnabled} event.
*
* Requirements:
*
* - Validator must not already be enabled.
*/
function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager {
require(!_trustedValidators[validatorId], "Validator is already enabled");
_trustedValidators[validatorId] = true;
trustedValidatorsList.push(validatorId);
emit ValidatorWasEnabled(validatorId);
}
/**
* @dev Allows Admin to disable a validator by removing their ID from
* the trusted list.
*
* Emits a {ValidatorWasDisabled} event.
*
* Requirements:
*
* - Validator must not already be disabled.
*/
function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager {
require(_trustedValidators[validatorId], "Validator is already disabled");
_trustedValidators[validatorId] = false;
uint position = _find(trustedValidatorsList, validatorId);
if (position < trustedValidatorsList.length) {
trustedValidatorsList[position] =
trustedValidatorsList[trustedValidatorsList.length.sub(1)];
}
trustedValidatorsList.pop();
emit ValidatorWasDisabled(validatorId);
}
/**
* @dev Owner can disable the trusted validator list. Once turned off, the
* trusted list cannot be re-enabled.
*/
function disableWhitelist() external onlyValidatorManager {
useWhitelist = false;
}
/**
* @dev Allows `msg.sender` to request a new address.
*
* Requirements:
*
* - `msg.sender` must already be a validator.
* - New address must not be null.
* - New address must not be already registered as a validator.
*/
function requestForNewAddress(address newValidatorAddress) external {
require(newValidatorAddress != address(0), "New address cannot be null");
require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered");
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].requestedAddress = newValidatorAddress;
}
/**
* @dev Allows msg.sender to confirm an address change.
*
* Emits a {ValidatorAddressChanged} event.
*
* Requirements:
*
* - Must be owner of new address.
*/
function confirmNewAddress(uint validatorId)
external
checkValidatorExists(validatorId)
{
require(
getValidator(validatorId).requestedAddress == msg.sender,
"The validator address cannot be changed because it is not the actual owner"
);
delete validators[validatorId].requestedAddress;
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress);
}
/**
* @dev Links a node address to validator ID. Validator must present
* the node signature of the validator ID.
*
* Requirements:
*
* - Signature must be valid.
* - Address must not be assigned to a validator.
*/
function linkNodeAddress(address nodeAddress, bytes calldata sig) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(
keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress,
"Signature is not pass"
);
require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator");
_addNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasAdded(validatorId, nodeAddress);
}
/**
* @dev Unlinks a node address from a validator.
*
* Emits a {NodeAddressWasRemoved} event.
*/
function unlinkNodeAddress(address nodeAddress) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
this.removeNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasRemoved(validatorId, nodeAddress);
}
/**
* @dev Allows a validator to set a minimum delegation amount.
*/
function setValidatorMDA(uint minimumDelegationAmount) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].minimumDelegationAmount = minimumDelegationAmount;
}
/**
* @dev Allows a validator to set a new validator name.
*/
function setValidatorName(string calldata newName) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].name = newName;
}
/**
* @dev Allows a validator to set a new validator description.
*/
function setValidatorDescription(string calldata newDescription) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].description = newDescription;
}
/**
* @dev Allows a validator to start accepting new delegation requests.
*
* Requirements:
*
* - Must not have already enabled accepting new requests.
*/
function startAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled");
validators[validatorId].acceptNewRequests = true;
}
/**
* @dev Allows a validator to stop accepting new delegation requests.
*
* Requirements:
*
* - Must not have already stopped accepting new requests.
*/
function stopAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled");
validators[validatorId].acceptNewRequests = false;
}
function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") {
require(_nodeAddressToValidatorId[nodeAddress] == validatorId,
"Validator does not have permissions to unlink node");
delete _nodeAddressToValidatorId[nodeAddress];
for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) {
if (_nodeAddresses[validatorId][i] == nodeAddress) {
if (i + 1 < _nodeAddresses[validatorId].length) {
_nodeAddresses[validatorId][i] =
_nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
}
delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
_nodeAddresses[validatorId].pop();
break;
}
}
}
/**
* @dev Returns the amount of validator bond (self-delegation).
*/
function getAndUpdateBondAmount(uint validatorId)
external
returns (uint)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
return delegationController.getAndUpdateDelegatedByHolderToValidatorNow(
getValidator(validatorId).validatorAddress,
validatorId
);
}
/**
* @dev Returns node addresses linked to the msg.sender.
*/
function getMyNodesAddresses() external view returns (address[] memory) {
return getNodeAddresses(getValidatorId(msg.sender));
}
/**
* @dev Returns the list of trusted validators.
*/
function getTrustedValidators() external view returns (uint[] memory) {
return trustedValidatorsList;
}
/**
* @dev Checks whether the validator ID is linked to the validator address.
*/
function checkValidatorAddressToId(address validatorAddress, uint validatorId)
external
view
returns (bool)
{
return getValidatorId(validatorAddress) == validatorId ? true : false;
}
/**
* @dev Returns the validator ID linked to a node address.
*
* Requirements:
*
* - Node address must be linked to a validator.
*/
function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) {
validatorId = _nodeAddressToValidatorId[nodeAddress];
require(validatorId != 0, "Node address is not assigned to a validator");
}
function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view {
require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request");
require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests");
require(
validators[validatorId].minimumDelegationAmount <= amount,
"Amount does not meet the validator's minimum delegation amount"
);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
useWhitelist = true;
}
/**
* @dev Returns a validator's node addresses.
*/
function getNodeAddresses(uint validatorId) public view returns (address[] memory) {
return _nodeAddresses[validatorId];
}
/**
* @dev Checks whether validator ID exists.
*/
function validatorExists(uint validatorId) public view returns (bool) {
return validatorId <= numberOfValidators && validatorId != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function validatorAddressExists(address validatorAddress) public view returns (bool) {
return _validatorAddressToId[validatorAddress] != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function checkIfValidatorAddressExists(address validatorAddress) public view {
require(validatorAddressExists(validatorAddress), "Validator address does not exist");
}
/**
* @dev Returns the Validator struct.
*/
function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) {
return validators[validatorId];
}
/**
* @dev Returns the validator ID for the given validator address.
*/
function getValidatorId(address validatorAddress) public view returns (uint) {
checkIfValidatorAddressExists(validatorAddress);
return _validatorAddressToId[validatorAddress];
}
/**
* @dev Checks whether the validator is currently accepting new delegation requests.
*/
function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return validators[validatorId].acceptNewRequests;
}
function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return _trustedValidators[validatorId] || !useWhitelist;
}
// private
/**
* @dev Links a validator address to a validator ID.
*
* Requirements:
*
* - Address is not already in use by another validator.
*/
function _setValidatorAddress(uint validatorId, address validatorAddress) private {
if (_validatorAddressToId[validatorAddress] == validatorId) {
return;
}
require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator");
address oldAddress = validators[validatorId].validatorAddress;
delete _validatorAddressToId[oldAddress];
_nodeAddressToValidatorId[validatorAddress] = validatorId;
validators[validatorId].validatorAddress = validatorAddress;
_validatorAddressToId[validatorAddress] = validatorId;
}
/**
* @dev Links a node address to a validator ID.
*
* Requirements:
*
* - Node address must not be already linked to a validator.
*/
function _addNodeAddress(uint validatorId, address nodeAddress) private {
if (_nodeAddressToValidatorId[nodeAddress] == validatorId) {
return;
}
require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address");
_nodeAddressToValidatorId[nodeAddress] = validatorId;
_nodeAddresses[validatorId].push(nodeAddress);
}
function _find(uint[] memory array, uint index) private pure returns (uint) {
uint i;
for (i = 0; i < array.length; i++) {
if (array[i] == index) {
return i;
}
}
return array.length;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ConstantsHolder.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
/**
* @title ConstantsHolder
* @dev Contract contains constants and common variables for the SKALE Network.
*/
contract ConstantsHolder is Permissions {
// initial price for creating Node (100 SKL)
uint public constant NODE_DEPOSIT = 100 * 1e18;
uint8 public constant TOTAL_SPACE_ON_NODE = 128;
// part of Node for Small Skale-chain (1/128 of Node)
uint8 public constant SMALL_DIVISOR = 128;
// part of Node for Medium Skale-chain (1/32 of Node)
uint8 public constant MEDIUM_DIVISOR = 32;
// part of Node for Large Skale-chain (full Node)
uint8 public constant LARGE_DIVISOR = 1;
// part of Node for Medium Test Skale-chain (1/4 of Node)
uint8 public constant MEDIUM_TEST_DIVISOR = 4;
// typically number of Nodes for Skale-chain (16 Nodes)
uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16;
// number of Nodes for Test Skale-chain (2 Nodes)
uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2;
// number of Nodes for Test Skale-chain (4 Nodes)
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
// number of seconds in one year
uint32 public constant SECONDS_TO_YEAR = 31622400;
// initial number of monitors
uint public constant NUMBER_OF_MONITORS = 24;
uint public constant OPTIMAL_LOAD_PERCENTAGE = 80;
uint public constant ADJUSTMENT_SPEED = 1000;
uint public constant COOLDOWN_TIME = 60;
uint public constant MIN_PRICE = 10**6;
uint public constant MSR_REDUCING_COEFFICIENT = 2;
uint public constant DOWNTIME_THRESHOLD_PART = 30;
uint public constant BOUNTY_LOCKUP_MONTHS = 2;
uint public constant ALRIGHT_DELTA = 62893;
uint public constant BROADCAST_DELTA = 131000;
uint public constant COMPLAINT_BAD_DATA_DELTA = 49580;
uint public constant PRE_RESPONSE_DELTA = 74500;
uint public constant COMPLAINT_DELTA = 76221;
uint public constant RESPONSE_DELTA = 183000;
// MSR - Minimum staking requirement
uint public msr;
// Reward period - 30 days (each 30 days Node would be granted for bounty)
uint32 public rewardPeriod;
// Allowable latency - 150000 ms by default
uint32 public allowableLatency;
/**
* Delta period - 1 hour (1 hour before Reward period became Monitors need
* to send Verdicts and 1 hour after Reward period became Node need to come
* and get Bounty)
*/
uint32 public deltaPeriod;
/**
* Check time - 2 minutes (every 2 minutes monitors should check metrics
* from checked nodes)
*/
uint public checkTime;
//Need to add minimal allowed parameters for verdicts
uint public launchTimestamp;
uint public rotationDelay;
uint public proofOfUseLockUpPeriodDays;
uint public proofOfUseDelegationPercentage;
uint public limitValidatorsPerDelegator;
uint256 public firstDelegationsMonth; // deprecated
// date when schains will be allowed for creation
uint public schainCreationTimeStamp;
uint public minimalSchainLifetime;
uint public complaintTimelimit;
bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE");
modifier onlyConstantsHolderManager() {
require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required");
_;
}
/**
* @dev Allows the Owner to set new reward and delta periods
* This function is only for tests.
*/
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyConstantsHolderManager {
require(
newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime,
"Incorrect Periods"
);
rewardPeriod = newRewardPeriod;
deltaPeriod = newDeltaPeriod;
}
/**
* @dev Allows the Owner to set the new check time.
* This function is only for tests.
*/
function setCheckTime(uint newCheckTime) external onlyConstantsHolderManager {
require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time");
checkTime = newCheckTime;
}
/**
* @dev Allows the Owner to set the allowable latency in milliseconds.
* This function is only for testing purposes.
*/
function setLatency(uint32 newAllowableLatency) external onlyConstantsHolderManager {
allowableLatency = newAllowableLatency;
}
/**
* @dev Allows the Owner to set the minimum stake requirement.
*/
function setMSR(uint newMSR) external onlyConstantsHolderManager {
msr = newMSR;
}
/**
* @dev Allows the Owner to set the launch timestamp.
*/
function setLaunchTimestamp(uint timestamp) external onlyConstantsHolderManager {
require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched");
launchTimestamp = timestamp;
}
/**
* @dev Allows the Owner to set the node rotation delay.
*/
function setRotationDelay(uint newDelay) external onlyConstantsHolderManager {
rotationDelay = newDelay;
}
/**
* @dev Allows the Owner to set the proof-of-use lockup period.
*/
function setProofOfUseLockUpPeriod(uint periodDays) external onlyConstantsHolderManager {
proofOfUseLockUpPeriodDays = periodDays;
}
/**
* @dev Allows the Owner to set the proof-of-use delegation percentage
* requirement.
*/
function setProofOfUseDelegationPercentage(uint percentage) external onlyConstantsHolderManager {
require(percentage <= 100, "Percentage value is incorrect");
proofOfUseDelegationPercentage = percentage;
}
/**
* @dev Allows the Owner to set the maximum number of validators that a
* single delegator can delegate to.
*/
function setLimitValidatorsPerDelegator(uint newLimit) external onlyConstantsHolderManager {
limitValidatorsPerDelegator = newLimit;
}
function setSchainCreationTimeStamp(uint timestamp) external onlyConstantsHolderManager {
schainCreationTimeStamp = timestamp;
}
function setMinimalSchainLifetime(uint lifetime) external onlyConstantsHolderManager {
minimalSchainLifetime = lifetime;
}
function setComplaintTimelimit(uint timelimit) external onlyConstantsHolderManager {
complaintTimelimit = timelimit;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
msr = 0;
rewardPeriod = 2592000;
allowableLatency = 150000;
deltaPeriod = 3600;
checkTime = 300;
launchTimestamp = uint(-1);
rotationDelay = 12 hours;
proofOfUseLockUpPeriodDays = 90;
proofOfUseDelegationPercentage = 50;
limitValidatorsPerDelegator = 20;
firstDelegationsMonth = 0;
complaintTimelimit = 1800;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Nodes.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol";
import "./delegation/DelegationController.sol";
import "./delegation/ValidatorService.sol";
import "./utils/Random.sol";
import "./utils/SegmentTree.sol";
import "./BountyV2.sol";
import "./ConstantsHolder.sol";
import "./Permissions.sol";
/**
* @title Nodes
* @dev This contract contains all logic to manage SKALE Network nodes states,
* space availability, stake requirement checks, and exit functions.
*
* Nodes may be in one of several states:
*
* - Active: Node is registered and is in network operation.
* - Leaving: Node has begun exiting from the network.
* - Left: Node has left the network.
* - In_Maintenance: Node is temporarily offline or undergoing infrastructure
* maintenance
*
* Note: Online nodes contain both Active and Leaving states.
*/
contract Nodes is Permissions {
using Random for Random.RandomGenerator;
using SafeCast for uint;
using SegmentTree for SegmentTree.Tree;
// All Nodes states
enum NodeStatus {Active, Leaving, Left, In_Maintenance}
struct Node {
string name;
bytes4 ip;
bytes4 publicIP;
uint16 port;
bytes32[2] publicKey;
uint startBlock;
uint lastRewardDate;
uint finishTime;
NodeStatus status;
uint validatorId;
}
// struct to note which Nodes and which number of Nodes owned by user
struct CreatedNodes {
mapping (uint => bool) isNodeExist;
uint numberOfNodes;
}
struct SpaceManaging {
uint8 freeSpace;
uint indexInSpaceMap;
}
// TODO: move outside the contract
struct NodeCreationParams {
string name;
bytes4 ip;
bytes4 publicIp;
uint16 port;
bytes32[2] publicKey;
uint16 nonce;
string domainName;
}
bytes32 constant public COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE");
bytes32 public constant NODE_MANAGER_ROLE = keccak256("NODE_MANAGER_ROLE");
// array which contain all Nodes
Node[] public nodes;
SpaceManaging[] public spaceOfNodes;
// mapping for checking which Nodes and which number of Nodes owned by user
mapping (address => CreatedNodes) public nodeIndexes;
// mapping for checking is IP address busy
mapping (bytes4 => bool) public nodesIPCheck;
// mapping for checking is Name busy
mapping (bytes32 => bool) public nodesNameCheck;
// mapping for indication from Name to Index
mapping (bytes32 => uint) public nodesNameToIndex;
// mapping for indication from space to Nodes
mapping (uint8 => uint[]) public spaceToNodes;
mapping (uint => uint[]) public validatorToNodeIndexes;
uint public numberOfActiveNodes;
uint public numberOfLeavingNodes;
uint public numberOfLeftNodes;
mapping (uint => string) public domainNames;
mapping (uint => bool) private _invisible;
SegmentTree.Tree private _nodesAmountBySpace;
mapping (uint => bool) public incompliant;
/**
* @dev Emitted when a node is created.
*/
event NodeCreated(
uint nodeIndex,
address owner,
string name,
bytes4 ip,
bytes4 publicIP,
uint16 port,
uint16 nonce,
string domainName,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node completes a network exit.
*/
event ExitCompleted(
uint nodeIndex,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node begins to exit from the network.
*/
event ExitInitialized(
uint nodeIndex,
uint startLeavingPeriod,
uint time,
uint gasSpend
);
modifier checkNodeExists(uint nodeIndex) {
_checkNodeIndex(nodeIndex);
_;
}
modifier onlyNodeOrNodeManager(uint nodeIndex) {
_checkNodeOrNodeManager(nodeIndex, msg.sender);
_;
}
modifier onlyCompliance() {
require(hasRole(COMPLIANCE_ROLE, msg.sender), "COMPLIANCE_ROLE is required");
_;
}
modifier nonZeroIP(bytes4 ip) {
require(ip != 0x0 && !nodesIPCheck[ip], "IP address is zero or is not available");
_;
}
/**
* @dev Allows Schains and SchainsInternal contracts to occupy available
* space on a node.
*
* Returns whether operation is successful.
*/
function removeSpaceFromNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allowTwo("NodeRotation", "SchainsInternal")
returns (bool)
{
if (spaceOfNodes[nodeIndex].freeSpace < space) {
return false;
}
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8()
);
}
return true;
}
/**
* @dev Allows Schains contract to occupy free space on a node.
*
* Returns whether operation is successful.
*/
function addSpaceToNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allowTwo("Schains", "NodeRotation")
{
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8()
);
}
}
/**
* @dev Allows SkaleManager to change a node's last reward date.
*/
function changeNodeLastRewardDate(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].lastRewardDate = block.timestamp;
}
/**
* @dev Allows SkaleManager to change a node's finish time.
*/
function changeNodeFinishTime(uint nodeIndex, uint time)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].finishTime = time;
}
/**
* @dev Allows SkaleManager contract to create new node and add it to the
* Nodes contract.
*
* Emits a {NodeCreated} event.
*
* Requirements:
*
* - Node IP must be non-zero.
* - Node IP must be available.
* - Node name must not already be registered.
* - Node port must be greater than zero.
*/
function createNode(address from, NodeCreationParams calldata params)
external
allow("SkaleManager")
nonZeroIP(params.ip)
{
// checks that Node has correct data
require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered");
require(params.port > 0, "Port is zero");
require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect");
uint validatorId = ValidatorService(
contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from);
uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE();
nodes.push(Node({
name: params.name,
ip: params.ip,
publicIP: params.publicIp,
port: params.port,
publicKey: params.publicKey,
startBlock: block.number,
lastRewardDate: block.timestamp,
finishTime: 0,
status: NodeStatus.Active,
validatorId: validatorId
}));
uint nodeIndex = nodes.length.sub(1);
validatorToNodeIndexes[validatorId].push(nodeIndex);
bytes32 nodeId = keccak256(abi.encodePacked(params.name));
nodesIPCheck[params.ip] = true;
nodesNameCheck[nodeId] = true;
nodesNameToIndex[nodeId] = nodeIndex;
nodeIndexes[from].isNodeExist[nodeIndex] = true;
nodeIndexes[from].numberOfNodes++;
domainNames[nodeIndex] = params.domainName;
spaceOfNodes.push(SpaceManaging({
freeSpace: totalSpace,
indexInSpaceMap: spaceToNodes[totalSpace].length
}));
_setNodeActive(nodeIndex);
emit NodeCreated(
nodeIndex,
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.nonce,
params.domainName,
block.timestamp,
gasleft());
}
/**
* @dev Allows SkaleManager contract to initiate a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitInitialized} event.
*/
function initExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeActive(nodeIndex), "Node should be Active");
_setNodeLeaving(nodeIndex);
emit ExitInitialized(
nodeIndex,
block.timestamp,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to complete a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitCompleted} event.
*
* Requirements:
*
* - Node must have already initialized a node exit procedure.
*/
function completeExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeLeaving(nodeIndex), "Node is not Leaving");
_setNodeLeft(nodeIndex);
emit ExitCompleted(
nodeIndex,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to delete a validator's node.
*
* Requirements:
*
* - Validator ID must exist.
*/
function deleteNodeForValidator(uint validatorId, uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
if (position < validatorNodes.length) {
validatorToNodeIndexes[validatorId][position] =
validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)];
}
validatorToNodeIndexes[validatorId].pop();
address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey);
if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) {
if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) {
validatorService.removeNodeAddress(validatorId, nodeOwner);
}
nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false;
nodeIndexes[nodeOwner].numberOfNodes--;
}
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to create another node.
*
* Requirements:
*
* - Validator must be included on trusted list if trusted list is enabled.
* - Validator must have sufficient stake to operate an additional node.
*/
function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress);
require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node");
require(
_checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length),
"Validator must meet the Minimum Staking Requirement");
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to maintain a node.
*
* Returns whether validator can maintain node with current stake.
*
* Requirements:
*
* - Validator ID and nodeIndex must both exist.
*/
function checkPossibilityToMaintainNode(
uint validatorId,
uint nodeIndex
)
external
checkNodeExists(nodeIndex)
allow("Bounty")
returns (bool)
{
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
require(position < validatorNodes.length, "Node does not exist for this Validator");
return _checkValidatorPositionToMaintainNode(validatorId, position);
}
/**
* @dev Allows Node to set In_Maintenance status.
*
* Requirements:
*
* - Node must already be Active.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active");
_setNodeInMaintenance(nodeIndex);
}
/**
* @dev Allows Node to remove In_Maintenance status.
*
* Requirements:
*
* - Node must already be In Maintenance.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance");
_setNodeActive(nodeIndex);
}
/**
* @dev Marks the node as incompliant
*
*/
function setNodeIncompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) {
if (!incompliant[nodeIndex]) {
incompliant[nodeIndex] = true;
_makeNodeInvisible(nodeIndex);
}
}
/**
* @dev Marks the node as compliant
*
*/
function setNodeCompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) {
if (incompliant[nodeIndex]) {
incompliant[nodeIndex] = false;
_tryToMakeNodeVisible(nodeIndex);
}
}
function setDomainName(uint nodeIndex, string memory domainName)
external
onlyNodeOrNodeManager(nodeIndex)
{
domainNames[nodeIndex] = domainName;
}
function makeNodeVisible(uint nodeIndex) external allow("SchainsInternal") {
_tryToMakeNodeVisible(nodeIndex);
}
function makeNodeInvisible(uint nodeIndex) external allow("SchainsInternal") {
_makeNodeInvisible(nodeIndex);
}
function changeIP(
uint nodeIndex,
bytes4 newIP,
bytes4 newPublicIP
)
external
onlyAdmin
checkNodeExists(nodeIndex)
nonZeroIP(newIP)
{
if (newPublicIP != 0x0) {
require(newIP == newPublicIP, "IP address is not the same");
nodes[nodeIndex].publicIP = newPublicIP;
}
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesIPCheck[newIP] = true;
nodes[nodeIndex].ip = newIP;
}
function getRandomNodeWithFreeSpace(
uint8 freeSpace,
Random.RandomGenerator memory randomGenerator
)
external
view
returns (uint)
{
uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast(
freeSpace == 0 ? 1 : freeSpace,
randomGenerator
).toUint8();
require(place > 0, "Node not found");
return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)];
}
/**
* @dev Checks whether it is time for a node's reward.
*/
function isTimeForReward(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now;
}
/**
* @dev Returns IP address of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeIP(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes4)
{
require(nodeIndex < nodes.length, "Node does not exist");
return nodes[nodeIndex].ip;
}
/**
* @dev Returns domain name of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeDomainName(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (string memory)
{
return domainNames[nodeIndex];
}
/**
* @dev Returns the port of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodePort(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint16)
{
return nodes[nodeIndex].port;
}
/**
* @dev Returns the public key of a given node.
*/
function getNodePublicKey(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes32[2] memory)
{
return nodes[nodeIndex].publicKey;
}
/**
* @dev Returns an address of a given node.
*/
function getNodeAddress(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (address)
{
return _publicKeyToAddress(nodes[nodeIndex].publicKey);
}
/**
* @dev Returns the finish exit time of a given node.
*/
function getNodeFinishTime(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].finishTime;
}
/**
* @dev Checks whether a node has left the network.
*/
function isNodeLeft(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Left;
}
function isNodeInMaintenance(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.In_Maintenance;
}
/**
* @dev Returns a given node's last reward date.
*/
function getNodeLastRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].lastRewardDate;
}
/**
* @dev Returns a given node's next reward date.
*/
function getNodeNextRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex);
}
/**
* @dev Returns the total number of registered nodes.
*/
function getNumberOfNodes() external view returns (uint) {
return nodes.length;
}
/**
* @dev Returns the total number of online nodes.
*
* Note: Online nodes are equal to the number of active plus leaving nodes.
*/
function getNumberOnlineNodes() external view returns (uint) {
return numberOfActiveNodes.add(numberOfLeavingNodes);
}
/**
* @dev Return active node IDs.
*/
function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) {
activeNodeIds = new uint[](numberOfActiveNodes);
uint indexOfActiveNodeIds = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIds[indexOfActiveNodeIds] = indexOfNodes;
indexOfActiveNodeIds++;
}
}
}
/**
* @dev Return a given node's current status.
*/
function getNodeStatus(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (NodeStatus)
{
return nodes[nodeIndex].status;
}
/**
* @dev Return a validator's linked nodes.
*
* Requirements:
*
* - Validator ID must exist.
*/
function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
return validatorToNodeIndexes[validatorId];
}
/**
* @dev Returns number of nodes with available space.
*/
function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) {
if (freeSpace == 0) {
return _nodesAmountBySpace.sumFromPlaceToLast(1);
}
return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace);
}
/**
* @dev constructor in Permissions approach.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
numberOfActiveNodes = 0;
numberOfLeavingNodes = 0;
numberOfLeftNodes = 0;
_nodesAmountBySpace.create(128);
}
/**
* @dev Returns the Validator ID for a given node.
*/
function getValidatorId(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].validatorId;
}
/**
* @dev Checks whether a node exists for a given address.
*/
function isNodeExist(address from, uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodeIndexes[from].isNodeExist[nodeIndex];
}
/**
* @dev Checks whether a node's status is Active.
*/
function isNodeActive(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Active;
}
/**
* @dev Checks whether a node's status is Leaving.
*/
function isNodeLeaving(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Leaving;
}
function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal {
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
uint len = spaceToNodes[space].length.sub(1);
if (indexInArray < len) {
uint shiftedIndex = spaceToNodes[space][len];
spaceToNodes[space][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
}
spaceToNodes[space].pop();
delete spaceOfNodes[nodeIndex].indexInSpaceMap;
}
function _getNodesAmountBySpace() internal view returns (SegmentTree.Tree storage) {
return _nodesAmountBySpace;
}
/**
* @dev Returns the index of a given node within the validator's node index.
*/
function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) {
uint i;
for (i = 0; i < validatorNodeIndexes.length; i++) {
if (validatorNodeIndexes[i] == nodeIndex) {
return i;
}
}
return validatorNodeIndexes.length;
}
/**
* @dev Moves a node to a new space mapping.
*/
function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromTree(space);
_addNodeToTree(newSpace);
_removeNodeFromSpaceToNodes(nodeIndex, space);
_addNodeToSpaceToNodes(nodeIndex, newSpace);
}
spaceOfNodes[nodeIndex].freeSpace = newSpace;
}
/**
* @dev Changes a node's status to Active.
*/
function _setNodeActive(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Active;
numberOfActiveNodes = numberOfActiveNodes.add(1);
if (_invisible[nodeIndex]) {
_tryToMakeNodeVisible(nodeIndex);
} else {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
}
}
/**
* @dev Changes a node's status to In_Maintenance.
*/
function _setNodeInMaintenance(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.In_Maintenance;
numberOfActiveNodes = numberOfActiveNodes.sub(1);
_makeNodeInvisible(nodeIndex);
}
/**
* @dev Changes a node's status to Left.
*/
function _setNodeLeft(uint nodeIndex) private {
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false;
delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))];
if (nodes[nodeIndex].status == NodeStatus.Active) {
numberOfActiveNodes--;
} else {
numberOfLeavingNodes--;
}
nodes[nodeIndex].status = NodeStatus.Left;
numberOfLeftNodes++;
delete spaceOfNodes[nodeIndex].freeSpace;
}
/**
* @dev Changes a node's status to Leaving.
*/
function _setNodeLeaving(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Leaving;
numberOfActiveNodes--;
numberOfLeavingNodes++;
_makeNodeInvisible(nodeIndex);
}
function _makeNodeInvisible(uint nodeIndex) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromSpaceToNodes(nodeIndex, space);
_removeNodeFromTree(space);
_invisible[nodeIndex] = true;
}
}
function _tryToMakeNodeVisible(uint nodeIndex) private {
if (_invisible[nodeIndex] && _canBeVisible(nodeIndex)) {
_makeNodeVisible(nodeIndex);
}
}
function _makeNodeVisible(uint nodeIndex) private {
if (_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
delete _invisible[nodeIndex];
}
}
function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private {
spaceToNodes[space].push(nodeIndex);
spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length.sub(1);
}
function _addNodeToTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.addToPlace(space, 1);
}
}
function _removeNodeFromTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.removeFromPlace(space, 1);
}
}
function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = ConstantsHolder(contractManager.getConstantsHolder()).msr();
return position.add(1).mul(msr) <= delegationsTotal;
}
function _checkNodeIndex(uint nodeIndex) private view {
require(nodeIndex < nodes.length, "Node with such index does not exist");
}
function _checkNodeOrNodeManager(uint nodeIndex, address sender) private view {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(
isNodeExist(sender, nodeIndex) ||
hasRole(NODE_MANAGER_ROLE, msg.sender) ||
getValidatorId(nodeIndex) == validatorService.getValidatorId(sender),
"Sender is not permitted to call this function"
);
}
function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1]));
bytes20 addr;
for (uint8 i = 12; i < 32; i++) {
addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8);
}
return address(addr);
}
function _canBeVisible(uint nodeIndex) private view returns (bool) {
return !incompliant[nodeIndex] && nodes[nodeIndex].status == NodeStatus.Active;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Permissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "./ContractManager.sol";
/**
* @title Permissions
* @dev Contract is connected module for Upgradeable approach, knows ContractManager
*/
contract Permissions is AccessControlUpgradeSafe {
using SafeMath for uint;
using Address for address;
ContractManager public contractManager;
/**
* @dev Modifier to make a function callable only when caller is the Owner.
*
* Requirements:
*
* - The caller must be the owner.
*/
modifier onlyOwner() {
require(_isOwner(), "Caller is not the owner");
_;
}
/**
* @dev Modifier to make a function callable only when caller is an Admin.
*
* Requirements:
*
* - The caller must be an admin.
*/
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "Caller is not an admin");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName` contract.
*
* Requirements:
*
* - The caller must be the owner or `contractName`.
*/
modifier allow(string memory contractName) {
require(
contractManager.getContract(contractName) == msg.sender || _isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1` or `contractName2` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, or `contractName2`.
*/
modifier allowTwo(string memory contractName1, string memory contractName2) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1`, `contractName2`, or `contractName3` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, `contractName2`, or
* `contractName3`.
*/
modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
contractManager.getContract(contractName3) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
function initialize(address contractManagerAddress) public virtual initializer {
AccessControlUpgradeSafe.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setContractManager(contractManagerAddress);
}
function _isOwner() internal view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function _isAdmin(address account) internal view returns (bool) {
address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager")));
if (skaleManagerAddress != address(0)) {
AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress);
return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner();
} else {
return _isOwner();
}
}
function _setContractManager(address contractManagerAddress) private {
require(contractManagerAddress != address(0), "ContractManager address is not set");
require(contractManagerAddress.isContract(), "Address is not contract");
contractManager = ContractManager(contractManagerAddress);
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FractionUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library FractionUtils {
using SafeMath for uint;
struct Fraction {
uint numerator;
uint denominator;
}
function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) {
require(denominator > 0, "Division by zero");
Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator});
reduceFraction(fraction);
return fraction;
}
function createFraction(uint value) internal pure returns (Fraction memory) {
return createFraction(value, 1);
}
function reduceFraction(Fraction memory fraction) internal pure {
uint _gcd = gcd(fraction.numerator, fraction.denominator);
fraction.numerator = fraction.numerator.div(_gcd);
fraction.denominator = fraction.denominator.div(_gcd);
}
// numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1
function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) {
return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator));
}
function gcd(uint a, uint b) internal pure returns (uint) {
uint _a = a;
uint _b = b;
if (_b > _a) {
(_a, _b) = swap(_a, _b);
}
while (_b > 0) {
_a = _a.mod(_b);
(_a, _b) = swap (_a, _b);
}
return _a;
}
function swap(uint a, uint b) internal pure returns (uint, uint) {
return (b, a);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
MathUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library MathUtils {
uint constant private _EPS = 1e6;
event UnderflowError(
uint a,
uint b
);
function boundedSub(uint256 a, uint256 b) internal returns (uint256) {
if (a >= b) {
return a - b;
} else {
emit UnderflowError(a, b);
return 0;
}
}
function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a - b;
} else {
return 0;
}
}
function muchGreater(uint256 a, uint256 b) internal pure returns (bool) {
assert(uint(-1) - _EPS > b);
return a > b + _EPS;
}
function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) {
if (a > b) {
return a - b < _EPS;
} else {
return b - a < _EPS;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationPeriodManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../ConstantsHolder.sol";
/**
* @title Delegation Period Manager
* @dev This contract handles all delegation offerings. Delegations are held for
* a specified period (months), and different durations can have different
* returns or `stakeMultiplier`. Currently, only delegation periods can be added.
*/
contract DelegationPeriodManager is Permissions {
mapping (uint => uint) public stakeMultipliers;
bytes32 public constant DELEGATION_PERIOD_SETTER_ROLE = keccak256("DELEGATION_PERIOD_SETTER_ROLE");
/**
* @dev Emitted when a new delegation period is specified.
*/
event DelegationPeriodWasSet(
uint length,
uint stakeMultiplier
);
/**
* @dev Allows the Owner to create a new available delegation period and
* stake multiplier in the network.
*
* Emits a {DelegationPeriodWasSet} event.
*/
function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external {
require(hasRole(DELEGATION_PERIOD_SETTER_ROLE, msg.sender), "DELEGATION_PERIOD_SETTER_ROLE is required");
require(stakeMultipliers[monthsCount] == 0, "Delegation period is already set");
stakeMultipliers[monthsCount] = stakeMultiplier;
emit DelegationPeriodWasSet(monthsCount, stakeMultiplier);
}
/**
* @dev Checks whether given delegation period is allowed.
*/
function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) {
return stakeMultipliers[monthsCount] != 0;
}
/**
* @dev Initial delegation period and multiplier settings.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
stakeMultipliers[2] = 100; // 2 months at 100
// stakeMultipliers[6] = 150; // 6 months at 150
// stakeMultipliers[12] = 200; // 12 months at 200
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Punisher.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../interfaces/delegation/ILocker.sol";
import "./ValidatorService.sol";
import "./DelegationController.sol";
/**
* @title Punisher
* @dev This contract handles all slashing and forgiving operations.
*/
contract Punisher is Permissions, ILocker {
// holder => tokens
mapping (address => uint) private _locked;
bytes32 public constant FORGIVER_ROLE = keccak256("FORGIVER_ROLE");
/**
* @dev Emitted upon slashing condition.
*/
event Slash(
uint validatorId,
uint amount
);
/**
* @dev Emitted upon forgive condition.
*/
event Forgive(
address wallet,
uint amount
);
/**
* @dev Allows SkaleDKG contract to execute slashing on a validator and
* validator's delegations by an `amount` of tokens.
*
* Emits a {Slash} event.
*
* Requirements:
*
* - Validator must exist.
*/
function slash(uint validatorId, uint amount) external allow("SkaleDKG") {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(validatorService.validatorExists(validatorId), "Validator does not exist");
delegationController.confiscate(validatorId, amount);
emit Slash(validatorId, amount);
}
/**
* @dev Allows the Admin to forgive a slashing condition.
*
* Emits a {Forgive} event.
*
* Requirements:
*
* - All slashes must have been processed.
*/
function forgive(address holder, uint amount) external {
require(hasRole(FORGIVER_ROLE, msg.sender), "FORGIVER_ROLE is required");
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated");
if (amount > _locked[holder]) {
delete _locked[holder];
} else {
_locked[holder] = _locked[holder].sub(amount);
}
emit Forgive(holder, amount);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows DelegationController contract to execute slashing of
* delegations.
*/
function handleSlash(address holder, uint amount) external allow("DelegationController") {
_locked[holder] = _locked[holder].add(amount);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
// private
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
delegationController.processAllSlashes(wallet);
return _locked[wallet];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TokenState.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../interfaces/delegation/ILocker.sol";
import "../Permissions.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title Token State
* @dev This contract manages lockers to control token transferability.
*
* The SKALE Network has three types of locked tokens:
*
* - Tokens that are transferrable but are currently locked into delegation with
* a validator.
*
* - Tokens that are not transferable from one address to another, but may be
* delegated to a validator `getAndUpdateLockedAmount`. This lock enforces
* Proof-of-Use requirements.
*
* - Tokens that are neither transferable nor delegatable
* `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing.
*/
contract TokenState is Permissions, ILocker {
string[] private _lockers;
DelegationController private _delegationController;
bytes32 public constant LOCKER_MANAGER_ROLE = keccak256("LOCKER_MANAGER_ROLE");
modifier onlyLockerManager() {
require(hasRole(LOCKER_MANAGER_ROLE, msg.sender), "LOCKER_MANAGER_ROLE is required");
_;
}
/**
* @dev Emitted when a contract is added to the locker.
*/
event LockerWasAdded(
string locker
);
/**
* @dev Emitted when a contract is removed from the locker.
*/
event LockerWasRemoved(
string locker
);
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address holder) external override returns (uint) {
if (address(_delegationController) == address(0)) {
_delegationController =
DelegationController(contractManager.getContract("DelegationController"));
}
uint locked = 0;
if (_delegationController.getDelegationsByHolderLength(holder) > 0) {
// the holder ever delegated
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
locked = locked.add(locker.getAndUpdateLockedAmount(holder));
}
}
return locked;
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) {
uint forbidden = 0;
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder));
}
return forbidden;
}
/**
* @dev Allows the Owner to remove a contract from the locker.
*
* Emits a {LockerWasRemoved} event.
*/
function removeLocker(string calldata locker) external onlyLockerManager {
uint index;
bytes32 hash = keccak256(abi.encodePacked(locker));
for (index = 0; index < _lockers.length; ++index) {
if (keccak256(abi.encodePacked(_lockers[index])) == hash) {
break;
}
}
if (index < _lockers.length) {
if (index < _lockers.length.sub(1)) {
_lockers[index] = _lockers[_lockers.length.sub(1)];
}
delete _lockers[_lockers.length.sub(1)];
_lockers.pop();
emit LockerWasRemoved(locker);
}
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
_setupRole(LOCKER_MANAGER_ROLE, msg.sender);
addLocker("DelegationController");
addLocker("Punisher");
}
/**
* @dev Allows the Owner to add a contract to the Locker.
*
* Emits a {LockerWasAdded} event.
*/
function addLocker(string memory locker) public onlyLockerManager {
_lockers.push(locker);
emit LockerWasAdded(locker);
}
}
pragma solidity ^0.6.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) {
// Solidity only automatically asserts when dividing by 0
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;
}
}
pragma solidity ^0.6.0;
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
uint year;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
uint year;
uint month;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ContractManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "./utils/StringUtils.sol";
/**
* @title ContractManager
* @dev Contract contains the actual current mapping from contract IDs
* (in the form of human-readable strings) to addresses.
*/
contract ContractManager is OwnableUpgradeSafe, IContractManager {
using StringUtils for string;
using Address for address;
string public constant BOUNTY = "Bounty";
string public constant CONSTANTS_HOLDER = "ConstantsHolder";
string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager";
string public constant PUNISHER = "Punisher";
string public constant SKALE_TOKEN = "SkaleToken";
string public constant TIME_HELPERS = "TimeHelpers";
string public constant TOKEN_STATE = "TokenState";
string public constant VALIDATOR_SERVICE = "ValidatorService";
// mapping of actual smart contracts addresses
mapping (bytes32 => address) public contracts;
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external initializer {
OwnableUpgradeSafe.__Ownable_init();
}
/**
* @dev Allows the Owner to add contract to mapping of contract addresses.
*
* Emits a {ContractUpgraded} event.
*
* Requirements:
*
* - New address is non-zero.
* - Contract is not already added.
* - Contract address contains code.
*/
function setContractsAddress(
string calldata contractsName,
address newContractsAddress
)
external
override
onlyOwner
{
// check newContractsAddress is not equal to zero
require(newContractsAddress != address(0), "New address is equal zero");
// create hash of contractsName
bytes32 contractId = keccak256(abi.encodePacked(contractsName));
// check newContractsAddress is not equal the previous contract's address
require(contracts[contractId] != newContractsAddress, "Contract is already added");
require(newContractsAddress.isContract(), "Given contract address does not contain code");
// add newContractsAddress to mapping of actual contract addresses
contracts[contractId] = newContractsAddress;
emit ContractUpgraded(contractsName, newContractsAddress);
}
/**
* @dev Returns contract address.
*
* Requirements:
*
* - Contract must exist.
*/
function getDelegationPeriodManager() external view returns (address) {
return getContract(DELEGATION_PERIOD_MANAGER);
}
function getBounty() external view returns (address) {
return getContract(BOUNTY);
}
function getValidatorService() external view returns (address) {
return getContract(VALIDATOR_SERVICE);
}
function getTimeHelpers() external view returns (address) {
return getContract(TIME_HELPERS);
}
function getConstantsHolder() external view returns (address) {
return getContract(CONSTANTS_HOLDER);
}
function getSkaleToken() external view returns (address) {
return getContract(SKALE_TOKEN);
}
function getTokenState() external view returns (address) {
return getContract(TOKEN_STATE);
}
function getPunisher() external view returns (address) {
return getContract(PUNISHER);
}
function getContract(string memory name) public view override returns (address contractAddress) {
contractAddress = contracts[keccak256(abi.encodePacked(name))];
if (contractAddress == address(0)) {
revert(name.strConcat(" contract has not been found"));
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value 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.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value 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(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value 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(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value 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(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.2;
/**
* @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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @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");
}
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IContractManager.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IContractManager {
function setContractsAddress(string calldata contractsName, address newContractsAddress) external;
function getContract(string calldata name) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
StringUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library StringUtils {
using SafeMath for uint;
function strConcat(string memory a, string memory b) internal pure returns (string memory) {
bytes memory _ba = bytes(a);
bytes memory _bb = bytes(b);
string memory ab = new string(_ba.length.add(_bb.length));
bytes memory strBytes = bytes(ab);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
strBytes[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
strBytes[k++] = _bb[i];
}
return string(strBytes);
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such 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.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SegmentTree.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title Random
* @dev The library for generating of pseudo random numbers
*/
library Random {
using SafeMath for uint;
struct RandomGenerator {
uint seed;
}
/**
* @dev Create an instance of RandomGenerator
*/
function create(uint seed) internal pure returns (RandomGenerator memory) {
return RandomGenerator({seed: seed});
}
function createFromEntropy(bytes memory entropy) internal pure returns (RandomGenerator memory) {
return create(uint(keccak256(entropy)));
}
/**
* @dev Generates random value
*/
function random(RandomGenerator memory self) internal pure returns (uint) {
self.seed = uint(sha256(abi.encodePacked(self.seed)));
return self.seed;
}
/**
* @dev Generates random value in range [0, max)
*/
function random(RandomGenerator memory self, uint max) internal pure returns (uint) {
assert(max > 0);
uint maxRand = uint(-1).sub(uint(-1).mod(max));
if (uint(-1).sub(maxRand) == max.sub(1)) {
return random(self).mod(max);
} else {
uint rand = random(self);
while (rand >= maxRand) {
rand = random(self);
}
return rand.mod(max);
}
}
/**
* @dev Generates random value in range [min, max)
*/
function random(RandomGenerator memory self, uint min, uint max) internal pure returns (uint) {
assert(min < max);
return min.add(random(self, max.sub(min)));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SegmentTree.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./Random.sol";
/**
* @title SegmentTree
* @dev This library implements segment tree data structure
*
* Segment tree allows effectively calculate sum of elements in sub arrays
* by storing some amount of additional data.
*
* IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n.
* Size of initial array always must be power of 2
*
* Example:
*
* Array:
* +---+---+---+---+---+---+---+---+
* | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +---+---+---+---+---+---+---+---+
*
* Segment tree structure:
* +-------------------------------+
* | 36 |
* +---------------+---------------+
* | 10 | 26 |
* +-------+-------+-------+-------+
* | 3 | 7 | 11 | 15 |
* +---+---+---+---+---+---+---+---+
* | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +---+---+---+---+---+---+---+---+
*
* How the segment tree is stored in an array:
* +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+
* | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+
*/
library SegmentTree {
using Random for Random.RandomGenerator;
using SafeMath for uint;
struct Tree {
uint[] tree;
}
/**
* @dev Allocates storage for segment tree of `size` elements
*
* Requirements:
*
* - `size` must be greater than 0
* - `size` must be power of 2
*/
function create(Tree storage segmentTree, uint size) external {
require(size > 0, "Size can't be 0");
require(size & size.sub(1) == 0, "Size is not power of 2");
segmentTree.tree = new uint[](size.mul(2).sub(1));
}
/**
* @dev Adds `delta` to element of segment tree at `place`
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function addToPlace(Tree storage self, uint place, uint delta) external {
require(_correctPlace(self, place), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
self.tree[0] = self.tree[0].add(delta);
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta);
}
}
/**
* @dev Subtracts `delta` from element of segment tree at `place`
*
* Requirements:
*
* - `place` must be in range [1, size]
* - initial value of target element must be not less than `delta`
*/
function removeFromPlace(Tree storage self, uint place, uint delta) external {
require(_correctPlace(self, place), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
self.tree[0] = self.tree[0].sub(delta);
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].sub(delta);
}
}
/**
* @dev Adds `delta` to element of segment tree at `toPlace`
* and subtracts `delta` from element at `fromPlace`
*
* Requirements:
*
* - `fromPlace` must be in range [1, size]
* - `toPlace` must be in range [1, size]
* - initial value of element at `fromPlace` must be not less than `delta`
*/
function moveFromPlaceToPlace(
Tree storage self,
uint fromPlace,
uint toPlace,
uint delta
)
external
{
require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
uint middle = leftBound.add(rightBound).div(2);
uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace;
uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace;
while (toPlaceMove <= middle || middle < fromPlaceMove) {
if (middle < fromPlaceMove) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
middle = leftBound.add(rightBound).div(2);
}
uint leftBoundMove = leftBound;
uint rightBoundMove = rightBound;
uint stepMove = step;
while(leftBoundMove < rightBoundMove && leftBound < rightBound) {
uint middleMove = leftBoundMove.add(rightBoundMove).div(2);
if (fromPlace > middleMove) {
leftBoundMove = middleMove.add(1);
stepMove = stepMove.add(stepMove).add(1);
} else {
rightBoundMove = middleMove;
stepMove = stepMove.add(stepMove);
}
self.tree[stepMove.sub(1)] = self.tree[stepMove.sub(1)].sub(delta);
middle = leftBound.add(rightBound).div(2);
if (toPlace > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta);
}
}
/**
* @dev Returns random position in range [`place`, size]
* with probability proportional to value stored at this position.
* If all element in range are 0 returns 0
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function getRandomNonZeroElementFromPlaceToLast(
Tree storage self,
uint place,
Random.RandomGenerator memory randomGenerator
)
external
view
returns (uint)
{
require(_correctPlace(self, place), "Incorrect place");
uint vertex = 1;
uint leftBound = 0;
uint rightBound = getSize(self);
uint currentFrom = place.sub(1);
uint currentSum = sumFromPlaceToLast(self, place);
if (currentSum == 0) {
return 0;
}
while(leftBound.add(1) < rightBound) {
if (_middle(leftBound, rightBound) <= currentFrom) {
vertex = _right(vertex);
leftBound = _middle(leftBound, rightBound);
} else {
uint rightSum = self.tree[_right(vertex).sub(1)];
uint leftSum = currentSum.sub(rightSum);
if (Random.random(randomGenerator, currentSum) < leftSum) {
// go left
vertex = _left(vertex);
rightBound = _middle(leftBound, rightBound);
currentSum = leftSum;
} else {
// go right
vertex = _right(vertex);
leftBound = _middle(leftBound, rightBound);
currentFrom = leftBound;
currentSum = rightSum;
}
}
}
return leftBound.add(1);
}
/**
* @dev Returns sum of elements in range [`place`, size]
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) {
require(_correctPlace(self, place), "Incorrect place");
if (place == 1) {
return self.tree[0];
}
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
sum = sum.add(self.tree[step]);
}
}
sum = sum.add(self.tree[step.sub(1)]);
}
/**
* @dev Returns amount of elements in segment tree
*/
function getSize(Tree storage segmentTree) internal view returns (uint) {
if (segmentTree.tree.length > 0) {
return segmentTree.tree.length.div(2).add(1);
} else {
return 0;
}
}
/**
* @dev Checks if `place` is valid position in segment tree
*/
function _correctPlace(Tree storage self, uint place) private view returns (bool) {
return place >= 1 && place <= getSize(self);
}
/**
* @dev Calculates index of left child of the vertex
*/
function _left(uint vertex) private pure returns (uint) {
return vertex.mul(2);
}
/**
* @dev Calculates index of right child of the vertex
*/
function _right(uint vertex) private pure returns (uint) {
return vertex.mul(2).add(1);
}
/**
* @dev Calculates arithmetical mean of 2 numbers
*/
function _middle(uint left, uint right) private pure returns (uint) {
return left.add(right).div(2);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ILocker.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface of the Locker functions.
*/
interface ILocker {
/**
* @dev Returns and updates the total amount of locked tokens of a given
* `holder`.
*/
function getAndUpdateLockedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the total non-transferrable and un-delegatable
* amount of a given `holder`.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
NodesMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../BountyV2.sol";
import "../Permissions.sol";
contract NodesMock is Permissions {
uint public nodesCount = 0;
uint public nodesLeft = 0;
// nodeId => timestamp
mapping (uint => uint) public lastRewardDate;
// nodeId => left
mapping (uint => bool) public nodeLeft;
// nodeId => validatorId
mapping (uint => uint) public owner;
function registerNodes(uint amount, uint validatorId) external {
for (uint nodeId = nodesCount; nodeId < nodesCount + amount; ++nodeId) {
lastRewardDate[nodeId] = now;
owner[nodeId] = validatorId;
}
nodesCount += amount;
}
function removeNode(uint nodeId) external {
++nodesLeft;
nodeLeft[nodeId] = true;
}
function changeNodeLastRewardDate(uint nodeId) external {
lastRewardDate[nodeId] = now;
}
function getNodeLastRewardDate(uint nodeIndex) external view returns (uint) {
require(nodeIndex < nodesCount, "Node does not exist");
return lastRewardDate[nodeIndex];
}
function isNodeLeft(uint nodeId) external view returns (bool) {
return nodeLeft[nodeId];
}
function getNumberOnlineNodes() external view returns (uint) {
return nodesCount.sub(nodesLeft);
}
function checkPossibilityToMaintainNode(uint /* validatorId */, uint /* nodeIndex */) external pure returns (bool) {
return true;
}
function getValidatorId(uint nodeId) external view returns (uint) {
return owner[nodeId];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleManagerMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../interfaces/IMintableToken.sol";
import "../Permissions.sol";
contract SkaleManagerMock is Permissions, IERC777Recipient {
IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE");
constructor (address contractManagerAddress) public {
Permissions.initialize(contractManagerAddress);
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
}
function payBounty(uint validatorId, uint amount) external {
IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken"));
require(IMintableToken(address(skaleToken)).mint(address(this), amount, "", ""), "Token was not minted");
require(
IMintableToken(address(skaleToken))
.mint(contractManager.getContract("Distributor"), amount, abi.encode(validatorId), ""),
"Token was not minted"
);
}
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external override allow("SkaleToken")
// solhint-disable-next-line no-empty-blocks
{
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IMintableToken.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
interface IMintableToken {
function mint(
address account,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external
returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleToken.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./thirdparty/openzeppelin/ERC777.sol";
import "./Permissions.sol";
import "./interfaces/delegation/IDelegatableToken.sol";
import "./interfaces/IMintableToken.sol";
import "./delegation/Punisher.sol";
import "./delegation/TokenState.sol";
/**
* @title SkaleToken
* @dev Contract defines the SKALE token and is based on ERC777 token
* implementation.
*/
contract SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken {
using SafeMath for uint;
string public constant NAME = "SKALE";
string public constant SYMBOL = "SKL";
uint public constant DECIMALS = 18;
uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created
constructor(address contractsAddress, address[] memory defOps) public
ERC777("SKALE", "SKL", defOps)
{
Permissions.initialize(contractsAddress);
}
/**
* @dev Allows Owner or SkaleManager to mint an amount of tokens and
* transfer minted tokens to a specified address.
*
* Returns whether the operation is successful.
*
* Requirements:
*
* - Mint must not exceed the total supply.
*/
function mint(
address account,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external
override
allow("SkaleManager")
//onlyAuthorized
returns (bool)
{
require(amount <= CAP.sub(totalSupply()), "Amount is too big");
_mint(
account,
amount,
userData,
operatorData
);
return true;
}
/**
* @dev See {IDelegatableToken-getAndUpdateDelegatedAmount}.
*/
function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) {
return DelegationController(contractManager.getContract("DelegationController"))
.getAndUpdateDelegatedAmount(wallet);
}
/**
* @dev See {IDelegatableToken-getAndUpdateSlashedAmount}.
*/
function getAndUpdateSlashedAmount(address wallet) external override returns (uint) {
return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {IDelegatableToken-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) public override returns (uint) {
return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet);
}
// internal
function _beforeTokenTransfer(
address, // operator
address from,
address, // to
uint256 tokenId)
internal override
{
uint locked = getAndUpdateLockedAmount(from);
if (locked > 0) {
require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring");
}
}
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) internal override nonReentrant {
super._callTokensToSend(operator, from, to, amount, userData, operatorData);
}
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) internal override nonReentrant {
super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
// we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe
function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) {
return Context._msgData();
}
function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) {
return Context._msgSender();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol"; Removed by SKALE
// import "@openzeppelin/contracts/utils/Address.sol"; Removed by SKALE
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
/* Added by SKALE */
import "../../Permissions.sol";
/* End of added by SKALE */
/**
* @dev Implementation of the {IERC777} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract ERC777 is Context, IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory name,
string memory symbol,
address[] memory defaultOperators
) public {
_name = name;
_symbol = symbol;
_defaultOperatorsArray = defaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes memory data) public override {
_send(_msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) public override {
_burn(_msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(
address operator,
address tokenHolder
) public view override returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) public override {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) public override {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view override returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
public override
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view override returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) public override returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal virtual
{
require(account != address(0), "ERC777: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, amount);
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
internal
{
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
internal virtual
{
require(from != address(0), "ERC777: burn from the zero address");
address operator = _msgSender();
/* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_beforeTokenTransfer(operator, from, address(0), amount);
/* End of changed by SKALE */
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_beforeTokenTransfer(operator, from, to, amount);
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function _approve(address holder, address spender, uint256 value) internal {
require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
/* Chaged by SKALE from private */ internal /* End of changed by SKALE */
/* Added by SKALE */ virtual /* End of added by SKALE */
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
/* Chaged by SKALE from private */ internal /* End of changed by SKALE */
/* Added by SKALE */ virtual /* End of added by SKALE */
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - when `from` is zero, `tokenId` will be minted for `to`.
* - when `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address operator, address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IDelegatableToken.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface of the SkaleToken contract.
*/
interface IDelegatableToken {
/**
* @dev Returns and updates the amount of locked tokens of a given account `wallet`.
*/
function getAndUpdateLockedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the amount of delegated tokens of a given account `wallet`.
*/
function getAndUpdateDelegatedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the amount of slashed tokens of a given account `wallet`.
*/
function getAndUpdateSlashedAmount(address wallet) external returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
pragma solidity ^0.6.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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleTokenInternalTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../SkaleToken.sol";
contract SkaleTokenInternalTester is SkaleToken {
constructor(address contractManagerAddress, address[] memory defOps) public
SkaleToken(contractManagerAddress, defOps)
// solhint-disable-next-line no-empty-blocks
{ }
function getMsgData() external view returns (bytes memory) {
return _msgData();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TimeHelpersWithDebug.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "../delegation/TimeHelpers.sol";
contract TimeHelpersWithDebug is TimeHelpers, OwnableUpgradeSafe {
struct TimeShift {
uint pointInTime;
uint shift;
}
TimeShift[] private _timeShift;
function skipTime(uint sec) external onlyOwner {
if (_timeShift.length > 0) {
_timeShift.push(TimeShift({pointInTime: now, shift: _timeShift[_timeShift.length.sub(1)].shift.add(sec)}));
} else {
_timeShift.push(TimeShift({pointInTime: now, shift: sec}));
}
}
function initialize() external initializer {
OwnableUpgradeSafe.__Ownable_init();
}
function timestampToMonth(uint timestamp) public view override returns (uint) {
return super.timestampToMonth(timestamp.add(_getTimeShift(timestamp)));
}
function monthToTimestamp(uint month) public view override returns (uint) {
uint shiftedTimestamp = super.monthToTimestamp(month);
if (_timeShift.length > 0) {
return _findTimeBeforeTimeShift(shiftedTimestamp);
} else {
return shiftedTimestamp;
}
}
// private
function _getTimeShift(uint timestamp) private view returns (uint) {
if (_timeShift.length > 0) {
if (timestamp < _timeShift[0].pointInTime) {
return 0;
} else if (timestamp >= _timeShift[_timeShift.length.sub(1)].pointInTime) {
return _timeShift[_timeShift.length.sub(1)].shift;
} else {
uint left = 0;
uint right = _timeShift.length.sub(1);
while (left + 1 < right) {
uint middle = left.add(right).div(2);
if (timestamp < _timeShift[middle].pointInTime) {
right = middle;
} else {
left = middle;
}
}
return _timeShift[left].shift;
}
} else {
return 0;
}
}
function _findTimeBeforeTimeShift(uint shiftedTimestamp) private view returns (uint) {
uint lastTimeShiftIndex = _timeShift.length.sub(1);
if (_timeShift[lastTimeShiftIndex].pointInTime.add(_timeShift[lastTimeShiftIndex].shift)
< shiftedTimestamp) {
return shiftedTimestamp.sub(_timeShift[lastTimeShiftIndex].shift);
} else {
if (shiftedTimestamp <= _timeShift[0].pointInTime.add(_timeShift[0].shift)) {
if (shiftedTimestamp < _timeShift[0].pointInTime) {
return shiftedTimestamp;
} else {
return _timeShift[0].pointInTime;
}
} else {
uint left = 0;
uint right = lastTimeShiftIndex;
while (left + 1 < right) {
uint middle = left.add(right).div(2);
if (_timeShift[middle].pointInTime.add(_timeShift[middle].shift) < shiftedTimestamp) {
left = middle;
} else {
right = middle;
}
}
if (shiftedTimestamp < _timeShift[right].pointInTime.add(_timeShift[left].shift)) {
return shiftedTimestamp.sub(_timeShift[left].shift);
} else {
return _timeShift[right].pointInTime;
}
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SafeMock.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
contract SafeMock is OwnableUpgradeSafe {
constructor() public {
OwnableUpgradeSafe.__Ownable_init();
multiSend(""); // this is needed to remove slither warning
}
function transferProxyAdminOwnership(OwnableUpgradeSafe proxyAdmin, address newOwner) external onlyOwner {
proxyAdmin.transferOwnership(newOwner);
}
function destroy() external onlyOwner {
selfdestruct(msg.sender);
}
/// @dev Sends multiple transactions and reverts all if one fails.
/// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of
/// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte),
/// to as a address (=> 20 bytes),
/// value as a uint256 (=> 32 bytes),
/// data length as a uint256 (=> 32 bytes),
/// data as bytes.
/// see abi.encodePacked for more information on packed encoding
function multiSend(bytes memory transactions)
public
{
// solhint-disable-next-line no-inline-assembly
assembly {
let length := mload(transactions)
let i := 0x20
// solhint-disable-next-line no-empty-blocks
for { } lt(i, length) { } {
// First byte of the data is the operation.
// We shift by 248 bits (256 - 8 [operation byte]) it right
// since mload will always load 32 bytes (a word).
// This will also zero out unused data.
let operation := shr(0xf8, mload(add(transactions, i)))
// We offset the load address by 1 byte (operation byte)
// We shift it right by 96 bits (256 - 160 [20 address bytes])
// to right-align the data and zero out unused data.
let to := shr(0x60, mload(add(transactions, add(i, 0x01))))
// We offset the load address by 21 byte (operation byte + 20 address bytes)
let value := mload(add(transactions, add(i, 0x15)))
// We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes)
let dataLength := mload(add(transactions, add(i, 0x35)))
// We offset the load address by 85 byte
// (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes)
let data := add(transactions, add(i, 0x55))
let success := 0
switch operation
case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) }
case 1 { success := delegatecall(gas(), to, data, dataLength, 0, 0) }
if eq(success, 0) { revert(0, 0) }
// Next entry starts at 85 byte + data length
i := add(i, add(0x55, dataLength))
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgAlright.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
import "../ContractManager.sol";
import "../Wallets.sol";
import "../KeyStorage.sol";
/**
* @title SkaleDkgAlright
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgAlright {
event AllDataReceived(bytes32 indexed schainHash, uint nodeIndex);
event SuccessfulDKG(bytes32 indexed schainHash);
function alright(
bytes32 schainHash,
uint fromNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => uint) storage lastSuccessfulDKG
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
(uint index, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, fromNodeIndex, true);
uint numberOfParticipant = channels[schainHash].n;
require(numberOfParticipant == dkgProcess[schainHash].numberOfBroadcasted, "Still Broadcasting phase");
require(
complaints[schainHash].fromNodeToComplaint != fromNodeIndex ||
(fromNodeIndex == 0 && complaints[schainHash].startComplaintBlockTimestamp == 0),
"Node has already sent complaint"
);
require(!dkgProcess[schainHash].completed[index], "Node is already alright");
dkgProcess[schainHash].completed[index] = true;
dkgProcess[schainHash].numberOfCompleted++;
emit AllDataReceived(schainHash, fromNodeIndex);
if (dkgProcess[schainHash].numberOfCompleted == numberOfParticipant) {
lastSuccessfulDKG[schainHash] = now;
channels[schainHash].active = false;
KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainHash);
emit SuccessfulDKG(schainHash);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDKG.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./delegation/Punisher.sol";
import "./SlashingTable.sol";
import "./Schains.sol";
import "./SchainsInternal.sol";
import "./utils/FieldOperations.sol";
import "./NodeRotation.sol";
import "./KeyStorage.sol";
import "./interfaces/ISkaleDKG.sol";
import "./thirdparty/ECDH.sol";
import "./utils/Precompiled.sol";
import "./Wallets.sol";
import "./dkg/SkaleDkgAlright.sol";
import "./dkg/SkaleDkgBroadcast.sol";
import "./dkg/SkaleDkgComplaint.sol";
import "./dkg/SkaleDkgPreResponse.sol";
import "./dkg/SkaleDkgResponse.sol";
/**
* @title SkaleDKG
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
contract SkaleDKG is Permissions, ISkaleDKG {
using Fp2Operations for Fp2Operations.Fp2Point;
using G2Operations for G2Operations.G2Point;
enum DkgFunction {Broadcast, Alright, ComplaintBadData, PreResponse, Complaint, Response}
struct Channel {
bool active;
uint n;
uint startedBlockTimestamp;
uint startedBlock;
}
struct ProcessDKG {
uint numberOfBroadcasted;
uint numberOfCompleted;
bool[] broadcasted;
bool[] completed;
}
struct ComplaintData {
uint nodeToComplaint;
uint fromNodeToComplaint;
uint startComplaintBlockTimestamp;
bool isResponse;
bytes32 keyShare;
G2Operations.G2Point sumOfVerVec;
}
struct KeyShare {
bytes32[2] publicKey;
bytes32 share;
}
struct Context {
bool isDebt;
uint delta;
DkgFunction dkgFunction;
}
uint public constant COMPLAINT_TIMELIMIT = 1800;
mapping(bytes32 => Channel) public channels;
mapping(bytes32 => uint) public lastSuccessfulDKG;
mapping(bytes32 => ProcessDKG) public dkgProcess;
mapping(bytes32 => ComplaintData) public complaints;
mapping(bytes32 => uint) public startAlrightTimestamp;
mapping(bytes32 => mapping(uint => bytes32)) public hashedData;
mapping(bytes32 => uint) private _badNodes;
/**
* @dev Emitted when a channel is opened.
*/
event ChannelOpened(bytes32 schainHash);
/**
* @dev Emitted when a channel is closed.
*/
event ChannelClosed(bytes32 schainHash);
/**
* @dev Emitted when a node broadcasts keyshare.
*/
event BroadcastAndKeyShare(
bytes32 indexed schainHash,
uint indexed fromNode,
G2Operations.G2Point[] verificationVector,
KeyShare[] secretKeyContribution
);
/**
* @dev Emitted when all group data is received by node.
*/
event AllDataReceived(bytes32 indexed schainHash, uint nodeIndex);
/**
* @dev Emitted when DKG is successful.
*/
event SuccessfulDKG(bytes32 indexed schainHash);
/**
* @dev Emitted when a complaint against a node is verified.
*/
event BadGuy(uint nodeIndex);
/**
* @dev Emitted when DKG failed.
*/
event FailedDKG(bytes32 indexed schainHash);
/**
* @dev Emitted when a new node is rotated in.
*/
event NewGuy(uint nodeIndex);
/**
* @dev Emitted when an incorrect complaint is sent.
*/
event ComplaintError(string error);
/**
* @dev Emitted when a complaint is sent.
*/
event ComplaintSent(
bytes32 indexed schainHash, uint indexed fromNodeIndex, uint indexed toNodeIndex);
modifier correctGroup(bytes32 schainHash) {
require(channels[schainHash].active, "Group is not created");
_;
}
modifier correctGroupWithoutRevert(bytes32 schainHash) {
if (!channels[schainHash].active) {
emit ComplaintError("Group is not created");
} else {
_;
}
}
modifier correctNode(bytes32 schainHash, uint nodeIndex) {
(uint index, ) = checkAndReturnIndexInGroup(schainHash, nodeIndex, true);
_;
}
modifier correctNodeWithoutRevert(bytes32 schainHash, uint nodeIndex) {
(, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
if (!check) {
emit ComplaintError("Node is not in this group");
} else {
_;
}
}
modifier onlyNodeOwner(uint nodeIndex) {
_checkMsgSenderIsNodeOwner(nodeIndex);
_;
}
modifier refundGasBySchain(bytes32 schainHash, Context memory context) {
uint gasTotal = gasleft();
_;
_refundGasBySchain(schainHash, gasTotal, context);
}
modifier refundGasByValidatorToSchain(bytes32 schainHash, Context memory context) {
uint gasTotal = gasleft();
_;
_refundGasBySchain(schainHash, gasTotal, context);
_refundGasByValidatorToSchain(schainHash);
}
function alright(bytes32 schainHash, uint fromNodeIndex)
external
refundGasBySchain(schainHash,
Context({
isDebt: false,
delta: ConstantsHolder(contractManager.getConstantsHolder()).ALRIGHT_DELTA(),
dkgFunction: DkgFunction.Alright
}))
correctGroup(schainHash)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgAlright.alright(
schainHash,
fromNodeIndex,
contractManager,
channels,
dkgProcess,
complaints,
lastSuccessfulDKG
);
}
function broadcast(
bytes32 schainHash,
uint nodeIndex,
G2Operations.G2Point[] memory verificationVector,
KeyShare[] memory secretKeyContribution
)
external
refundGasBySchain(schainHash,
Context({
isDebt: false,
delta: ConstantsHolder(contractManager.getConstantsHolder()).BROADCAST_DELTA(),
dkgFunction: DkgFunction.Broadcast
}))
correctGroup(schainHash)
onlyNodeOwner(nodeIndex)
{
SkaleDkgBroadcast.broadcast(
schainHash,
nodeIndex,
verificationVector,
secretKeyContribution,
contractManager,
channels,
dkgProcess,
hashedData
);
}
function complaintBadData(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex)
external
refundGasBySchain(
schainHash,
Context({
isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_BAD_DATA_DELTA(),
dkgFunction: DkgFunction.ComplaintBadData
}))
correctGroupWithoutRevert(schainHash)
correctNode(schainHash, fromNodeIndex)
correctNodeWithoutRevert(schainHash, toNodeIndex)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgComplaint.complaintBadData(
schainHash,
fromNodeIndex,
toNodeIndex,
contractManager,
complaints
);
}
function preResponse(
bytes32 schainId,
uint fromNodeIndex,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult,
KeyShare[] memory secretKeyContribution
)
external
refundGasBySchain(
schainId,
Context({
isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).PRE_RESPONSE_DELTA(),
dkgFunction: DkgFunction.PreResponse
}))
correctGroup(schainId)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgPreResponse.preResponse(
schainId,
fromNodeIndex,
verificationVector,
verificationVectorMult,
secretKeyContribution,
contractManager,
complaints,
hashedData
);
}
function complaint(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex)
external
refundGasByValidatorToSchain(
schainHash,
Context({
isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_DELTA(),
dkgFunction: DkgFunction.Complaint
}))
correctGroupWithoutRevert(schainHash)
correctNode(schainHash, fromNodeIndex)
correctNodeWithoutRevert(schainHash, toNodeIndex)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgComplaint.complaint(
schainHash,
fromNodeIndex,
toNodeIndex,
contractManager,
channels,
complaints,
startAlrightTimestamp
);
}
function response(
bytes32 schainHash,
uint fromNodeIndex,
uint secretNumber,
G2Operations.G2Point memory multipliedShare
)
external
refundGasByValidatorToSchain(
schainHash,
Context({isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).RESPONSE_DELTA(),
dkgFunction: DkgFunction.Response
}))
correctGroup(schainHash)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgResponse.response(
schainHash,
fromNodeIndex,
secretNumber,
multipliedShare,
contractManager,
channels,
complaints
);
}
/**
* @dev Allows Schains and NodeRotation contracts to open a channel.
*
* Emits a {ChannelOpened} event.
*
* Requirements:
*
* - Channel is not already created.
*/
function openChannel(bytes32 schainHash) external override allowTwo("Schains","NodeRotation") {
_openChannel(schainHash);
}
/**
* @dev Allows SchainsInternal contract to delete a channel.
*
* Requirements:
*
* - Channel must exist.
*/
function deleteChannel(bytes32 schainHash) external override allow("SchainsInternal") {
delete channels[schainHash];
delete dkgProcess[schainHash];
delete complaints[schainHash];
KeyStorage(contractManager.getContract("KeyStorage")).deleteKey(schainHash);
}
function setStartAlrightTimestamp(bytes32 schainHash) external allow("SkaleDKG") {
startAlrightTimestamp[schainHash] = now;
}
function setBadNode(bytes32 schainHash, uint nodeIndex) external allow("SkaleDKG") {
_badNodes[schainHash] = nodeIndex;
}
function finalizeSlashing(bytes32 schainHash, uint badNode) external allow("SkaleDKG") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal")
);
emit BadGuy(badNode);
emit FailedDKG(schainHash);
schainsInternal.makeSchainNodesInvisible(schainHash);
if (schainsInternal.isAnyFreeNode(schainHash)) {
uint newNode = nodeRotation.rotateNode(
badNode,
schainHash,
false,
true
);
emit NewGuy(newNode);
} else {
_openChannel(schainHash);
schainsInternal.removeNodeFromSchain(
badNode,
schainHash
);
channels[schainHash].active = false;
}
schainsInternal.makeSchainNodesVisible(schainHash);
Punisher(contractManager.getPunisher()).slash(
Nodes(contractManager.getContract("Nodes")).getValidatorId(badNode),
SlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG")
);
}
function getChannelStartedTime(bytes32 schainHash) external view returns (uint) {
return channels[schainHash].startedBlockTimestamp;
}
function getChannelStartedBlock(bytes32 schainHash) external view returns (uint) {
return channels[schainHash].startedBlock;
}
function getNumberOfBroadcasted(bytes32 schainHash) external view returns (uint) {
return dkgProcess[schainHash].numberOfBroadcasted;
}
function getNumberOfCompleted(bytes32 schainHash) external view returns (uint) {
return dkgProcess[schainHash].numberOfCompleted;
}
function getTimeOfLastSuccessfulDKG(bytes32 schainHash) external view returns (uint) {
return lastSuccessfulDKG[schainHash];
}
function getComplaintData(bytes32 schainHash) external view returns (uint, uint) {
return (complaints[schainHash].fromNodeToComplaint, complaints[schainHash].nodeToComplaint);
}
function getComplaintStartedTime(bytes32 schainHash) external view returns (uint) {
return complaints[schainHash].startComplaintBlockTimestamp;
}
function getAlrightStartedTime(bytes32 schainHash) external view returns (uint) {
return startAlrightTimestamp[schainHash];
}
/**
* @dev Checks whether channel is opened.
*/
function isChannelOpened(bytes32 schainHash) external override view returns (bool) {
return channels[schainHash].active;
}
function isLastDKGSuccessful(bytes32 schainHash) external override view returns (bool) {
return channels[schainHash].startedBlockTimestamp <= lastSuccessfulDKG[schainHash];
}
/**
* @dev Checks whether broadcast is possible.
*/
function isBroadcastPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return channels[schainHash].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
!dkgProcess[schainHash].broadcasted[index];
}
/**
* @dev Checks whether complaint is possible.
*/
function isComplaintPossible(
bytes32 schainHash,
uint fromNodeIndex,
uint toNodeIndex
)
external
view
returns (bool)
{
(uint indexFrom, bool checkFrom) = checkAndReturnIndexInGroup(schainHash, fromNodeIndex, false);
(uint indexTo, bool checkTo) = checkAndReturnIndexInGroup(schainHash, toNodeIndex, false);
if (!checkFrom || !checkTo)
return false;
bool complaintSending = (
complaints[schainHash].nodeToComplaint == uint(-1) &&
dkgProcess[schainHash].broadcasted[indexTo] &&
!dkgProcess[schainHash].completed[indexFrom]
) ||
(
dkgProcess[schainHash].broadcasted[indexTo] &&
complaints[schainHash].startComplaintBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp &&
complaints[schainHash].nodeToComplaint == toNodeIndex
) ||
(
!dkgProcess[schainHash].broadcasted[indexTo] &&
complaints[schainHash].nodeToComplaint == uint(-1) &&
channels[schainHash].startedBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp
) ||
(
complaints[schainHash].nodeToComplaint == uint(-1) &&
isEveryoneBroadcasted(schainHash) &&
dkgProcess[schainHash].completed[indexFrom] &&
!dkgProcess[schainHash].completed[indexTo] &&
startAlrightTimestamp[schainHash].add(_getComplaintTimelimit()) <= block.timestamp
);
return channels[schainHash].active &&
dkgProcess[schainHash].broadcasted[indexFrom] &&
_isNodeOwnedByMessageSender(fromNodeIndex, msg.sender) &&
complaintSending;
}
/**
* @dev Checks whether sending Alright response is possible.
*/
function isAlrightPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return channels[schainHash].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
channels[schainHash].n == dkgProcess[schainHash].numberOfBroadcasted &&
(complaints[schainHash].fromNodeToComplaint != nodeIndex ||
(nodeIndex == 0 && complaints[schainHash].startComplaintBlockTimestamp == 0)) &&
!dkgProcess[schainHash].completed[index];
}
/**
* @dev Checks whether sending a pre-response is possible.
*/
function isPreResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return channels[schainHash].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
complaints[schainHash].nodeToComplaint == nodeIndex &&
!complaints[schainHash].isResponse;
}
/**
* @dev Checks whether sending a response is possible.
*/
function isResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return channels[schainHash].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
complaints[schainHash].nodeToComplaint == nodeIndex &&
complaints[schainHash].isResponse;
}
function isNodeBroadcasted(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return check && dkgProcess[schainHash].broadcasted[index];
}
/**
* @dev Checks whether all data has been received by node.
*/
function isAllDataReceived(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return check && dkgProcess[schainHash].completed[index];
}
function hashData(
KeyShare[] memory secretKeyContribution,
G2Operations.G2Point[] memory verificationVector
)
external
pure
returns (bytes32)
{
bytes memory data;
for (uint i = 0; i < secretKeyContribution.length; i++) {
data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share);
}
for (uint i = 0; i < verificationVector.length; i++) {
data = abi.encodePacked(
data,
verificationVector[i].x.a,
verificationVector[i].x.b,
verificationVector[i].y.a,
verificationVector[i].y.b
);
}
return keccak256(data);
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
function checkAndReturnIndexInGroup(
bytes32 schainHash,
uint nodeIndex,
bool revertCheck
)
public
view
returns (uint, bool)
{
uint index = SchainsInternal(contractManager.getContract("SchainsInternal"))
.getNodeIndexInGroup(schainHash, nodeIndex);
if (index >= channels[schainHash].n && revertCheck) {
revert("Node is not in this group");
}
return (index, index < channels[schainHash].n);
}
function _refundGasBySchain(bytes32 schainHash, uint gasTotal, Context memory context) private {
Wallets wallets = Wallets(payable(contractManager.getContract("Wallets")));
bool isLastNode = channels[schainHash].n == dkgProcess[schainHash].numberOfCompleted;
if (context.dkgFunction == DkgFunction.Alright && isLastNode) {
wallets.refundGasBySchain(
schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(74800), context.isDebt
);
} else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 14e5) {
wallets.refundGasBySchain(
schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(590000), context.isDebt
);
} else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 7e5) {
wallets.refundGasBySchain(
schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(250000), context.isDebt
);
} else if (context.dkgFunction == DkgFunction.Response){
wallets.refundGasBySchain(
schainHash, msg.sender, gasTotal.sub(gasleft()).sub(context.delta), context.isDebt
);
} else {
wallets.refundGasBySchain(
schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta), context.isDebt
);
}
}
function _refundGasByValidatorToSchain(bytes32 schainHash) private {
uint validatorId = Nodes(contractManager.getContract("Nodes"))
.getValidatorId(_badNodes[schainHash]);
Wallets(payable(contractManager.getContract("Wallets")))
.refundGasByValidatorToSchain(validatorId, schainHash);
delete _badNodes[schainHash];
}
function _openChannel(bytes32 schainHash) private {
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal")
);
uint len = schainsInternal.getNumberOfNodesInGroup(schainHash);
channels[schainHash].active = true;
channels[schainHash].n = len;
delete dkgProcess[schainHash].completed;
delete dkgProcess[schainHash].broadcasted;
dkgProcess[schainHash].broadcasted = new bool[](len);
dkgProcess[schainHash].completed = new bool[](len);
complaints[schainHash].fromNodeToComplaint = uint(-1);
complaints[schainHash].nodeToComplaint = uint(-1);
delete complaints[schainHash].startComplaintBlockTimestamp;
delete dkgProcess[schainHash].numberOfBroadcasted;
delete dkgProcess[schainHash].numberOfCompleted;
channels[schainHash].startedBlockTimestamp = now;
channels[schainHash].startedBlock = block.number;
KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(schainHash);
emit ChannelOpened(schainHash);
}
function isEveryoneBroadcasted(bytes32 schainHash) public view returns (bool) {
return channels[schainHash].n == dkgProcess[schainHash].numberOfBroadcasted;
}
function _isNodeOwnedByMessageSender(uint nodeIndex, address from) private view returns (bool) {
return Nodes(contractManager.getContract("Nodes")).isNodeExist(from, nodeIndex);
}
function _checkMsgSenderIsNodeOwner(uint nodeIndex) private view {
require(_isNodeOwnedByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender");
}
function _getComplaintTimelimit() private view returns (uint) {
return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Wallets.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@skalenetwork/skale-manager-interfaces/IWallets.sol";
import "./Permissions.sol";
import "./delegation/ValidatorService.sol";
import "./SchainsInternal.sol";
import "./Nodes.sol";
/**
* @title Wallets
* @dev Contract contains logic to perform automatic self-recharging ether for nodes
*/
contract Wallets is Permissions, IWallets {
mapping (uint => uint) private _validatorWallets;
mapping (bytes32 => uint) private _schainWallets;
mapping (bytes32 => uint) private _schainDebts;
/**
* @dev Emitted when the validator wallet was funded
*/
event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId);
/**
* @dev Emitted when the schain wallet was funded
*/
event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash);
/**
* @dev Emitted when the node received a refund from validator to its wallet
*/
event NodeRefundedByValidator(address node, uint validatorId, uint amount);
/**
* @dev Emitted when the node received a refund from schain to its wallet
*/
event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount);
/**
* @dev Is executed on a call to the contract with empty calldata.
* This is the function that is executed on plain Ether transfers,
* so validator or schain owner can use usual transfer ether to recharge wallet.
*/
receive() external payable {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32[] memory schainHashs = schainsInternal.getSchainHashsByAddress(msg.sender);
if (schainHashs.length == 1) {
rechargeSchainWallet(schainHashs[0]);
} else {
uint validatorId = validatorService.getValidatorId(msg.sender);
rechargeValidatorWallet(validatorId);
}
}
/**
* @dev Reimburse gas for node by validator wallet. If validator wallet has not enough funds
* the node will receive the entire remaining amount in the validator's wallet.
* `validatorId` - validator that will reimburse desired transaction
* `spender` - address to send reimbursed funds
* `spentGas` - amount of spent gas that should be reimbursed to desired node
*
* Emits a {NodeRefundedByValidator} event.
*
* Requirements:
* - Given validator should exist
*/
function refundGasByValidator(
uint validatorId,
address payable spender,
uint spentGas
)
external
allowTwo("SkaleManager", "SkaleDKG")
{
require(validatorId != 0, "ValidatorId could not be zero");
uint amount = tx.gasprice * spentGas;
if (amount <= _validatorWallets[validatorId]) {
_validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount);
emit NodeRefundedByValidator(spender, validatorId, amount);
spender.transfer(amount);
} else {
uint wholeAmount = _validatorWallets[validatorId];
// solhint-disable-next-line reentrancy
delete _validatorWallets[validatorId];
emit NodeRefundedByValidator(spender, validatorId, wholeAmount);
spender.transfer(wholeAmount);
}
}
/**
* @dev Returns the amount owed to the owner of the chain by the validator,
* if the validator does not have enough funds, then everything
* that the validator has will be returned to the owner of the chain.
*/
function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external allow("SkaleDKG") {
uint debtAmount = _schainDebts[schainHash];
uint validatorWallet = _validatorWallets[validatorId];
if (debtAmount <= validatorWallet) {
_validatorWallets[validatorId] = validatorWallet.sub(debtAmount);
} else {
debtAmount = validatorWallet;
delete _validatorWallets[validatorId];
}
_schainWallets[schainHash] = _schainWallets[schainHash].add(debtAmount);
delete _schainDebts[schainHash];
}
/**
* @dev Reimburse gas for node by schain wallet. If schain wallet has not enough funds
* than transaction will be reverted.
* `schainHash` - schain that will reimburse desired transaction
* `spender` - address to send reimbursed funds
* `spentGas` - amount of spent gas that should be reimbursed to desired node
* `isDebt` - parameter that indicates whether this amount should be recorded as debt for the validator
*
* Emits a {NodeRefundedBySchain} event.
*
* Requirements:
* - Given schain should exist
* - Schain wallet should have enough funds
*/
function refundGasBySchain(
bytes32 schainHash,
address payable spender,
uint spentGas,
bool isDebt
)
external
override
allowTwo("SkaleDKG", "MessageProxyForMainnet")
{
uint amount = tx.gasprice * spentGas;
if (isDebt) {
amount += (_schainDebts[schainHash] == 0 ? 21000 : 6000) * tx.gasprice;
_schainDebts[schainHash] = _schainDebts[schainHash].add(amount);
}
require(schainHash != bytes32(0), "SchainHash cannot be null");
require(amount <= _schainWallets[schainHash], "Schain wallet has not enough funds");
_schainWallets[schainHash] = _schainWallets[schainHash].sub(amount);
emit NodeRefundedBySchain(spender, schainHash, amount);
spender.transfer(amount);
}
/**
* @dev Withdraws money from schain wallet. Possible to execute only after deleting schain.
* `schainOwner` - address of schain owner that will receive rest of the schain balance
* `schainHash` - schain wallet from which money is withdrawn
*
* Requirements:
* - Executable only after initing delete schain
*/
function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external allow("Schains") {
uint amount = _schainWallets[schainHash];
delete _schainWallets[schainHash];
schainOwner.transfer(amount);
}
/**
* @dev Withdraws money from vaildator wallet.
* `amount` - the amount of money in wei
*
* Requirements:
* - Validator must have sufficient withdrawal amount
*/
function withdrawFundsFromValidatorWallet(uint amount) external {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
uint validatorId = validatorService.getValidatorId(msg.sender);
require(amount <= _validatorWallets[validatorId], "Balance is too low");
_validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount);
msg.sender.transfer(amount);
}
function getSchainBalance(bytes32 schainHash) external view returns (uint) {
return _schainWallets[schainHash];
}
function getValidatorBalance(uint validatorId) external view returns (uint) {
return _validatorWallets[validatorId];
}
/**
* @dev Recharge the validator wallet by id.
* `validatorId` - id of existing validator.
*
* Emits a {ValidatorWalletRecharged} event.
*
* Requirements:
* - Given validator must exist
*/
function rechargeValidatorWallet(uint validatorId) public payable {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator does not exists");
_validatorWallets[validatorId] = _validatorWallets[validatorId].add(msg.value);
emit ValidatorWalletRecharged(msg.sender, msg.value, validatorId);
}
/**
* @dev Recharge the schain wallet by schainHash (hash of schain name).
* `schainHash` - id of existing schain.
*
* Emits a {SchainWalletRecharged} event.
*
* Requirements:
* - Given schain must be created
*/
function rechargeSchainWallet(bytes32 schainHash) public payable override {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainActive(schainHash), "Schain should be active for recharging");
_schainWallets[schainHash] = _schainWallets[schainHash].add(msg.value);
emit SchainWalletRecharged(msg.sender, msg.value, schainHash);
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
KeyStorage.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Decryption.sol";
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./thirdparty/ECDH.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
contract KeyStorage is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
using G2Operations for G2Operations.G2Point;
struct BroadcastedData {
KeyShare[] secretKeyContribution;
G2Operations.G2Point[] verificationVector;
}
struct KeyShare {
bytes32[2] publicKey;
bytes32 share;
}
// Unused variable!!
mapping(bytes32 => mapping(uint => BroadcastedData)) private _data;
//
mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress;
mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys;
// Unused variable
mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys;
//
mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys;
function deleteKey(bytes32 schainHash) external allow("SkaleDKG") {
_previousSchainsPublicKeys[schainHash].push(_schainsPublicKeys[schainHash]);
delete _schainsPublicKeys[schainHash];
delete _data[schainHash][0];
delete _schainsNodesPublicKeys[schainHash];
}
function initPublicKeyInProgress(bytes32 schainHash) external allow("SkaleDKG") {
_publicKeysInProgress[schainHash] = G2Operations.getG2Zero();
}
function adding(bytes32 schainHash, G2Operations.G2Point memory value) external allow("SkaleDKG") {
require(value.isG2(), "Incorrect g2 point");
_publicKeysInProgress[schainHash] = value.addG2(_publicKeysInProgress[schainHash]);
}
function finalizePublicKey(bytes32 schainHash) external allow("SkaleDKG") {
if (!_isSchainsPublicKeyZero(schainHash)) {
_previousSchainsPublicKeys[schainHash].push(_schainsPublicKeys[schainHash]);
}
_schainsPublicKeys[schainHash] = _publicKeysInProgress[schainHash];
delete _publicKeysInProgress[schainHash];
}
function getCommonPublicKey(bytes32 schainHash) external view returns (G2Operations.G2Point memory) {
return _schainsPublicKeys[schainHash];
}
function getPreviousPublicKey(bytes32 schainHash) external view returns (G2Operations.G2Point memory) {
uint length = _previousSchainsPublicKeys[schainHash].length;
if (length == 0) {
return G2Operations.getG2Zero();
}
return _previousSchainsPublicKeys[schainHash][length - 1];
}
function getAllPreviousPublicKeys(bytes32 schainHash) external view returns (G2Operations.G2Point[] memory) {
return _previousSchainsPublicKeys[schainHash];
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
function _isSchainsPublicKeyZero(bytes32 schainHash) private view returns (bool) {
return _schainsPublicKeys[schainHash].x.a == 0 &&
_schainsPublicKeys[schainHash].x.b == 0 &&
_schainsPublicKeys[schainHash].y.a == 0 &&
_schainsPublicKeys[schainHash].y.b == 0;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SlashingTable.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
import "./ConstantsHolder.sol";
/**
* @title Slashing Table
* @dev This contract manages slashing conditions and penalties.
*/
contract SlashingTable is Permissions {
mapping (uint => uint) private _penalties;
bytes32 public constant PENALTY_SETTER_ROLE = keccak256("PENALTY_SETTER_ROLE");
/**
* @dev Allows the Owner to set a slashing penalty in SKL tokens for a
* given offense.
*/
function setPenalty(string calldata offense, uint penalty) external {
require(hasRole(PENALTY_SETTER_ROLE, msg.sender), "PENALTY_SETTER_ROLE is required");
_penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty;
}
/**
* @dev Returns the penalty in SKL tokens for a given offense.
*/
function getPenalty(string calldata offense) external view returns (uint) {
uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))];
return penalty;
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Schains.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@skalenetwork/skale-manager-interfaces/ISchains.sol";
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./ConstantsHolder.sol";
import "./KeyStorage.sol";
import "./SkaleVerifier.sol";
import "./utils/FieldOperations.sol";
import "./NodeRotation.sol";
import "./interfaces/ISkaleDKG.sol";
import "./Wallets.sol";
/**
* @title Schains
* @dev Contains functions to manage Schains such as Schain creation,
* deletion, and rotation.
*/
contract Schains is Permissions, ISchains {
struct SchainParameters {
uint lifetime;
uint8 typeOfSchain;
uint16 nonce;
string name;
}
bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE");
/**
* @dev Emitted when an schain is created.
*/
event SchainCreated(
string name,
address owner,
uint partOfNode,
uint lifetime,
uint numberOfNodes,
uint deposit,
uint16 nonce,
bytes32 schainHash,
uint time,
uint gasSpend
);
/**
* @dev Emitted when an schain is deleted.
*/
event SchainDeleted(
address owner,
string name,
bytes32 indexed schainHash
);
/**
* @dev Emitted when a node in an schain is rotated.
*/
event NodeRotated(
bytes32 schainHash,
uint oldNode,
uint newNode
);
/**
* @dev Emitted when a node is added to an schain.
*/
event NodeAdded(
bytes32 schainHash,
uint newNode
);
/**
* @dev Emitted when a group of nodes is created for an schain.
*/
event SchainNodes(
string name,
bytes32 schainHash,
uint[] nodesInGroup,
uint time,
uint gasSpend
);
/**
* @dev Allows SkaleManager contract to create an Schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type is valid.
* - There is sufficient deposit to create type of schain.
*/
function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") {
SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data);
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder());
uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp();
uint minSchainLifetime = constantsHolder.minimalSchainLifetime();
require(now >= schainCreationTimeStamp, "It is not a time for creating Schain");
require(
schainParameters.lifetime >= minSchainLifetime,
"Minimal schain lifetime should be satisfied"
);
require(
getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit,
"Not enough money to create Schain");
_addSchain(from, deposit, schainParameters);
}
/**
* @dev Allows the foundation to create an Schain without tokens.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - sender is granted with SCHAIN_CREATOR_ROLE
* - Schain type is valid.
*/
function addSchainByFoundation(
uint lifetime,
uint8 typeOfSchain,
uint16 nonce,
string calldata name,
address schainOwner
)
external
payable
{
require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain");
SchainParameters memory schainParameters = SchainParameters({
lifetime: lifetime,
typeOfSchain: typeOfSchain,
nonce: nonce,
name: name
});
address _schainOwner;
if (schainOwner != address(0)) {
_schainOwner = schainOwner;
} else {
_schainOwner = msg.sender;
}
_addSchain(_schainOwner, 0, schainParameters);
bytes32 schainHash = keccak256(abi.encodePacked(name));
Wallets(payable(contractManager.getContract("Wallets"))).rechargeSchainWallet{value: msg.value}(schainHash);
}
/**
* @dev Allows SkaleManager to remove an schain from the network.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Executed by schain owner.
*/
function deleteSchain(address from, string calldata name) external allow("SkaleManager") {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainHash = keccak256(abi.encodePacked(name));
require(
schainsInternal.isOwnerAddress(from, schainHash),
"Message sender is not the owner of the Schain"
);
_deleteSchain(name, schainsInternal);
}
/**
* @dev Allows SkaleManager to delete any Schain.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Schain exists.
*/
function deleteSchainByRoot(string calldata name) external allow("SkaleManager") {
_deleteSchain(name, SchainsInternal(contractManager.getContract("SchainsInternal")));
}
/**
* @dev Allows SkaleManager contract to restart schain creation by forming a
* new schain group. Executed when DKG procedure fails and becomes stuck.
*
* Emits a {NodeAdded} event.
*
* Requirements:
*
* - Previous DKG procedure must have failed.
* - DKG failure got stuck because there were no free nodes to rotate in.
* - A free node must be released in the network.
*/
function restartSchainCreation(string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainHash = keccak256(abi.encodePacked(name));
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
require(!skaleDKG.isLastDKGSuccessful(schainHash), "DKG success");
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal"));
require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes for new group formation");
uint newNodeIndex = nodeRotation.selectNodeToGroup(schainHash);
skaleDKG.openChannel(schainHash);
emit NodeAdded(schainHash, newNodeIndex);
}
/**
* @dev addSpace - return occupied space to Node
* nodeIndex - index of Node at common array of Nodes
* partOfNode - divisor of given type of Schain
*/
function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
nodes.addSpaceToNode(nodeIndex, partOfNode);
}
/**
* @dev Checks whether schain group signature is valid.
*/
function verifySchainSignature(
uint signatureA,
uint signatureB,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
string calldata schainName
)
external
view
override
returns (bool)
{
SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier"));
G2Operations.G2Point memory publicKey = KeyStorage(
contractManager.getContract("KeyStorage")
).getCommonPublicKey(
keccak256(abi.encodePacked(schainName))
);
return skaleVerifier.verify(
Fp2Operations.Fp2Point({
a: signatureA,
b: signatureB
}),
hash, counter,
hashA, hashB,
publicKey
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Returns the current price in SKL tokens for given Schain type and lifetime.
*/
function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder());
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
uint nodeDeposit = constantsHolder.NODE_DEPOSIT();
uint numberOfNodes;
uint8 divisor;
(divisor, numberOfNodes) = schainsInternal.getSchainType(typeOfSchain);
if (divisor == 0) {
return 1e18;
} else {
uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2)));
uint down = uint(
uint(constantsHolder.SMALL_DIVISOR())
.mul(uint(constantsHolder.SECONDS_TO_YEAR()))
.div(divisor)
);
return up.div(down);
}
}
/**
* @dev Initializes an schain in the SchainsInternal contract.
*
* Requirements:
*
* - Schain name is not already in use.
*/
function _initializeSchainInSchainsInternal(
string memory name,
address from,
uint deposit,
uint lifetime,
SchainsInternal schainsInternal
)
private
{
require(schainsInternal.isSchainNameAvailable(name), "Schain name is not available");
// initialize Schain
schainsInternal.initializeSchain(name, from, lifetime, deposit);
schainsInternal.setSchainIndex(keccak256(abi.encodePacked(name)), from);
}
/**
* @dev Converts data from bytes to normal schain parameters of lifetime,
* type, nonce, and name.
*/
function _fallbackSchainParametersDataConverter(bytes memory data)
private
pure
returns (SchainParameters memory schainParameters)
{
(schainParameters.lifetime,
schainParameters.typeOfSchain,
schainParameters.nonce,
schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string));
}
/**
* @dev Allows creation of node group for Schain.
*
* Emits an {SchainNodes} event.
*/
function _createGroupForSchain(
string memory schainName,
bytes32 schainHash,
uint numberOfNodes,
uint8 partOfNode,
SchainsInternal schainsInternal
)
private
{
uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainHash, numberOfNodes, partOfNode);
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainHash);
emit SchainNodes(
schainName,
schainHash,
nodesInGroup,
block.timestamp,
gasleft());
}
/**
* @dev Creates an schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type must be valid.
*/
function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
//initialize Schain
_initializeSchainInSchainsInternal(
schainParameters.name,
from,
deposit,
schainParameters.lifetime,
schainsInternal
);
// create a group for Schain
uint numberOfNodes;
uint8 partOfNode;
(partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain);
_createGroupForSchain(
schainParameters.name,
keccak256(abi.encodePacked(schainParameters.name)),
numberOfNodes,
partOfNode,
schainsInternal
);
emit SchainCreated(
schainParameters.name,
from,
partOfNode,
schainParameters.lifetime,
numberOfNodes,
deposit,
schainParameters.nonce,
keccak256(abi.encodePacked(schainParameters.name)),
block.timestamp,
gasleft());
}
function _deleteSchain(string calldata name, SchainsInternal schainsInternal) private {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainHash = keccak256(abi.encodePacked(name));
require(schainsInternal.isSchainExist(schainHash), "Schain does not exist");
uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainHash);
uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainHash);
for (uint i = 0; i < nodesInGroup.length; i++) {
uint schainIndex = schainsInternal.findSchainAtSchainsForNode(
nodesInGroup[i],
schainHash
);
if (schainsInternal.checkHoleForSchain(schainHash, i)) {
continue;
}
require(
schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]),
"Some Node does not contain given Schain");
schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainHash);
schainsInternal.removeNodeFromExceptions(schainHash, nodesInGroup[i]);
this.addSpace(nodesInGroup[i], partOfNode);
}
schainsInternal.deleteGroup(schainHash);
address from = schainsInternal.getSchainOwner(schainHash);
schainsInternal.removeSchain(schainHash, from);
schainsInternal.removeHolesForSchain(schainHash);
nodeRotation.removeRotation(schainHash);
Wallets(
payable(contractManager.getContract("Wallets"))
).withdrawFundsFromSchainWallet(payable(from), schainHash);
emit SchainDeleted(from, name, schainHash);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SchainsInternal.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol";
import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol";
import "./interfaces/ISkaleDKG.sol";
import "./utils/Random.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
/**
* @title SchainsInternal
* @dev Contract contains all functionality logic to internally manage Schains.
*/
contract SchainsInternal is Permissions, ISchainsInternal {
using Random for Random.RandomGenerator;
using EnumerableSet for EnumerableSet.UintSet;
struct Schain {
string name;
address owner;
uint indexInOwnerList;
uint8 partOfNode;
uint lifetime;
uint startDate;
uint startBlock;
uint deposit;
uint64 index;
}
struct SchainType {
uint8 partOfNode;
uint numberOfNodes;
}
// mapping which contain all schains
mapping (bytes32 => Schain) public schains;
mapping (bytes32 => bool) public isSchainActive;
mapping (bytes32 => uint[]) public schainsGroups;
mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups;
// mapping shows schains by owner's address
mapping (address => bytes32[]) public schainIndexes;
// mapping shows schains which Node composed in
mapping (uint => bytes32[]) public schainsForNodes;
mapping (uint => uint[]) public holesForNodes;
mapping (bytes32 => uint[]) public holesForSchains;
// array which contain all schains
bytes32[] public schainsAtSystem;
uint64 public numberOfSchains;
// total resources that schains occupied
uint public sumOfSchainsResources;
mapping (bytes32 => bool) public usedSchainNames;
mapping (uint => SchainType) public schainTypes;
uint public numberOfSchainTypes;
// schain hash => node index => index of place
// index of place is a number from 1 to max number of slots on node(128)
mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode;
mapping (uint => bytes32[]) private _nodeToLockedSchains;
mapping (bytes32 => uint[]) private _schainToExceptionNodes;
EnumerableSet.UintSet private _keysOfSchainTypes;
bytes32 public constant SCHAIN_TYPE_MANAGER_ROLE = keccak256("SCHAIN_TYPE_MANAGER_ROLE");
bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE");
modifier onlySchainTypeManager() {
require(hasRole(SCHAIN_TYPE_MANAGER_ROLE, msg.sender), "SCHAIN_TYPE_MANAGER_ROLE is required");
_;
}
modifier onlyDebugger() {
require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required");
_;
}
/**
* @dev Allows Schain contract to initialize an schain.
*/
function initializeSchain(
string calldata name,
address from,
uint lifetime,
uint deposit) external allow("Schains")
{
bytes32 schainHash = keccak256(abi.encodePacked(name));
schains[schainHash].name = name;
schains[schainHash].owner = from;
schains[schainHash].startDate = block.timestamp;
schains[schainHash].startBlock = block.number;
schains[schainHash].lifetime = lifetime;
schains[schainHash].deposit = deposit;
schains[schainHash].index = numberOfSchains;
isSchainActive[schainHash] = true;
numberOfSchains++;
schainsAtSystem.push(schainHash);
usedSchainNames[schainHash] = true;
}
/**
* @dev Allows Schain contract to create a node group for an schain.
*/
function createGroupForSchain(
bytes32 schainHash,
uint numberOfNodes,
uint8 partOfNode
)
external
allow("Schains")
returns (uint[] memory)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
schains[schainHash].partOfNode = partOfNode;
if (partOfNode > 0) {
sumOfSchainsResources = sumOfSchainsResources.add(
numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode)
);
}
return _generateGroup(schainHash, numberOfNodes);
}
/**
* @dev Allows Schains contract to set index in owner list.
*/
function setSchainIndex(bytes32 schainHash, address from) external allow("Schains") {
schains[schainHash].indexInOwnerList = schainIndexes[from].length;
schainIndexes[from].push(schainHash);
}
/**
* @dev Allows Schains contract to change the Schain lifetime through
* an additional SKL token deposit.
*/
function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external allow("Schains") {
schains[schainHash].deposit = schains[schainHash].deposit.add(deposit);
schains[schainHash].lifetime = schains[schainHash].lifetime.add(lifetime);
}
/**
* @dev Allows Schains contract to remove an schain from the network.
* Generally schains are not removed from the system; instead they are
* simply allowed to expire.
*/
function removeSchain(bytes32 schainHash, address from) external allow("Schains") {
isSchainActive[schainHash] = false;
uint length = schainIndexes[from].length;
uint index = schains[schainHash].indexInOwnerList;
if (index != length.sub(1)) {
bytes32 lastSchainHash = schainIndexes[from][length.sub(1)];
schains[lastSchainHash].indexInOwnerList = index;
schainIndexes[from][index] = lastSchainHash;
}
schainIndexes[from].pop();
// TODO:
// optimize
for (uint i = 0; i + 1 < schainsAtSystem.length; i++) {
if (schainsAtSystem[i] == schainHash) {
schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)];
break;
}
}
schainsAtSystem.pop();
delete schains[schainHash];
numberOfSchains--;
}
/**
* @dev Allows Schains and SkaleDKG contracts to remove a node from an
* schain for node rotation or DKG failure.
*/
function removeNodeFromSchain(
uint nodeIndex,
bytes32 schainHash
)
external
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint indexOfNode = _findNode(schainHash, nodeIndex);
uint indexOfLastNode = schainsGroups[schainHash].length.sub(1);
if (indexOfNode == indexOfLastNode) {
schainsGroups[schainHash].pop();
} else {
delete schainsGroups[schainHash][indexOfNode];
if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) {
uint hole = holesForSchains[schainHash][0];
holesForSchains[schainHash][0] = indexOfNode;
holesForSchains[schainHash].push(hole);
} else {
holesForSchains[schainHash].push(indexOfNode);
}
}
uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash);
removeSchainForNode(nodeIndex, schainIndexOnNode);
delete placeOfSchainOnNode[schainHash][nodeIndex];
}
/**
* @dev Allows Schains contract to delete a group of schains
*/
function deleteGroup(bytes32 schainHash) external allow("Schains") {
// delete channel
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
delete schainsGroups[schainHash];
skaleDKG.deleteChannel(schainHash);
}
/**
* @dev Allows Schain and NodeRotation contracts to set a Node like
* exception for a given schain and nodeIndex.
*/
function setException(bytes32 schainHash, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
_setException(schainHash, nodeIndex);
}
/**
* @dev Allows Schains and NodeRotation contracts to add node to an schain
* group.
*/
function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
if (holesForSchains[schainHash].length == 0) {
schainsGroups[schainHash].push(nodeIndex);
} else {
schainsGroups[schainHash][holesForSchains[schainHash][0]] = nodeIndex;
uint min = uint(-1);
uint index = 0;
for (uint i = 1; i < holesForSchains[schainHash].length; i++) {
if (min > holesForSchains[schainHash][i]) {
min = holesForSchains[schainHash][i];
index = i;
}
}
if (min == uint(-1)) {
delete holesForSchains[schainHash];
} else {
holesForSchains[schainHash][0] = min;
holesForSchains[schainHash][index] =
holesForSchains[schainHash][holesForSchains[schainHash].length - 1];
holesForSchains[schainHash].pop();
}
}
}
/**
* @dev Allows Schains contract to remove holes for schains
*/
function removeHolesForSchain(bytes32 schainHash) external allow("Schains") {
delete holesForSchains[schainHash];
}
/**
* @dev Allows Admin to add schain type
*/
function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlySchainTypeManager {
require(_keysOfSchainTypes.add(numberOfSchainTypes + 1), "Schain type is already added");
schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode;
schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes;
numberOfSchainTypes++;
}
/**
* @dev Allows Admin to remove schain type
*/
function removeSchainType(uint typeOfSchain) external onlySchainTypeManager {
require(_keysOfSchainTypes.remove(typeOfSchain), "Schain type is already removed");
delete schainTypes[typeOfSchain].partOfNode;
delete schainTypes[typeOfSchain].numberOfNodes;
}
/**
* @dev Allows Admin to set number of schain types
*/
function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlySchainTypeManager {
numberOfSchainTypes = newNumberOfSchainTypes;
}
/**
* @dev Allows Admin to move schain to placeOfSchainOnNode map
*/
function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyDebugger {
for (uint i = 0; i < schainsGroups[schainHash].length; i++) {
uint nodeIndex = schainsGroups[schainHash][i];
for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) {
if (schainsForNodes[nodeIndex][j] == schainHash) {
placeOfSchainOnNode[schainHash][nodeIndex] = j + 1;
}
}
}
}
function removeNodeFromAllExceptionSchains(uint nodeIndex) external allow("SkaleManager") {
uint len = _nodeToLockedSchains[nodeIndex].length;
if (len > 0) {
for (uint i = len; i > 0; i--) {
removeNodeFromExceptions(_nodeToLockedSchains[nodeIndex][i - 1], nodeIndex);
}
}
}
function makeSchainNodesInvisible(bytes32 schainHash) external allowTwo("NodeRotation", "SkaleDKG") {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) {
nodes.makeNodeInvisible(_schainToExceptionNodes[schainHash][i]);
}
}
function makeSchainNodesVisible(bytes32 schainHash) external allowTwo("NodeRotation", "SkaleDKG") {
_makeSchainNodesVisible(schainHash);
}
/**
* @dev Returns all Schains in the network.
*/
function getSchains() external view returns (bytes32[] memory) {
return schainsAtSystem;
}
/**
* @dev Returns all occupied resources on one node for an Schain.
*/
function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8) {
return schains[schainHash].partOfNode;
}
/**
* @dev Returns number of schains by schain owner.
*/
function getSchainListSize(address from) external view returns (uint) {
return schainIndexes[from].length;
}
/**
* @dev Returns hashes of schain names by schain owner.
*/
function getSchainHashsByAddress(address from) external view returns (bytes32[] memory) {
return schainIndexes[from];
}
/**
* @dev Returns hashes of schain names by schain owner.
*/
function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) {
return schainIndexes[from];
}
/**
* @dev Returns hashes of schain names running on a node.
*/
function getSchainHashsForNode(uint nodeIndex) external view returns (bytes32[] memory) {
return schainsForNodes[nodeIndex];
}
/**
* @dev Returns hashes of schain names running on a node.
*/
function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) {
return schainsForNodes[nodeIndex];
}
/**
* @dev Returns the owner of an schain.
*/
function getSchainOwner(bytes32 schainHash) external view returns (address) {
return schains[schainHash].owner;
}
/**
* @dev Checks whether schain name is available.
* TODO Need to delete - copy of web3.utils.soliditySha3
*/
function isSchainNameAvailable(string calldata name) external view returns (bool) {
bytes32 schainHash = keccak256(abi.encodePacked(name));
return schains[schainHash].owner == address(0) &&
!usedSchainNames[schainHash] &&
keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet"));
}
/**
* @dev Checks whether schain lifetime has expired.
*/
function isTimeExpired(bytes32 schainHash) external view returns (bool) {
return uint(schains[schainHash].startDate).add(schains[schainHash].lifetime) < block.timestamp;
}
/**
* @dev Checks whether address is owner of schain.
*/
function isOwnerAddress(address from, bytes32 schainHash) external view override returns (bool) {
return schains[schainHash].owner == from;
}
/**
* @dev Checks whether schain exists.
*/
function isSchainExist(bytes32 schainHash) external view returns (bool) {
return keccak256(abi.encodePacked(schains[schainHash].name)) != keccak256(abi.encodePacked(""));
}
/**
* @dev Returns schain name.
*/
function getSchainName(bytes32 schainHash) external view returns (string memory) {
return schains[schainHash].name;
}
/**
* @dev Returns last active schain of a node.
*/
function getActiveSchain(uint nodeIndex) external view returns (bytes32) {
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
return schainsForNodes[nodeIndex][i - 1];
}
}
return bytes32(0);
}
/**
* @dev Returns active schains of a node.
*/
function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) {
uint activeAmount = 0;
for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) {
if (schainsForNodes[nodeIndex][i] != bytes32(0)) {
activeAmount++;
}
}
uint cursor = 0;
activeSchains = new bytes32[](activeAmount);
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1];
}
}
}
/**
* @dev Returns number of nodes in an schain group.
*/
function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint) {
return schainsGroups[schainHash].length;
}
/**
* @dev Returns nodes in an schain group.
*/
function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory) {
return schainsGroups[schainHash];
}
/**
* @dev Checks whether sender is a node address from a given schain group.
*/
function isNodeAddressesInGroup(bytes32 schainHash, address sender) external view override returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < schainsGroups[schainHash].length; i++) {
if (nodes.getNodeAddress(schainsGroups[schainHash][i]) == sender) {
return true;
}
}
return false;
}
/**
* @dev Returns node index in schain group.
*/
function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint) {
for (uint index = 0; index < schainsGroups[schainHash].length; index++) {
if (schainsGroups[schainHash][index] == nodeId) {
return index;
}
}
return schainsGroups[schainHash].length;
}
/**
* @dev Checks whether there are any nodes with free resources for given
* schain.
*/
function isAnyFreeNode(bytes32 schainHash) external view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainHash].partOfNode;
return nodes.countNodesWithFreeSpace(space) > 0;
}
/**
* @dev Returns whether any exceptions exist for node in a schain group.
*/
function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
return _exceptionsForGroups[schainHash][nodeIndex];
}
function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) {
for (uint i = 0; i < holesForSchains[schainHash].length; i++) {
if (holesForSchains[schainHash][i] == indexOfNode) {
return true;
}
}
return false;
}
/**
* @dev Returns number of Schains on a node.
*/
function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) {
return schainsForNodes[nodeIndex].length;
}
function getSchainType(uint typeOfSchain) external view returns(uint8, uint) {
require(_keysOfSchainTypes.contains(typeOfSchain), "Invalid type of schain");
return (schainTypes[typeOfSchain].partOfNode, schainTypes[typeOfSchain].numberOfNodes);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
numberOfSchains = 0;
sumOfSchainsResources = 0;
numberOfSchainTypes = 0;
}
/**
* @dev Allows Schains and NodeRotation contracts to add schain to node.
*/
function addSchainForNode(uint nodeIndex, bytes32 schainHash) public allowTwo("Schains", "NodeRotation") {
if (holesForNodes[nodeIndex].length == 0) {
schainsForNodes[nodeIndex].push(schainHash);
placeOfSchainOnNode[schainHash][nodeIndex] = schainsForNodes[nodeIndex].length;
} else {
uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1];
schainsForNodes[nodeIndex][lastHoleOfNode] = schainHash;
placeOfSchainOnNode[schainHash][nodeIndex] = lastHoleOfNode + 1;
holesForNodes[nodeIndex].pop();
}
}
/**
* @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an
* schain from a node.
*/
function removeSchainForNode(uint nodeIndex, uint schainIndex)
public
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint length = schainsForNodes[nodeIndex].length;
if (schainIndex == length.sub(1)) {
schainsForNodes[nodeIndex].pop();
} else {
delete schainsForNodes[nodeIndex][schainIndex];
if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) {
uint hole = holesForNodes[nodeIndex][0];
holesForNodes[nodeIndex][0] = schainIndex;
holesForNodes[nodeIndex].push(hole);
} else {
holesForNodes[nodeIndex].push(schainIndex);
}
}
}
/**
* @dev Allows Schains contract to remove node from exceptions
*/
function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex)
public
allowThree("Schains", "NodeRotation", "SkaleManager")
{
_exceptionsForGroups[schainHash][nodeIndex] = false;
uint len = _nodeToLockedSchains[nodeIndex].length;
bool removed = false;
if (len > 0 && _nodeToLockedSchains[nodeIndex][len - 1] == schainHash) {
_nodeToLockedSchains[nodeIndex].pop();
removed = true;
} else {
for (uint i = len; i > 0 && !removed; i--) {
if (_nodeToLockedSchains[nodeIndex][i - 1] == schainHash) {
_nodeToLockedSchains[nodeIndex][i - 1] = _nodeToLockedSchains[nodeIndex][len - 1];
_nodeToLockedSchains[nodeIndex].pop();
removed = true;
}
}
}
len = _schainToExceptionNodes[schainHash].length;
removed = false;
if (len > 0 && _schainToExceptionNodes[schainHash][len - 1] == nodeIndex) {
_schainToExceptionNodes[schainHash].pop();
removed = true;
} else {
for (uint i = len; i > 0 && !removed; i--) {
if (_schainToExceptionNodes[schainHash][i - 1] == nodeIndex) {
_schainToExceptionNodes[schainHash][i - 1] = _schainToExceptionNodes[schainHash][len - 1];
_schainToExceptionNodes[schainHash].pop();
removed = true;
}
}
}
}
/**
* @dev Returns index of Schain in list of schains for a given node.
*/
function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainHash) public view returns (uint) {
if (placeOfSchainOnNode[schainHash][nodeIndex] == 0)
return schainsForNodes[nodeIndex].length;
return placeOfSchainOnNode[schainHash][nodeIndex] - 1;
}
function _getNodeToLockedSchains() internal view returns (mapping(uint => bytes32[]) storage) {
return _nodeToLockedSchains;
}
function _getSchainToExceptionNodes() internal view returns (mapping(bytes32 => uint[]) storage) {
return _schainToExceptionNodes;
}
/**
* @dev Generates schain group using a pseudo-random generator.
*/
function _generateGroup(bytes32 schainHash, uint numberOfNodes) private returns (uint[] memory nodesInGroup) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainHash].partOfNode;
nodesInGroup = new uint[](numberOfNodes);
require(nodes.countNodesWithFreeSpace(space) >= nodesInGroup.length, "Not enough nodes to create Schain");
Random.RandomGenerator memory randomGenerator = Random.createFromEntropy(
abi.encodePacked(uint(blockhash(block.number.sub(1))), schainHash)
);
for (uint i = 0; i < numberOfNodes; i++) {
uint node = nodes.getRandomNodeWithFreeSpace(space, randomGenerator);
nodesInGroup[i] = node;
_setException(schainHash, node);
addSchainForNode(node, schainHash);
nodes.makeNodeInvisible(node);
require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node");
}
// set generated group
schainsGroups[schainHash] = nodesInGroup;
_makeSchainNodesVisible(schainHash);
}
function _setException(bytes32 schainHash, uint nodeIndex) private {
_exceptionsForGroups[schainHash][nodeIndex] = true;
_nodeToLockedSchains[nodeIndex].push(schainHash);
_schainToExceptionNodes[schainHash].push(nodeIndex);
}
function _makeSchainNodesVisible(bytes32 schainHash) private {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) {
nodes.makeNodeVisible(_schainToExceptionNodes[schainHash][i]);
}
}
/**
* @dev Returns local index of node in schain group.
*/
function _findNode(bytes32 schainHash, uint nodeIndex) private view returns (uint) {
uint[] memory nodesInGroup = schainsGroups[schainHash];
uint index;
for (index = 0; index < nodesInGroup.length; index++) {
if (nodesInGroup[index] == nodeIndex) {
return index;
}
}
return index;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FieldOperations.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./Precompiled.sol";
library Fp2Operations {
using SafeMath for uint;
struct Fp2Point {
uint a;
uint b;
}
uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) });
}
function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) });
}
function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure
returns (Fp2Point memory difference)
{
uint p = P;
if (diminished.a >= subtracted.a) {
difference.a = addmod(diminished.a, p - subtracted.a, p);
} else {
difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p);
}
if (diminished.b >= subtracted.b) {
difference.b = addmod(diminished.b, p - subtracted.b, p);
} else {
difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p);
}
}
function mulFp2(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (Fp2Point memory result)
{
uint p = P;
Fp2Point memory point = Fp2Point({
a: mulmod(value1.a, value2.a, p),
b: mulmod(value1.b, value2.b, p)});
result.a = addmod(
point.a,
mulmod(p - 1, point.b, p),
p);
result.b = addmod(
mulmod(
addmod(value1.a, value1.b, p),
addmod(value2.a, value2.b, p),
p),
p - addmod(point.a, point.b, p),
p);
}
function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) {
uint p = P;
uint ab = mulmod(value.a, value.b, p);
uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p);
return Fp2Point({ a: mult, b: addmod(ab, ab, p) });
}
function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) {
uint p = P;
uint t0 = mulmod(value.a, value.a, p);
uint t1 = mulmod(value.b, value.b, p);
uint t2 = mulmod(p - 1, t1, p);
if (t0 >= t2) {
t2 = addmod(t0, p - t2, p);
} else {
t2 = (p - addmod(t2, p - t0, p)).mod(p);
}
uint t3 = Precompiled.bigModExp(t2, p - 2, p);
result.a = mulmod(value.a, t3, p);
result.b = (p - mulmod(value.b, t3, p)).mod(p);
}
function isEqual(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (bool)
{
return value1.a == value2.a && value1.b == value2.b;
}
}
library G1Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 1,
b: 2
});
}
function isG1Point(uint x, uint y) internal pure returns (bool) {
uint p = Fp2Operations.P;
return mulmod(y, y, p) ==
addmod(mulmod(mulmod(x, x, p), x, p), 3, p);
}
function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return isG1Point(point.a, point.b);
}
function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return point.a < Fp2Operations.P && point.b < Fp2Operations.P;
}
function negate(uint y) internal pure returns (uint) {
return Fp2Operations.P.sub(y).mod(Fp2Operations.P);
}
}
library G2Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
struct G2Point {
Fp2Operations.Fp2Point x;
Fp2Operations.Fp2Point y;
}
function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 19485874751759354771024239261021720505790618469301721065564631296452457478373,
b: 266929791119991161246907387137283842545076965332900288569378510910307636690
});
}
function getG2Generator() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 10857046999023057135944570762232829481370756359578518086990519993285655852781,
b: 11559732032986387107991004021392285783925812861821192530917403151452391805634
}),
y: Fp2Operations.Fp2Point({
a: 8495653923123431417604973247489272438418190587263600148770280649306958101930,
b: 4082367875863433681332203403145435568316851327593401208105741076214120093531
})
});
}
function getG2Zero() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 0,
b: 0
}),
y: Fp2Operations.Fp2Point({
a: 1,
b: 0
})
});
}
function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) {
if (isG2ZeroPoint(x, y)) {
return true;
}
Fp2Operations.Fp2Point memory squaredY = y.squaredFp2();
Fp2Operations.Fp2Point memory res = squaredY.minusFp2(
x.squaredFp2().mulFp2(x)
).minusFp2(getTWISTB());
return res.a == 0 && res.b == 0;
}
function isG2(G2Point memory value) internal pure returns (bool) {
return isG2Point(value.x, value.y);
}
function isG2ZeroPoint(
Fp2Operations.Fp2Point memory x,
Fp2Operations.Fp2Point memory y
)
internal
pure
returns (bool)
{
return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0;
}
function isG2Zero(G2Point memory value) internal pure returns (bool) {
return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0;
// return isG2ZeroPoint(value.x, value.y);
}
function addG2(
G2Point memory value1,
G2Point memory value2
)
internal
view
returns (G2Point memory sum)
{
if (isG2Zero(value1)) {
return value2;
}
if (isG2Zero(value2)) {
return value1;
}
if (isEqual(value1, value2)) {
return doubleG2(value1);
}
Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2());
sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x));
sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x)));
uint p = Fp2Operations.P;
sum.y.a = (p - sum.y.a).mod(p);
sum.y.b = (p - sum.y.b).mod(p);
}
function isEqual(
G2Point memory value1,
G2Point memory value2
)
internal
pure
returns (bool)
{
return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y);
}
function doubleG2(G2Point memory value)
internal
view
returns (G2Point memory result)
{
if (isG2Zero(value)) {
return value;
} else {
Fp2Operations.Fp2Point memory s =
value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2());
result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x));
result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x)));
uint p = Fp2Operations.P;
result.y.a = (p - result.y.a).mod(p);
result.y.b = (p - result.y.b).mod(p);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
NodeRotation.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./interfaces/ISkaleDKG.sol";
import "./utils/Random.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./Schains.sol";
/**
* @title NodeRotation
* @dev This contract handles all node rotation functionality.
*/
contract NodeRotation is Permissions {
using Random for Random.RandomGenerator;
/**
* nodeIndex - index of Node which is in process of rotation (left from schain)
* newNodeIndex - index of Node which is rotated(added to schain)
* freezeUntil - time till which Node should be turned on
* rotationCounter - how many rotations were on this schain
*/
struct Rotation {
uint nodeIndex;
uint newNodeIndex;
uint freezeUntil;
uint rotationCounter;
}
struct LeavingHistory {
bytes32 schainIndex;
uint finishedRotation;
}
mapping (bytes32 => Rotation) public rotations;
mapping (uint => LeavingHistory[]) public leavingHistory;
mapping (bytes32 => bool) public waitForNewNode;
bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE");
modifier onlyDebugger() {
require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required");
_;
}
/**
* @dev Allows SkaleManager to remove, find new node, and rotate node from
* schain.
*
* Requirements:
*
* - A free node must exist.
*/
function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool, bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainHash = schainsInternal.getActiveSchain(nodeIndex);
if (schainHash == bytes32(0)) {
return (true, false);
}
_startRotation(schainHash, nodeIndex);
rotateNode(nodeIndex, schainHash, true, false);
return (schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false, true);
}
/**
* @dev Allows SkaleManager contract to freeze all schains on a given node.
*/
function freezeSchains(uint nodeIndex) external allow("SkaleManager") {
bytes32[] memory schains = SchainsInternal(
contractManager.getContract("SchainsInternal")
).getSchainHashsForNode(nodeIndex);
for (uint i = 0; i < schains.length; i++) {
if (schains[i] != bytes32(0)) {
require(
ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schains[i]),
"DKG did not finish on Schain"
);
if (rotations[schains[i]].freezeUntil < now) {
_startWaiting(schains[i], nodeIndex);
} else {
if (rotations[schains[i]].nodeIndex != nodeIndex) {
revert("Occupied by rotation on Schain");
}
}
}
}
}
/**
* @dev Allows Schains contract to remove a rotation from an schain.
*/
function removeRotation(bytes32 schainIndex) external allow("Schains") {
delete rotations[schainIndex];
}
/**
* @dev Allows Owner to immediately rotate an schain.
*/
function skipRotationDelay(bytes32 schainIndex) external onlyDebugger {
rotations[schainIndex].freezeUntil = now;
}
/**
* @dev Returns rotation details for a given schain.
*/
function getRotation(bytes32 schainIndex) external view returns (Rotation memory) {
return rotations[schainIndex];
}
/**
* @dev Returns leaving history for a given node.
*/
function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) {
return leavingHistory[nodeIndex];
}
function isRotationInProgress(bytes32 schainIndex) external view returns (bool) {
return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex];
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an
* schain.
*/
function rotateNode(
uint nodeIndex,
bytes32 schainHash,
bool shouldDelay,
bool isBadNode
)
public
allowTwo("SkaleDKG", "SkaleManager")
returns (uint newNode)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
schainsInternal.removeNodeFromSchain(nodeIndex, schainHash);
if (!isBadNode) {
schainsInternal.removeNodeFromExceptions(schainHash, nodeIndex);
}
newNode = selectNodeToGroup(schainHash);
Nodes(contractManager.getContract("Nodes")).addSpaceToNode(
nodeIndex,
schainsInternal.getSchainsPartOfNode(schainHash)
);
_finishRotation(schainHash, nodeIndex, newNode, shouldDelay);
}
/**
* @dev Allows SkaleManager, Schains, and SkaleDKG contracts to
* pseudo-randomly select a new Node for an Schain.
*
* Requirements:
*
* - Schain is active.
* - A free node already exists.
* - Free space can be allocated from the node.
*/
function selectNodeToGroup(bytes32 schainHash)
public
allowThree("SkaleManager", "Schains", "SkaleDKG")
returns (uint nodeIndex)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
require(schainsInternal.isSchainActive(schainHash), "Group is not active");
uint8 space = schainsInternal.getSchainsPartOfNode(schainHash);
schainsInternal.makeSchainNodesInvisible(schainHash);
require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes available for rotation");
Random.RandomGenerator memory randomGenerator = Random.createFromEntropy(
abi.encodePacked(uint(blockhash(block.number - 1)), schainHash)
);
nodeIndex = nodes.getRandomNodeWithFreeSpace(space, randomGenerator);
require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex");
schainsInternal.makeSchainNodesVisible(schainHash);
schainsInternal.addSchainForNode(nodeIndex, schainHash);
schainsInternal.setException(schainHash, nodeIndex);
schainsInternal.setNodeInGroup(schainHash, nodeIndex);
}
/**
* @dev Initiates rotation of a node from an schain.
*/
function _startRotation(bytes32 schainIndex, uint nodeIndex) private {
rotations[schainIndex].newNodeIndex = nodeIndex;
waitForNewNode[schainIndex] = true;
}
function _startWaiting(bytes32 schainIndex, uint nodeIndex) private {
ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
rotations[schainIndex].nodeIndex = nodeIndex;
rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay());
}
/**
* @dev Completes rotation of a node from an schain.
*/
function _finishRotation(
bytes32 schainIndex,
uint nodeIndex,
uint newNodeIndex,
bool shouldDelay)
private
{
leavingHistory[nodeIndex].push(
LeavingHistory(
schainIndex,
shouldDelay ? now.add(
ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay()
) : now
)
);
rotations[schainIndex].newNodeIndex = newNodeIndex;
rotations[schainIndex].rotationCounter++;
delete waitForNewNode[schainIndex];
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex);
}
/**
* @dev Checks whether a rotation can be performed.
*
* Requirements:
*
* - Schain must exist.
*/
function _checkRotation(bytes32 schainHash ) private view returns (bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainExist(schainHash), "Schain does not exist for rotation");
return schainsInternal.isAnyFreeNode(schainHash);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISkaleDKG.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface to {SkaleDKG}.
*/
interface ISkaleDKG {
/**
* @dev See {SkaleDKG-openChannel}.
*/
function openChannel(bytes32 schainHash) external;
/**
* @dev See {SkaleDKG-deleteChannel}.
*/
function deleteChannel(bytes32 schainHash) external;
/**
* @dev See {SkaleDKG-isLastDKGSuccessful}.
*/
function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool);
/**
* @dev See {SkaleDKG-isChannelOpened}.
*/
function isChannelOpened(bytes32 schainHash) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Modifications Copyright (C) 2018 SKALE Labs
ec.sol by @jbaylina under GPL-3.0 License
*/
/** @file ECDH.sol
* @author Jordi Baylina (@jbaylina)
* @date 2016
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title ECDH
* @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to
* support the DKG process.
*/
contract ECDH {
using SafeMath for uint256;
uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant private _A = 0;
function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) {
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
_GX,
_GY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function deriveKey(
uint256 privKey,
uint256 pubX,
uint256 pubY
)
external
pure
returns (uint256 qx, uint256 qy)
{
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
pubX,
pubY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function jAdd(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N));
}
function jSub(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N));
}
function jMul(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N));
}
function jDiv(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N));
}
function inverse(uint256 a) public pure returns (uint256 invA) {
require(a > 0 && a < _N, "Input is incorrect");
uint256 t = 0;
uint256 newT = 1;
uint256 r = _N;
uint256 newR = a;
uint256 q;
while (newR != 0) {
q = r.div(newR);
(t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N));
(r, newR) = (newR, r % newR);
}
return t;
}
function ecAdd(
uint256 x1,
uint256 y1,
uint256 z1,
uint256 x2,
uint256 y2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 ln;
uint256 lz;
uint256 da;
uint256 db;
// we use (0 0 1) as zero point, z always equal 1
if ((x1 == 0) && (y1 == 0)) {
return (x2, y2, z2);
}
// we use (0 0 1) as zero point, z always equal 1
if ((x2 == 0) && (y2 == 0)) {
return (x1, y1, z1);
}
if ((x1 == x2) && (y1 == y2)) {
(ln, lz) = jMul(x1, z1, x1, z1);
(ln, lz) = jMul(ln,lz,3,1);
(ln, lz) = jAdd(ln,lz,_A,1);
(da, db) = jMul(y1,z1,2,1);
} else {
(ln, lz) = jSub(y2,z2,y1,z1);
(da, db) = jSub(x2,z2,x1,z1);
}
(ln, lz) = jDiv(ln,lz,da,db);
(x3, da) = jMul(ln,lz,ln,lz);
(x3, da) = jSub(x3,da,x1,z1);
(x3, da) = jSub(x3,da,x2,z2);
(y3, db) = jSub(x1,z1,x3,da);
(y3, db) = jMul(y3,db,ln,lz);
(y3, db) = jSub(y3,db,y1,z1);
if (da != db) {
x3 = mulmod(x3, db, _N);
y3 = mulmod(y3, da, _N);
z3 = mulmod(da, db, _N);
} else {
z3 = da;
}
}
function ecDouble(
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
(x3, y3, z3) = ecAdd(
x1,
y1,
z1,
x1,
y1,
z1
);
}
function ecMul(
uint256 d,
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 remaining = d;
uint256 px = x1;
uint256 py = y1;
uint256 pz = z1;
uint256 acx = 0;
uint256 acy = 0;
uint256 acz = 1;
if (d == 0) {
return (0, 0, 1);
}
while (remaining != 0) {
if ((remaining & 1) != 0) {
(acx, acy, acz) = ecAdd(
acx,
acy,
acz,
px,
py,
pz
);
}
remaining = remaining.div(2);
(px, py, pz) = ecDouble(px, py, pz);
}
(x3, y3, z3) = (acx, acy, acz);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Precompiled.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library Precompiled {
function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) {
uint[6] memory inputToBigModExp;
inputToBigModExp[0] = 32;
inputToBigModExp[1] = 32;
inputToBigModExp[2] = 32;
inputToBigModExp[3] = base;
inputToBigModExp[4] = power;
inputToBigModExp[5] = modulus;
uint[1] memory out;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20)
}
require(success, "BigModExp failed");
return out[0];
}
function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) {
uint[3] memory inputToMul;
uint[2] memory output;
inputToMul[0] = x;
inputToMul[1] = y;
inputToMul[2] = k;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40)
}
require(success, "Multiplication failed");
return (output[0], output[1]);
}
function bn256Pairing(
uint x1,
uint y1,
uint a1,
uint b1,
uint c1,
uint d1,
uint x2,
uint y2,
uint a2,
uint b2,
uint c2,
uint d2)
internal view returns (bool)
{
bool success;
uint[12] memory inputToPairing;
inputToPairing[0] = x1;
inputToPairing[1] = y1;
inputToPairing[2] = a1;
inputToPairing[3] = b1;
inputToPairing[4] = c1;
inputToPairing[5] = d1;
inputToPairing[6] = x2;
inputToPairing[7] = y2;
inputToPairing[8] = a2;
inputToPairing[9] = b2;
inputToPairing[10] = c2;
inputToPairing[11] = d2;
uint[1] memory out;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20)
}
require(success, "Pairing check failed");
return out[0] != 0;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgBroadcast.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../SkaleDKG.sol";
import "../KeyStorage.sol";
import "../utils/FieldOperations.sol";
/**
* @title SkaleDkgBroadcast
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgBroadcast {
using SafeMath for uint;
/**
* @dev Emitted when a node broadcasts keyshare.
*/
event BroadcastAndKeyShare(
bytes32 indexed schainHash,
uint indexed fromNode,
G2Operations.G2Point[] verificationVector,
SkaleDKG.KeyShare[] secretKeyContribution
);
/**
* @dev Broadcasts verification vector and secret key contribution to all
* other nodes in the group.
*
* Emits BroadcastAndKeyShare event.
*
* Requirements:
*
* - `msg.sender` must have an associated node.
* - `verificationVector` must be a certain length.
* - `secretKeyContribution` length must be equal to number of nodes in group.
*/
function broadcast(
bytes32 schainHash,
uint nodeIndex,
G2Operations.G2Point[] memory verificationVector,
SkaleDKG.KeyShare[] memory secretKeyContribution,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess,
mapping(bytes32 => mapping(uint => bytes32)) storage hashedData
)
external
{
uint n = channels[schainHash].n;
require(verificationVector.length == getT(n), "Incorrect number of verification vectors");
require(
secretKeyContribution.length == n,
"Incorrect number of secret key shares"
);
(uint index, ) = SkaleDKG(contractManager.getContract("SkaleDKG")).checkAndReturnIndexInGroup(
schainHash, nodeIndex, true
);
require(!dkgProcess[schainHash].broadcasted[index], "This node has already broadcasted");
dkgProcess[schainHash].broadcasted[index] = true;
dkgProcess[schainHash].numberOfBroadcasted++;
if (dkgProcess[schainHash].numberOfBroadcasted == channels[schainHash].n) {
SkaleDKG(contractManager.getContract("SkaleDKG")).setStartAlrightTimestamp(schainHash);
}
hashedData[schainHash][index] = SkaleDKG(contractManager.getContract("SkaleDKG")).hashData(
secretKeyContribution, verificationVector
);
KeyStorage(contractManager.getContract("KeyStorage")).adding(schainHash, verificationVector[0]);
emit BroadcastAndKeyShare(
schainHash,
nodeIndex,
verificationVector,
secretKeyContribution
);
}
function getT(uint n) public pure returns (uint) {
return n.mul(2).add(1).div(3);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgComplaint.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../SkaleDKG.sol";
import "../ConstantsHolder.sol";
import "../Wallets.sol";
import "../Nodes.sol";
/**
* @title SkaleDkgComplaint
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgComplaint {
using SafeMath for uint;
/**
* @dev Emitted when an incorrect complaint is sent.
*/
event ComplaintError(string error);
/**
* @dev Emitted when a complaint is sent.
*/
event ComplaintSent(
bytes32 indexed schainHash, uint indexed fromNodeIndex, uint indexed toNodeIndex);
/**
* @dev Creates a complaint from a node (accuser) to a given node.
* The accusing node must broadcast additional parameters within 1800 blocks.
*
* Emits {ComplaintSent} or {ComplaintError} event.
*
* Requirements:
*
* - `msg.sender` must have an associated node.
*/
function complaint(
bytes32 schainHash,
uint fromNodeIndex,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => uint) storage startAlrightTimestamp
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
require(skaleDKG.isNodeBroadcasted(schainHash, fromNodeIndex), "Node has not broadcasted");
if (skaleDKG.isNodeBroadcasted(schainHash, toNodeIndex)) {
_handleComplaintWhenBroadcasted(
schainHash,
fromNodeIndex,
toNodeIndex,
contractManager,
complaints,
startAlrightTimestamp
);
} else {
// not broadcasted in 30 min
_handleComplaintWhenNotBroadcasted(schainHash, toNodeIndex, contractManager, channels);
}
skaleDKG.setBadNode(schainHash, toNodeIndex);
}
function complaintBadData(
bytes32 schainHash,
uint fromNodeIndex,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
require(skaleDKG.isNodeBroadcasted(schainHash, fromNodeIndex), "Node has not broadcasted");
require(skaleDKG.isNodeBroadcasted(schainHash, toNodeIndex), "Accused node has not broadcasted");
require(!skaleDKG.isAllDataReceived(schainHash, fromNodeIndex), "Node has already sent alright");
if (complaints[schainHash].nodeToComplaint == uint(-1)) {
complaints[schainHash].nodeToComplaint = toNodeIndex;
complaints[schainHash].fromNodeToComplaint = fromNodeIndex;
complaints[schainHash].startComplaintBlockTimestamp = block.timestamp;
emit ComplaintSent(schainHash, fromNodeIndex, toNodeIndex);
} else {
emit ComplaintError("First complaint has already been processed");
}
}
function _handleComplaintWhenBroadcasted(
bytes32 schainHash,
uint fromNodeIndex,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => uint) storage startAlrightTimestamp
)
private
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
// missing alright
if (complaints[schainHash].nodeToComplaint == uint(-1)) {
if (
skaleDKG.isEveryoneBroadcasted(schainHash) &&
!skaleDKG.isAllDataReceived(schainHash, toNodeIndex) &&
startAlrightTimestamp[schainHash].add(_getComplaintTimelimit(contractManager)) <= block.timestamp
) {
// missing alright
skaleDKG.finalizeSlashing(schainHash, toNodeIndex);
return;
} else if (!skaleDKG.isAllDataReceived(schainHash, fromNodeIndex)) {
// incorrect data
skaleDKG.finalizeSlashing(schainHash, fromNodeIndex);
return;
}
emit ComplaintError("Has already sent alright");
return;
} else if (complaints[schainHash].nodeToComplaint == toNodeIndex) {
// 30 min after incorrect data complaint
if (complaints[schainHash].startComplaintBlockTimestamp.add(
_getComplaintTimelimit(contractManager)
) <= block.timestamp) {
skaleDKG.finalizeSlashing(schainHash, complaints[schainHash].nodeToComplaint);
return;
}
emit ComplaintError("The same complaint rejected");
return;
}
emit ComplaintError("One complaint is already sent");
}
function _handleComplaintWhenNotBroadcasted(
bytes32 schainHash,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels
)
private
{
if (channels[schainHash].startedBlockTimestamp.add(
_getComplaintTimelimit(contractManager)
) <= block.timestamp) {
SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainHash, toNodeIndex);
return;
}
emit ComplaintError("Complaint sent too early");
}
function _getComplaintTimelimit(ContractManager contractManager) private view returns (uint) {
return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgPreResponse.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
import "../Wallets.sol";
import "../utils/FieldOperations.sol";
/**
* @title SkaleDkgPreResponse
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgPreResponse {
using SafeMath for uint;
using G2Operations for G2Operations.G2Point;
function preResponse(
bytes32 schainHash,
uint fromNodeIndex,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult,
SkaleDKG.KeyShare[] memory secretKeyContribution,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => mapping(uint => bytes32)) storage hashedData
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
uint index = _preResponseCheck(
schainHash,
fromNodeIndex,
verificationVector,
verificationVectorMult,
secretKeyContribution,
skaleDKG,
complaints,
hashedData
);
_processPreResponse(secretKeyContribution[index].share, schainHash, verificationVectorMult, complaints);
}
function _preResponseCheck(
bytes32 schainHash,
uint fromNodeIndex,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult,
SkaleDKG.KeyShare[] memory secretKeyContribution,
SkaleDKG skaleDKG,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => mapping(uint => bytes32)) storage hashedData
)
private
view
returns (uint index)
{
(uint indexOnSchain, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, fromNodeIndex, true);
require(complaints[schainHash].nodeToComplaint == fromNodeIndex, "Not this Node");
require(!complaints[schainHash].isResponse, "Already submitted pre response data");
require(
hashedData[schainHash][indexOnSchain] == skaleDKG.hashData(secretKeyContribution, verificationVector),
"Broadcasted Data is not correct"
);
require(
verificationVector.length == verificationVectorMult.length,
"Incorrect length of multiplied verification vector"
);
(index, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, complaints[schainHash].fromNodeToComplaint, true);
require(
_checkCorrectVectorMultiplication(index, verificationVector, verificationVectorMult),
"Multiplied verification vector is incorrect"
);
}
function _processPreResponse(
bytes32 share,
bytes32 schainHash,
G2Operations.G2Point[] memory verificationVectorMult,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
private
{
complaints[schainHash].keyShare = share;
complaints[schainHash].sumOfVerVec = _calculateSum(verificationVectorMult);
complaints[schainHash].isResponse = true;
}
function _calculateSum(G2Operations.G2Point[] memory verificationVectorMult)
private
view
returns (G2Operations.G2Point memory)
{
G2Operations.G2Point memory value = G2Operations.getG2Zero();
for (uint i = 0; i < verificationVectorMult.length; i++) {
value = value.addG2(verificationVectorMult[i]);
}
return value;
}
function _checkCorrectVectorMultiplication(
uint indexOnSchain,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult
)
private
view
returns (bool)
{
Fp2Operations.Fp2Point memory value = G1Operations.getG1Generator();
Fp2Operations.Fp2Point memory tmp = G1Operations.getG1Generator();
for (uint i = 0; i < verificationVector.length; i++) {
(tmp.a, tmp.b) = Precompiled.bn256ScalarMul(value.a, value.b, indexOnSchain.add(1) ** i);
if (!_checkPairing(tmp, verificationVector[i], verificationVectorMult[i])) {
return false;
}
}
return true;
}
function _checkPairing(
Fp2Operations.Fp2Point memory g1Mul,
G2Operations.G2Point memory verificationVector,
G2Operations.G2Point memory verificationVectorMult
)
private
view
returns (bool)
{
require(G1Operations.checkRange(g1Mul), "g1Mul is not valid");
g1Mul.b = G1Operations.negate(g1Mul.b);
Fp2Operations.Fp2Point memory one = G1Operations.getG1Generator();
return Precompiled.bn256Pairing(
one.a, one.b,
verificationVectorMult.x.b, verificationVectorMult.x.a,
verificationVectorMult.y.b, verificationVectorMult.y.a,
g1Mul.a, g1Mul.b,
verificationVector.x.b, verificationVector.x.a,
verificationVector.y.b, verificationVector.y.a
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgResponse.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
import "../Wallets.sol";
import "../Decryption.sol";
import "../Nodes.sol";
import "../thirdparty/ECDH.sol";
import "../utils/FieldOperations.sol";
/**
* @title SkaleDkgResponse
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgResponse {
using G2Operations for G2Operations.G2Point;
function response(
bytes32 schainHash,
uint fromNodeIndex,
uint secretNumber,
G2Operations.G2Point memory multipliedShare,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
external
{
uint index = SchainsInternal(contractManager.getContract("SchainsInternal"))
.getNodeIndexInGroup(schainHash, fromNodeIndex);
require(index < channels[schainHash].n, "Node is not in this group");
require(complaints[schainHash].nodeToComplaint == fromNodeIndex, "Not this Node");
require(complaints[schainHash].isResponse, "Have not submitted pre-response data");
uint badNode = _verifyDataAndSlash(
schainHash,
secretNumber,
multipliedShare,
contractManager,
complaints
);
SkaleDKG(contractManager.getContract("SkaleDKG")).setBadNode(schainHash, badNode);
}
function _verifyDataAndSlash(
bytes32 schainHash,
uint secretNumber,
G2Operations.G2Point memory multipliedShare,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
private
returns (uint badNode)
{
bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey(
complaints[schainHash].fromNodeToComplaint
);
uint256 pkX = uint(publicKey[0]);
(pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1]));
bytes32 key = bytes32(pkX);
// Decrypt secret key contribution
uint secret = Decryption(contractManager.getContract("Decryption")).decrypt(
complaints[schainHash].keyShare,
sha256(abi.encodePacked(key))
);
badNode = (
_checkCorrectMultipliedShare(multipliedShare, secret) &&
multipliedShare.isEqual(complaints[schainHash].sumOfVerVec) ?
complaints[schainHash].fromNodeToComplaint :
complaints[schainHash].nodeToComplaint
);
SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainHash, badNode);
}
function _checkCorrectMultipliedShare(
G2Operations.G2Point memory multipliedShare,
uint secret
)
private
view
returns (bool)
{
if (!multipliedShare.isG2()) {
return false;
}
G2Operations.G2Point memory tmp = multipliedShare;
Fp2Operations.Fp2Point memory g1 = G1Operations.getG1Generator();
Fp2Operations.Fp2Point memory share = Fp2Operations.Fp2Point({
a: 0,
b: 0
});
(share.a, share.b) = Precompiled.bn256ScalarMul(g1.a, g1.b, secret);
require(G1Operations.checkRange(share), "share is not valid");
share.b = G1Operations.negate(share.b);
require(G1Operations.isG1(share), "mulShare not in G1");
G2Operations.G2Point memory g2 = G2Operations.getG2Generator();
return Precompiled.bn256Pairing(
share.a, share.b,
g2.x.b, g2.x.a, g2.y.b, g2.y.a,
g1.a, g1.b,
tmp.x.b, tmp.x.a, tmp.y.b, tmp.y.a);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchains.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchains {
function verifySchainSignature(
uint256 signA,
uint256 signB,
bytes32 hash,
uint256 counter,
uint256 hashA,
uint256 hashB,
string calldata schainName
)
external
view
returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleVerifier.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
/**
* @title SkaleVerifier
* @dev Contains verify function to perform BLS signature verification.
*/
contract SkaleVerifier is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
/**
* @dev Verifies a BLS signature.
*
* Requirements:
*
* - Signature is in G1.
* - Hash is in G1.
* - G2.one in G2.
* - Public Key in G2.
*/
function verify(
Fp2Operations.Fp2Point calldata signature,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
G2Operations.G2Point calldata publicKey
)
external
view
returns (bool)
{
require(G1Operations.checkRange(signature), "Signature is not valid");
if (!_checkHashToGroupWithHelper(
hash,
counter,
hashA,
hashB
)
)
{
return false;
}
uint newSignB = G1Operations.negate(signature.b);
require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1");
require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1");
G2Operations.G2Point memory g2 = G2Operations.getG2Generator();
require(
G2Operations.isG2(publicKey),
"Public Key not in G2"
);
return Precompiled.bn256Pairing(
signature.a, newSignB,
g2.x.b, g2.x.a, g2.y.b, g2.y.a,
hashA, hashB,
publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
function _checkHashToGroupWithHelper(
bytes32 hash,
uint counter,
uint hashA,
uint hashB
)
private
pure
returns (bool)
{
if (counter > 100) {
return false;
}
uint xCoord = uint(hash) % Fp2Operations.P;
xCoord = (xCoord.add(counter)) % Fp2Operations.P;
uint ySquared = addmod(
mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P),
3,
Fp2Operations.P
);
if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) {
return false;
}
return true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchainsInternal - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchainsInternal {
function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool);
function isOwnerAddress(address from, bytes32 schainId) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Decryption.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @title Decryption
* @dev This contract performs encryption and decryption functions.
* Decrypt is used by SkaleDKG contract to decrypt secret key contribution to
* validate complaints during the DKG procedure.
*/
contract Decryption {
/**
* @dev Returns an encrypted text given a secret and a key.
*/
function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) {
return bytes32(secretNumber) ^ key;
}
/**
* @dev Returns a secret given an encrypted text and a key.
*/
function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) {
return uint256(ciphertext ^ key);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IWallets - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IWallets {
function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external;
function rechargeSchainWallet(bytes32 schainId) external payable;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
PartialDifferencesTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../delegation/PartialDifferences.sol";
contract PartialDifferencesTester {
using PartialDifferences for PartialDifferences.Sequence;
using PartialDifferences for PartialDifferences.Value;
using SafeMath for uint;
PartialDifferences.Sequence[] private _sequences;
// PartialDifferences.Value[] private _values;
function createSequence() external {
_sequences.push(PartialDifferences.Sequence({firstUnprocessedMonth: 0, lastChangedMonth: 0}));
}
function addToSequence(uint sequence, uint diff, uint month) external {
require(sequence < _sequences.length, "Sequence does not exist");
_sequences[sequence].addToSequence(diff, month);
}
function subtractFromSequence(uint sequence, uint diff, uint month) external {
require(sequence < _sequences.length, "Sequence does not exist");
_sequences[sequence].subtractFromSequence(diff, month);
}
function getAndUpdateSequenceItem(uint sequence, uint month) external returns (uint) {
require(sequence < _sequences.length, "Sequence does not exist");
return _sequences[sequence].getAndUpdateValueInSequence(month);
}
function reduceSequence(
uint sequence,
uint a,
uint b,
uint month) external
{
require(sequence < _sequences.length, "Sequence does not exist");
FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(a, b);
return _sequences[sequence].reduceSequence(reducingCoefficient, month);
}
function latestSequence() external view returns (uint id) {
require(_sequences.length > 0, "There are no _sequences");
return _sequences.length.sub(1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ReentrancyTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../Permissions.sol";
import "../delegation/DelegationController.sol";
contract ReentrancyTester is Permissions, IERC777Recipient, IERC777Sender {
IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bool private _reentrancyCheck = false;
bool private _burningAttack = false;
uint private _amount = 0;
constructor (address contractManagerAddress) public {
Permissions.initialize(contractManagerAddress);
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this));
}
function tokensReceived(
address /* operator */,
address /* from */,
address /* to */,
uint256 amount,
bytes calldata /* userData */,
bytes calldata /* operatorData */
)
external override
{
if (_reentrancyCheck) {
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
require(
skaleToken.transfer(contractManager.getContract("SkaleToken"), amount),
"Transfer is not successful");
}
}
function tokensToSend(
address, // operator
address, // from
address, // to
uint256, // amount
bytes calldata, // userData
bytes calldata // operatorData
) external override
{
if (_burningAttack) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
delegationController.delegate(
1,
_amount,
2,
"D2 is even");
}
}
function prepareToReentracyCheck() external {
_reentrancyCheck = true;
}
function prepareToBurningAttack() external {
_burningAttack = true;
}
function burningAttack() external {
IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken"));
_amount = skaleToken.balanceOf(address(this));
skaleToken.burn(_amount, "");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "./delegation/Distributor.sol";
import "./delegation/ValidatorService.sol";
import "./interfaces/IMintableToken.sol";
import "./BountyV2.sol";
import "./ConstantsHolder.sol";
import "./NodeRotation.sol";
import "./Permissions.sol";
import "./Schains.sol";
import "./Wallets.sol";
/**
* @title SkaleManager
* @dev Contract contains functions for node registration and exit, bounty
* management, and monitoring verdicts.
*/
contract SkaleManager is IERC777Recipient, Permissions {
IERC1820Registry private _erc1820;
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE");
string public version;
bytes32 public constant SCHAIN_DELETER_ROLE = keccak256("SCHAIN_DELETER_ROLE");
/**
* @dev Emitted when bounty is received.
*/
event BountyReceived(
uint indexed nodeIndex,
address owner,
uint averageDowntime,
uint averageLatency,
uint bounty,
uint previousBlockEvent,
uint time,
uint gasSpend
);
function tokensReceived(
address, // operator
address from,
address to,
uint256 value,
bytes calldata userData,
bytes calldata // operator data
)
external override
allow("SkaleToken")
{
require(to == address(this), "Receiver is incorrect");
if (userData.length > 0) {
Schains schains = Schains(
contractManager.getContract("Schains"));
schains.addSchain(from, value, userData);
}
}
function createNode(
uint16 port,
uint16 nonce,
bytes4 ip,
bytes4 publicIp,
bytes32[2] calldata publicKey,
string calldata name,
string calldata domainName
)
external
{
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
// validators checks inside checkPossibilityCreatingNode
nodes.checkPossibilityCreatingNode(msg.sender);
Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({
name: name,
ip: ip,
publicIp: publicIp,
port: port,
publicKey: publicKey,
nonce: nonce,
domainName: domainName
});
nodes.createNode(msg.sender, params);
}
function nodeExit(uint nodeIndex) external {
uint gasTotal = gasleft();
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint validatorId = nodes.getValidatorId(nodeIndex);
bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex));
if (!permitted && validatorService.validatorAddressExists(msg.sender)) {
permitted = validatorService.getValidatorId(msg.sender) == validatorId;
}
require(permitted, "Sender is not permitted to call this function");
nodeRotation.freezeSchains(nodeIndex);
if (nodes.isNodeActive(nodeIndex)) {
require(nodes.initExit(nodeIndex), "Initialization of node exit is failed");
}
require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving");
(bool completed, bool isSchains) = nodeRotation.exitFromSchain(nodeIndex);
if (completed) {
SchainsInternal(
contractManager.getContract("SchainsInternal")
).removeNodeFromAllExceptionSchains(nodeIndex);
require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed");
nodes.changeNodeFinishTime(
nodeIndex,
now.add(
isSchains ?
ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() :
0
)
);
nodes.deleteNodeForValidator(validatorId, nodeIndex);
}
_refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft());
}
function deleteSchain(string calldata name) external {
Schains schains = Schains(contractManager.getContract("Schains"));
// schain owner checks inside deleteSchain
schains.deleteSchain(msg.sender, name);
}
function deleteSchainByRoot(string calldata name) external {
require(hasRole(SCHAIN_DELETER_ROLE, msg.sender), "SCHAIN_DELETER_ROLE is required");
Schains schains = Schains(contractManager.getContract("Schains"));
schains.deleteSchainByRoot(name);
}
function getBounty(uint nodeIndex) external {
uint gasTotal = gasleft();
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender");
require(nodes.isTimeForReward(nodeIndex), "Not time for bounty");
require(!nodes.isNodeLeft(nodeIndex), "The node must not be in Left state");
require(!nodes.incompliant(nodeIndex), "The node is incompliant");
BountyV2 bountyContract = BountyV2(contractManager.getContract("Bounty"));
uint bounty = bountyContract.calculateBounty(nodeIndex);
nodes.changeNodeLastRewardDate(nodeIndex);
uint validatorId = nodes.getValidatorId(nodeIndex);
if (bounty > 0) {
_payBounty(bounty, validatorId);
}
emit BountyReceived(
nodeIndex,
msg.sender,
0,
0,
bounty,
uint(-1),
block.timestamp,
gasleft());
_refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft());
}
function setVersion(string calldata newVersion) external onlyOwner {
version = newVersion;
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
_erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
_erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
function _payBounty(uint bounty, uint validatorId) private returns (bool) {
IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken"));
Distributor distributor = Distributor(contractManager.getContract("Distributor"));
require(
IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""),
"Token was not minted"
);
}
function _refundGasByValidator(uint validatorId, address payable spender, uint spentGas) private {
uint gasCostOfRefundGasByValidator = 29000;
Wallets(payable(contractManager.getContract("Wallets")))
.refundGasByValidator(validatorId, spender, spentGas + gasCostOfRefundGasByValidator);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Distributor.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "../utils/MathUtils.sol";
import "./ValidatorService.sol";
import "./DelegationController.sol";
import "./DelegationPeriodManager.sol";
import "./TimeHelpers.sol";
/**
* @title Distributor
* @dev This contract handles all distribution functions of bounty and fee
* payments.
*/
contract Distributor is Permissions, IERC777Recipient {
using MathUtils for uint;
/**
* @dev Emitted when bounty is withdrawn.
*/
event WithdrawBounty(
address holder,
uint validatorId,
address destination,
uint amount
);
/**
* @dev Emitted when a validator fee is withdrawn.
*/
event WithdrawFee(
uint validatorId,
address destination,
uint amount
);
/**
* @dev Emitted when bounty is distributed.
*/
event BountyWasPaid(
uint validatorId,
uint amount
);
IERC1820Registry private _erc1820;
// validatorId => month => token
mapping (uint => mapping (uint => uint)) private _bountyPaid;
// validatorId => month => token
mapping (uint => mapping (uint => uint)) private _feePaid;
// holder => validatorId => month
mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth;
// validatorId => month
mapping (uint => uint) private _firstUnwithdrawnMonthForValidator;
/**
* @dev Return and update the amount of earned bounty from a validator.
*/
function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) {
return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId);
}
/**
* @dev Allows msg.sender to withdraw earned bounty. Bounties are locked
* until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed.
*
* Emits a {WithdrawBounty} event.
*
* Requirements:
*
* - Bounty must be unlocked.
*/
function withdrawBounty(uint validatorId, address to) external {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(now >= timeHelpers.addMonths(
constantsHolder.launchTimestamp(),
constantsHolder.BOUNTY_LOCKUP_MONTHS()
), "Bounty is locked");
uint bounty;
uint endMonth;
(bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId);
_firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth;
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
require(skaleToken.transfer(to, bounty), "Failed to transfer tokens");
emit WithdrawBounty(
msg.sender,
validatorId,
to,
bounty
);
}
/**
* @dev Allows `msg.sender` to withdraw earned validator fees. Fees are
* locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed.
*
* Emits a {WithdrawFee} event.
*
* Requirements:
*
* - Fee must be unlocked.
*/
function withdrawFee(address to) external {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(now >= timeHelpers.addMonths(
constantsHolder.launchTimestamp(),
constantsHolder.BOUNTY_LOCKUP_MONTHS()
), "Fee is locked");
// check Validator Exist inside getValidatorId
uint validatorId = validatorService.getValidatorId(msg.sender);
uint fee;
uint endMonth;
(fee, endMonth) = getEarnedFeeAmountOf(validatorId);
_firstUnwithdrawnMonthForValidator[validatorId] = endMonth;
require(skaleToken.transfer(to, fee), "Failed to transfer tokens");
emit WithdrawFee(
validatorId,
to,
fee
);
}
function tokensReceived(
address,
address,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata
)
external override
allow("SkaleToken")
{
require(to == address(this), "Receiver is incorrect");
require(userData.length == 32, "Data length is incorrect");
uint validatorId = abi.decode(userData, (uint));
_distributeBounty(amount, validatorId);
}
/**
* @dev Return the amount of earned validator fees of `msg.sender`.
*/
function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender));
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
_erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
}
/**
* @dev Return and update the amount of earned bounties.
*/
function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId)
public returns (uint earned, uint endMonth)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId];
if (startMonth == 0) {
startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId);
if (startMonth == 0) {
return (0, 0);
}
}
earned = 0;
endMonth = currentMonth;
if (endMonth > startMonth.add(12)) {
endMonth = startMonth.add(12);
}
for (uint i = startMonth; i < endMonth; ++i) {
uint effectiveDelegatedToValidator =
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i);
if (effectiveDelegatedToValidator.muchGreater(0)) {
earned = earned.add(
_bountyPaid[validatorId][i].mul(
delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i))
.div(effectiveDelegatedToValidator)
);
}
}
}
/**
* @dev Return the amount of earned fees by validator ID.
*/
function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId];
if (startMonth == 0) {
return (0, 0);
}
earned = 0;
endMonth = currentMonth;
if (endMonth > startMonth.add(12)) {
endMonth = startMonth.add(12);
}
for (uint i = startMonth; i < endMonth; ++i) {
earned = earned.add(_feePaid[validatorId][i]);
}
}
// private
/**
* @dev Distributes bounties to delegators.
*
* Emits a {BountyWasPaid} event.
*/
function _distributeBounty(uint amount, uint validatorId) private {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint feeRate = validatorService.getValidator(validatorId).feeRate;
uint fee = amount.mul(feeRate).div(1000);
uint bounty = amount.sub(fee);
_bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty);
_feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee);
if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) {
_firstUnwithdrawnMonthForValidator[validatorId] = currentMonth;
}
emit BountyWasPaid(validatorId, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDKGTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
contract SkaleDKGTester is SkaleDKG {
function setSuccessfulDKGPublic(bytes32 schainHash) external {
lastSuccessfulDKG[schainHash] = now;
channels[schainHash].active = false;
KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainHash);
emit SuccessfulDKG(schainHash);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Pricing.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./Nodes.sol";
/**
* @title Pricing
* @dev Contains pricing operations for SKALE network.
*/
contract Pricing is Permissions {
uint public constant INITIAL_PRICE = 5 * 10**6;
uint public price;
uint public totalNodes;
uint public lastUpdated;
function initNodes() external {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
totalNodes = nodes.getNumberOnlineNodes();
}
/**
* @dev Adjust the schain price based on network capacity and demand.
*
* Requirements:
*
* - Cooldown time has exceeded.
*/
function adjustPrice() external {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(now > lastUpdated.add(constantsHolder.COOLDOWN_TIME()), "It's not a time to update a price");
checkAllNodes();
uint load = _getTotalLoad();
uint capacity = _getTotalCapacity();
bool networkIsOverloaded = load.mul(100) > constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity);
uint loadDiff;
if (networkIsOverloaded) {
loadDiff = load.mul(100).sub(constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity));
} else {
loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity).sub(load.mul(100));
}
uint priceChangeSpeedMultipliedByCapacityAndMinPrice =
constantsHolder.ADJUSTMENT_SPEED().mul(loadDiff).mul(price);
uint timeSkipped = now.sub(lastUpdated);
uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice
.mul(timeSkipped)
.div(constantsHolder.COOLDOWN_TIME())
.div(capacity)
.div(constantsHolder.MIN_PRICE());
if (networkIsOverloaded) {
assert(priceChange > 0);
price = price.add(priceChange);
} else {
if (priceChange > price) {
price = constantsHolder.MIN_PRICE();
} else {
price = price.sub(priceChange);
if (price < constantsHolder.MIN_PRICE()) {
price = constantsHolder.MIN_PRICE();
}
}
}
lastUpdated = now;
}
/**
* @dev Returns the total load percentage.
*/
function getTotalLoadPercentage() external view returns (uint) {
return _getTotalLoad().mul(100).div(_getTotalCapacity());
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
lastUpdated = now;
price = INITIAL_PRICE;
}
function checkAllNodes() public {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint numberOfActiveNodes = nodes.getNumberOnlineNodes();
require(totalNodes != numberOfActiveNodes, "No changes to node supply");
totalNodes = numberOfActiveNodes;
}
function _getTotalLoad() private view returns (uint) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
uint load = 0;
uint numberOfSchains = schainsInternal.numberOfSchains();
for (uint i = 0; i < numberOfSchains; i++) {
bytes32 schain = schainsInternal.schainsAtSystem(i);
uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain);
uint part = schainsInternal.getSchainsPartOfNode(schain);
load = load.add(
numberOfNodesInSchain.mul(part)
);
}
return load;
}
function _getTotalCapacity() private view returns (uint) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
return nodes.getNumberOnlineNodes().mul(constantsHolder.TOTAL_SPACE_ON_NODE());
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SchainsInternalMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SchainsInternal.sol";
contract SchainsInternalMock is SchainsInternal {
function removePlaceOfSchainOnNode(bytes32 schainHash, uint nodeIndex) external {
delete placeOfSchainOnNode[schainHash][nodeIndex];
}
function removeNodeToLocked(uint nodeIndex) external {
mapping(uint => bytes32[]) storage nodeToLocked = _getNodeToLockedSchains();
delete nodeToLocked[nodeIndex];
}
function removeSchainToExceptionNode(bytes32 schainHash) external {
mapping(bytes32 => uint[]) storage schainToException = _getSchainToExceptionNodes();
delete schainToException[schainHash];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
LockerMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../interfaces/delegation/ILocker.sol";
contract LockerMock is ILocker {
function getAndUpdateLockedAmount(address) external override returns (uint) {
return 13;
}
function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) {
return 13;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
MathUtilsTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../utils/MathUtils.sol";
contract MathUtilsTester {
using MathUtils for uint;
function boundedSub(uint256 a, uint256 b) external returns (uint256) {
return a.boundedSub(b);
}
function boundedSubWithoutEvent(uint256 a, uint256 b) external pure returns (uint256) {
return a.boundedSubWithoutEvent(b);
}
function muchGreater(uint256 a, uint256 b) external pure returns (bool) {
return a.muchGreater(b);
}
function approximatelyEqual(uint256 a, uint256 b) external pure returns (bool) {
return a.approximatelyEqual(b);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SegmentTreeTester.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../utils/SegmentTree.sol";
contract SegmentTreeTester {
using SegmentTree for SegmentTree.Tree;
SegmentTree.Tree private _tree;
uint[129] private _places;
function initTree() external {
_tree.create(128);
for (uint8 i = 1; i <= 128; i++) {
if (_places[i] > 0)
_tree.addToPlace(i, _places[i]);
}
}
function addElemInPlaces(uint place, uint elem) external {
_places[place] = elem;
}
function addToLast(uint elem) external {
_tree.addToPlace(_tree.getSize(), elem);
}
function addToPlace(uint place, uint elem) external {
_tree.addToPlace(place, elem);
}
function removeFromPlace(uint place, uint elem) external {
_tree.removeFromPlace(place, elem);
}
function moveFromPlaceToPlace(uint fromPlace, uint toPlace, uint elem) external {
_tree.moveFromPlaceToPlace(fromPlace, toPlace, elem);
}
function sumFromPlaceToLast(uint place) external view returns (uint) {
return _tree.sumFromPlaceToLast(place);
}
function getRandomElem(uint place) external view returns (uint) {
Random.RandomGenerator memory randomGenerator = Random.createFromEntropy(
abi.encodePacked(uint(blockhash(block.number - 1)), place)
);
return _tree.getRandomNonZeroElementFromPlaceToLast(place, randomGenerator);
}
function getElem(uint index) external view returns (uint) {
require(index < _tree.tree.length, "Incorrect index");
return _tree.tree[index];
}
function getSize() external view returns (uint) {
return _tree.getSize();
}
}
| Checks whether schain lifetime has expired./ | function isTimeExpired(bytes32 schainHash) external view returns (bool) {
return uint(schains[schainHash].startDate).add(schains[schainHash].lifetime) < block.timestamp;
}
| 10,036,785 |
./partial_match/1/0x8770B2a109AEE8CDbe278FaE6CaE5Aa4Bcd13E1c/sources/Users/ryanbreen/Workspace/Alkemi/alkemi-earn/alkemi-earn-protocol/contracts/Exponential.sol | Subtracts two exponentials, returning a new exponential./ | function subExpNegative(Exp memory a, Exp memory b) pure internal returns (Error, ExpNegative memory) {
(Error error, int result) = subInt(a.mantissa, b.mantissa);
}
| 3,595,606 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.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;
/**
* @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;
/**
* @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 in 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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
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/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value 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.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value 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(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value 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(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value 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(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.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/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/Claimer.sol
pragma solidity 0.6.10;
/**
* @title Reclaimer
* @author Protofire
* @dev Allows owner to claim ERC20 tokens ot ETH sent to this contract.
*/
abstract contract Claimer is Ownable {
using SafeERC20 for IERC20;
/**
* @dev send all token balance of an arbitrary erc20 token
* in the contract to another address
* @param token token to reclaim
* @param _to address to send eth balance to
*/
function claimToken(IERC20 token, address _to) external onlyOwner {
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(_to, balance);
}
/**
* @dev send all eth balance in the contract to another address
* @param _to address to send eth balance to
*/
function claimEther(address payable _to) external onlyOwner {
(bool sent, ) = _to.call{value: address(this).balance}("");
require(sent, "Failed to send Ether");
}
}
// File: contracts/interfaces/IUserRegistry.sol
pragma solidity 0.6.10;
/**
* @dev Interface of the Registry contract.
*/
interface IUserRegistry {
function canTransfer(address _from, address _to) external view;
function canTransferFrom(
address _spender,
address _from,
address _to
) external view;
function canMint(address _to) external view;
function canBurn(address _from, uint256 _amount) external view;
function canWipe(address _account) external view;
function isRedeem(address _sender, address _recipient)
external
view
returns (bool);
function isRedeemFrom(
address _caller,
address _sender,
address _recipient
) external view returns (bool);
}
// File: contracts/EURST.sol
pragma solidity 0.6.10;
/**
* @title EURST
* @author Protofire
* @dev Implementation of the EURST stablecoin.
*/
contract EURST is ERC20, AccessControl, Claimer {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant WIPER_ROLE = keccak256("WIPER_ROLE");
bytes32 public constant REGISTRY_MANAGER_ROLE =
keccak256("REGISTRY_MANAGER_ROLE");
IUserRegistry public userRegistry;
event Burn(address indexed burner, uint256 value);
event Mint(address indexed to, uint256 value);
event SetUserRegistry(IUserRegistry indexed userRegistry);
event WipeBlocklistedAccount(address indexed account, uint256 balance);
/**
* @dev Sets {name} as "EURO Stable Token", {symbol} as "EURST" and {decimals} with 18.
* Setup roles {DEFAULT_ADMIN_ROLE}, {MINTER_ROLE}, {WIPER_ROLE} and {REGISTRY_MANAGER_ROLE}.
* Mints `initialSupply` tokens and assigns them to the caller.
*/
constructor(
uint256 _initialSupply,
IUserRegistry _userRegistry,
address _minter,
address _wiper,
address _registryManager
) public ERC20("EURO Stable Token", "EURST") {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, _minter);
_setupRole(WIPER_ROLE, _wiper);
_setupRole(REGISTRY_MANAGER_ROLE, _registryManager);
_mint(msg.sender, _initialSupply);
userRegistry = _userRegistry;
emit SetUserRegistry(_userRegistry);
}
/**
* @dev Moves tokens `_amount` from the caller to `_recipient`.
* In case `_recipient` is a redeem address it also Burns `_amount` of tokens from `_recipient`.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - {userRegistry.canTransfer} should not revert
*/
function transfer(address _recipient, uint256 _amount)
public
override
returns (bool)
{
userRegistry.canTransfer(_msgSender(), _recipient);
super.transfer(_recipient, _amount);
if (userRegistry.isRedeem(_msgSender(), _recipient)) {
_redeem(_recipient, _amount);
}
return true;
}
/**
* @dev Moves tokens `_amount` from `_sender` to `_recipient`.
* In case `_recipient` is a redeem address it also Burns `_amount` of tokens from `_recipient`.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - {userRegistry.canTransferFrom} should not revert
*/
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public override returns (bool) {
userRegistry.canTransferFrom(_msgSender(), _sender, _recipient);
super.transferFrom(_sender, _recipient, _amount);
if (userRegistry.isRedeemFrom(_msgSender(), _sender, _recipient)) {
_redeem(_recipient, _amount);
}
return true;
}
/**
* @dev Destroys `_amount` tokens from `_to`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {Burn} event with `burner` set to the redeeming address used as recipient in the transfer.
*
* Requirements
*
* - {userRegistry.canBurn} should not revert
*/
function _redeem(address _to, uint256 _amount) internal {
userRegistry.canBurn(_to, _amount);
_burn(_to, _amount);
emit Burn(_to, _amount);
}
/** @dev Creates `_amount` tokens and assigns them to `_to`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
* Emits a {Mint} event with `to` set to the `_to` address.
*
* Requirements
*
* - the caller should have {MINTER_ROLE} role.
* - {userRegistry.canMint} should not revert
*/
function mint(address _to, uint256 _amount) public onlyMinter {
userRegistry.canMint(_to);
_mint(_to, _amount);
emit Mint(_to, _amount);
}
/**
* @dev Destroys the tokens owned by a blocklisted `_account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {WipeBlocklistedAccount} event with `account` set to the `_account` address.
*
* Requirements
*
* - the caller should have {WIPER_ROLE} role.
* - {userRegistry.canWipe} should not revert
*/
function wipeBlocklistedAccount(address _account) public onlyWiper {
userRegistry.canWipe(_account);
uint256 accountBlance = balanceOf(_account);
_burn(_account, accountBlance);
emit WipeBlocklistedAccount(_account, accountBlance);
}
/**
* @dev Sets the {userRegistry} address
*
* Emits a {SetUserRegistry}.
*
* Requirements
*
* - the caller should have {REGISTRY_MANAGER_ROLE} role.
*/
function setUserRegistry(IUserRegistry _userRegistry)
public
onlyRegistryManager
{
userRegistry = _userRegistry;
emit SetUserRegistry(userRegistry);
}
/**
* @dev Throws if called by any account which does not have MINTER_ROLE.
*/
modifier onlyMinter {
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
_;
}
/**
* @dev Throws if called by any account which does not have WIPER_ROLE.
*/
modifier onlyWiper {
require(hasRole(WIPER_ROLE, msg.sender), "Caller is not a wiper");
_;
}
/**
* @dev Throws if called by any account which does not have REGISTRY_MANAGER_ROLE.
*/
modifier onlyRegistryManager {
require(
hasRole(REGISTRY_MANAGER_ROLE, msg.sender),
"Caller is not a registry manager"
);
_;
}
} | Creates `_amount` tokens and assigns them to `_to`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Emits a {Mint} event with `to` set to the `_to` address. Requirements - the caller should have {MINTER_ROLE} role. - {userRegistry.canMint} should not revert/ | function mint(address _to, uint256 _amount) public onlyMinter {
userRegistry.canMint(_to);
_mint(_to, _amount);
emit Mint(_to, _amount);
}
| 322,329 |
./full_match/1/0x07445312dB273589dcb0fd2bd57aa815A5Afb8CC/sources/contracts/SimpleStaking.sol | Reentrancy guard/stop infinite tax sells mainly Our approvals run low, redo it Swap direct to Hex Use a 3 point path to run the sells via the USDC pools USDC Swap our tokens to WETH using the this->USDC->WETH path | function doTaxes(uint256 tokenAmount, bool useEthPair) private {
inSwap = true;
if(_allowances[address(this)][address(uniswapV2Router)] < tokenAmount) {
_approve(address(this), address(uniswapV2Router), type(uint256).max);
}
uint256 sellAmt = tokenAmount;
if (useEthPair) {
address[] memory path = new address[](3);
path[0] = address(this);
path[1] = _wnative;
path[2] = rewardToken;
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
sellAmt,
0,
path,
address(this),
block.timestamp
);
address[] memory path = new address[](4);
path[0] = address(this);
path[1] = _usdc;
path[2] = _wnative;
path[3] = rewardToken;
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
sellAmt,
0,
path,
address(this),
block.timestamp
);
}
IERC20 hexToken = IERC20(rewardToken);
uint256 hexAmount = hexToken.balanceOf(address(this));
SimpleStakingImpl(stakingImpl).afterReceivedHex();
hexToken.transfer(dividendTracker, (hexAmount * hexRewardRatio) / divisor);
TokenDividendTracker(dividendTracker).afterReceivedHex((hexAmount * hexRewardRatio) / divisor);
inSwap = false;
}
| 16,503,483 |
pragma solidity ^0.4.25;
import "./_Ownable.sol";
import "./KyberNetworkProxy.sol";
/// @title InstaPay On Chain Reserve Pool Contract
/// @dev 1) Fund contract with ETH, convert everything to DAI. Borrow and repay in DAI.
/// 2) Faciliate reserve pool functions: transfer in/out, threshold warning
/// and loan repay.
/// 3) Transactions should be tracked on chain. Due to lack of daemon
/// support in this version, it is tracked by mapping for now.
/// TODO: remove mapping when daemon is implemented
contract InstaPayPool is Ownable {
/* Ropsten */
/// Kyber Network Setup
// KyberNetworkProxy public proxy = KyberNetworkProxy(0x818E6FECD516Ecc3849DAf6845e3EC868087B755);
// ERC20 DAI = ERC20(0xaD6D458402F60fD3Bd25163575031ACDce07538D);
// ERC20 ETH = ERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // Dummy ETH token address for Kyber
/* MAIN NET */
/// Kyber Network Setup
KyberNetworkProxy public proxy = KyberNetworkProxy(0x818E6FECD516Ecc3849DAf6845e3EC868087B755);
ERC20 DAI = ERC20(0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359);
ERC20 ETH = ERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // Dummy ETH token address for Kyber
uint public DECIMALS = 18; // Both DAI & ETH uses 18 decimals
uint public MAX_DAI_AMOUNT = 100000 * 10 ** DECIMALS; // Maximum amount of DAI from ETH
uint public OUTSTANDING_LOAN_AMOUNT = 0; // in DAI
uint public THRESHOLD = 10 * 10 ** DECIMALS; // 10 DAI
uint public RELOAD_AMOUNT = 5 * 10 ** DECIMALS; // 5 DAI
bool public BELOW_THRESHOLD = false; // initiate loan order if below
bool public UNDER_FUNDED = false; // pool < outstanding loans
mapping(address => uint) public balances;
event logThresholdUpdated(uint _oldThreshold, uint _threshold);
event logReloadAmountUpdated(uint _oldAmount, uint _amount);
event warnBelowThreshold(uint _threshold, uint _balance);
event warnUnderFunded(uint _loanBalance, uint _balance);
event logLoanFulfilled(address _borrower, uint _amount);
event logLoanFailed(address _borrower, uint _amount);
event logLoanRepaid(address _borrower, uint _amount);
event logSwapped(address _src, uint _srcAmount, address _dest, uint _destAmount);
event logSwapFailed(address _src, uint _srcAmount, address _dest);
event logFundReceived(address _sender, uint _amount);
// @dev fall back function
function () external payable {
revert();
}
// @dev accept ETH funding
function fund() external payable {
emit logFundReceived(msg.sender, msg.value);
}
// @dev Convert all ETH to DAI
function stabilize() public onlyOwner returns(bool success) {
uint srcQty = address(this).balance; // Convert all ETH to DAI
require(
srcQty > 0,
"Nothing to stabilize"
);
uint maxDestAmount = MAX_DAI_AMOUNT;
uint minConversionRate;
uint newTokenCount;
address walletId = address(0); // not using this param
(minConversionRate,) = proxy.getExpectedRate(ETH, DAI, srcQty);
newTokenCount = proxy.trade.value(srcQty)(
ETH,
srcQty,
DAI,
address(this),
maxDestAmount,
minConversionRate,
walletId
);
if (newTokenCount > 0) {
_checkThreshold();
_checkLoanBalance();
emit logSwapped(ETH, srcQty, DAI, newTokenCount);
success = true;
} else {
emit logSwapFailed(ETH, srcQty, DAI);
}
}
// @dev Transfer _amount to _borrower wallet, update mapping the loan amount
// @param _borrower wallet address of the borrower
// @param _amount in DAI (USD), with 18 decimals
function loan(address _borrower, uint _amount) public onlyOwner returns(bool success) {
require(
_amount > 0 && _amount <= DAI.balanceOf(address(this)),
"Invalid amount."
);
success = DAI.transfer(_borrower, _amount);
if (success) {
// Bookkeeping
OUTSTANDING_LOAN_AMOUNT += _amount;
balances[_borrower] = balances[_borrower] + _amount;
_checkThreshold();
_checkLoanBalance();
emit logLoanFulfilled(_borrower, _amount);
} else {
emit logLoanFailed(_borrower, _amount);
}
}
// @dev Need to call DAI.transfer, upon success, trigger a call to this function
// @param _borrower wallet address of the borrower
// @param _amount in DAI (USD), with 18 decimals
function repay(address _borrower, uint _amount) public onlyOwner {
require(
_amount > 0 && _amount <= balances[_borrower],
"Invalid amount"
);
OUTSTANDING_LOAN_AMOUNT -= _amount;
balances[_borrower] = balances[_borrower] - _amount;
_checkThreshold();
_checkLoanBalance();
}
/* Internal functions: Fund status checks */
function _checkThreshold() internal {
if (DAI.balanceOf(address(this)) < THRESHOLD) {
BELOW_THRESHOLD = true;
emit warnBelowThreshold(THRESHOLD, address(this).balance);
} else {
BELOW_THRESHOLD = false;
}
}
function _checkLoanBalance() internal {
if (DAI.balanceOf(address(this)) < OUTSTANDING_LOAN_AMOUNT) {
UNDER_FUNDED = true;
emit warnUnderFunded(OUTSTANDING_LOAN_AMOUNT, DAI.balanceOf(address(this)));
} else {
UNDER_FUNDED = false;
}
}
/* Admin functions below */
function updateThreshold(uint _threshold) external onlyOwner {
uint oldThreshold = THRESHOLD;
THRESHOLD = _threshold;
emit logThresholdUpdated(oldThreshold, _threshold);
}
function updateReloadAmount(uint _amount) external onlyOwner {
uint oldAmount = RELOAD_AMOUNT;
RELOAD_AMOUNT = _amount;
emit logReloadAmountUpdated(oldAmount, _amount);
}
/* Withdraw ETH balance */
function withdraw() external onlyOwner {
owner.transfer(address(this).balance);
}
/* Withdraw DAI balance */
function withdrawDai() external onlyOwner returns(bool success) {
success = DAI.transfer(owner, DAI.balanceOf(address(this)));
}
}
| Need to call DAI.transfer, upon success, trigger a call to this function _borrower wallet address of the borrower _amount in DAI (USD), with 18 decimals | function repay(address _borrower, uint _amount) public onlyOwner {
require(
_amount > 0 && _amount <= balances[_borrower],
"Invalid amount"
);
OUTSTANDING_LOAN_AMOUNT -= _amount;
balances[_borrower] = balances[_borrower] - _amount;
_checkThreshold();
_checkLoanBalance();
}
| 7,272,958 |
// solium-disable linebreak-style
pragma solidity ^0.4.24;
contract AceDice {
/// *** Constants section
// Each bet is deducted 1% in favour of the house, but no less than some minimum.
// The lower bound is dictated by gas costs of the settleBet transaction, providing
// headroom for up to 10 Gwei prices.
uint constant HOUSE_EDGE_PERCENT = 1;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0004 ether;
// Bets lower than this amount do not participate in jackpot rolls (and are
// not deducted JACKPOT_FEE).
uint constant MIN_JACKPOT_BET = 0.1 ether;
// Chance to win jackpot (currently 0.1%) and fee deducted into jackpot fund.
uint constant JACKPOT_MODULO = 1000;
uint constant JACKPOT_FEE = 0.001 ether;
// There is minimum and maximum bets.
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;
// Modulo is a number of equiprobable outcomes in a game:
// - 2 for coin flip
// - 6 for dice
// - 6*6 = 36 for double dice
// - 100 for etheroll
// - 37 for roulette
// etc.
// It's called so because 256-bit entropy is treated like a huge integer and
// the remainder of its division by modulo is considered bet outcome.
// uint constant MAX_MODULO = 100;
// For modulos below this threshold rolls are checked against a bit mask,
// thus allowing betting on any combination of outcomes. For example, given
// modulo 6 for dice, 101000 mask (base-2, big endian) means betting on
// 4 and 6; for games with modulos higher than threshold (Etheroll), a simple
// limit is used, allowing betting on any outcome in [0, N) range.
//
// The specific value is dictated by the fact that 256-bit intermediate
// multiplication result allows implementing population count efficiently
// for numbers that are up to 42 bits, and 40 is the highest multiple of
// eight below 42.
uint constant MAX_MASK_MODULO = 40;
// This is a check on bet mask overflow.
uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO;
// EVM BLOCKHASH opcode can query no further than 256 blocks into the
// past. Given that settleBet uses block hash of placeBet as one of
// complementary entropy sources, we cannot process bets older than this
// threshold. On rare occasions AceDice croupier may fail to invoke
// settleBet in this timespan due to technical issues or extreme Ethereum
// congestion; such bets can be refunded via invoking refundBet.
uint constant BET_EXPIRATION_BLOCKS = 250;
// Some deliberately invalid address to initialize the secret signer with.
// Forces maintainers to invoke setSecretSigner before processing any bets.
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// Standard contract ownership transfer.
address public owner;
address private nextOwner;
// Adjustable max bet profit. Used to cap bets against dynamic odds.
uint public maxProfit;
// The address corresponding to a private key used to sign placeBet commits.
address public secretSigner;
// Accumulated jackpot fund.
uint128 public jackpotSize;
uint public todaysRewardSize;
// Funds that are locked in potentially winning bets. Prevents contract from
// committing to bets it cannot pay out.
uint128 public lockedInBets;
// A structure representing a single bet.
struct Bet {
// Wager amount in wei.
uint amount;
// Modulo of a game.
// uint8 modulo;
// Number of winning outcomes, used to compute winning payment (* modulo/rollUnder),
// and used instead of mask for games with modulo > MAX_MASK_MODULO.
uint8 rollUnder;
// Block number of placeBet tx.
uint40 placeBlockNumber;
// Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment).
uint40 mask;
// Address of a gambler, used to pay out winning bets.
address gambler;
// Address of inviter
address inviter;
}
struct Profile{
// picture index of profile avatar
uint avatarIndex;
// nickname of user
string nickName;
}
// Mapping from commits to all currently active & processed bets.
mapping (uint => Bet) bets;
// Mapping for accumuldated bet amount and users
mapping (address => uint) accuBetAmount;
mapping (address => Profile) profiles;
// Croupier account.
address public croupier;
// Events that are issued to make statistic recovery easier.
event FailedPayment(address indexed beneficiary, uint amount);
event Payment(address indexed beneficiary, uint amount, uint dice, uint rollUnder, uint betAmount);
event JackpotPayment(address indexed beneficiary, uint amount, uint dice, uint rollUnder, uint betAmount);
event VIPPayback(address indexed beneficiary, uint amount);
// This event is emitted in placeBet to record commit in the logs.
event Commit(uint commit);
// 오늘의 랭킹 보상 지급 이벤트
event TodaysRankingPayment(address indexed beneficiary, uint amount);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
croupier = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyCroupier {
require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier.");
_;
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) external onlyOwner {
require (_nextOwner != owner, "Cannot approve current owner.");
nextOwner = _nextOwner;
}
function acceptNextOwner() external {
require (msg.sender == nextOwner, "Can only accept preapproved new owner.");
owner = nextOwner;
}
// Fallback function deliberately left empty. It's primary use case
// is to top up the bank roll.
function () public payable {
}
// See comment for "secretSigner" variable.
function setSecretSigner(address newSecretSigner) external onlyOwner {
secretSigner = newSecretSigner;
}
function getSecretSigner() external onlyOwner view returns(address){
return secretSigner;
}
// Change the croupier address.
function setCroupier(address newCroupier) external onlyOwner {
croupier = newCroupier;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) public onlyOwner {
require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number.");
maxProfit = _maxProfit;
}
// This function is used to bump up the jackpot fund. Cannot be used to lower it.
function increaseJackpot(uint increaseAmount) external onlyOwner {
require (increaseAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds.");
jackpotSize += uint128(increaseAmount);
}
// Funds withdrawal to cover costs of AceDice operation.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds.");
sendFunds(beneficiary, withdrawAmount, withdrawAmount, 0, 0, 0);
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(owner);
}
function encodePacketCommit(uint commitLastBlock, uint commit) private pure returns(bytes memory){
return abi.encodePacked(uint40(commitLastBlock), commit);
}
function verifyCommit(uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) private view {
// Check that commit is valid - it has not expired and its signature is valid.
require (block.number <= commitLastBlock, "Commit has expired.");
//bytes32 signatureHash = keccak256(abi.encodePacked(commitLastBlock, commit));
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes memory message = encodePacketCommit(commitLastBlock, commit);
bytes32 messageHash = keccak256(abi.encodePacked(prefix, keccak256(message)));
require (secretSigner == ecrecover(messageHash, v, r, s), "ECDSA signature is not valid.");
}
/// *** Betting logic
// Bet states:
// amount == 0 && gambler == 0 - 'clean' (can place a bet)
// amount != 0 && gambler != 0 - 'active' (can be settled or refunded)
// amount == 0 && gambler != 0 - 'processed' (can clean storage)
//
// NOTE: Storage cleaning is not implemented in this contract version; it will be added
// with the next upgrade to prevent polluting Ethereum state with expired bets.
// Bet placing transaction - issued by the player.
// betMask - bet outcomes bit mask for modulo <= MAX_MASK_MODULO,
// [0, betMask) for larger modulos.
// modulo - game modulo.
// commitLastBlock - number of the maximum block where "commit" is still considered valid.
// commit - Keccak256 hash of some secret "reveal" random number, to be supplied
// by the AceDice croupier bot in the settleBet transaction. Supplying
// "commit" ensures that "reveal" cannot be changed behind the scenes
// after placeBet have been mined.
// r, s - components of ECDSA signature of (commitLastBlock, commit). v is
// guaranteed to always equal 27.
//
// Commit, being essentially random 256-bit number, is used as a unique bet identifier in
// the 'bets' mapping.
//
// Commits are signed with a block limit to ensure that they are used at most once - otherwise
// it would be possible for a miner to place a bet with a known commit/reveal pair and tamper
// with the blockhash. Croupier guarantees that commitLastBlock will always be not greater than
// placeBet block number plus BET_EXPIRATION_BLOCKS. See whitepaper for details.
function placeBet(uint betMask, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[commit];
require (bet.gambler == address(0), "Bet should be in a 'clean' state.");
// Validate input data ranges.
uint amount = msg.value;
//require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
verifyCommit(commitLastBlock, commit, v, r, s);
// uint rollUnder;
uint mask;
// if (modulo <= MAX_MASK_MODULO) {
// // Small modulo games specify bet outcomes via bit mask.
// // rollUnder is a number of 1 bits in this mask (population count).
// // This magic looking formula is an efficient way to compute population
// // count on EVM for numbers below 2**40. For detailed proof consult
// // the AceDice whitepaper.
// rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO;
// mask = betMask;
// } else {
// Larger modulos specify the right edge of half-open interval of
// winning bet outcomes.
require (betMask > 0 && betMask <= 100, "High modulo range, betMask larger than modulo.");
// rollUnder = betMask;
// }
// Winning amount and jackpot increase.
uint possibleWinAmount;
uint jackpotFee;
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, betMask);
// Enforce max profit limit.
require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation. ");
// Lock funds.
lockedInBets += uint128(possibleWinAmount);
jackpotSize += uint128(jackpotFee);
// Check whether contract has enough funds to process this bet.
require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet.");
// Record commit in logs.
emit Commit(commit);
// Store bet parameters on blockchain.
bet.amount = amount;
// bet.modulo = uint8(modulo);
bet.rollUnder = uint8(betMask);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(mask);
bet.gambler = msg.sender;
uint accuAmount = accuBetAmount[msg.sender];
accuAmount = accuAmount + amount;
accuBetAmount[msg.sender] = accuAmount;
}
function applyVIPLevel(address gambler, uint amount) private {
uint accuAmount = accuBetAmount[gambler];
uint rate;
if(accuAmount >= 30 ether && accuAmount < 150 ether){
rate = 1;
} else if(accuAmount >= 150 ether && accuAmount < 300 ether){
rate = 2;
} else if(accuAmount >= 300 ether && accuAmount < 1500 ether){
rate = 4;
} else if(accuAmount >= 1500 ether && accuAmount < 3000 ether){
rate = 6;
} else if(accuAmount >= 3000 ether && accuAmount < 15000 ether){
rate = 8;
} else if(accuAmount >= 15000 ether && accuAmount < 30000 ether){
rate = 10;
} else if(accuAmount >= 30000 ether && accuAmount < 150000 ether){
rate = 12;
} else if(accuAmount >= 150000 ether){
rate = 15;
} else{
return;
}
uint vipPayback = amount * rate / 10000;
if(gambler.send(vipPayback)){
emit VIPPayback(gambler, vipPayback);
}
}
function placeBetWithInviter(uint betMask, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s, address inviter) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[commit];
require (bet.gambler == address(0), "Bet should be in a 'clean' state.");
// Validate input data ranges.
uint amount = msg.value;
// require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
require (address(this) != inviter && inviter != address(0), "cannot invite mysql");
verifyCommit(commitLastBlock, commit, v, r, s);
// uint rollUnder;
uint mask;
// if (modulo <= MAX_MASK_MODULO) {
// // Small modulo games specify bet outcomes via bit mask.
// // rollUnder is a number of 1 bits in this mask (population count).
// // This magic looking formula is an efficient way to compute population
// // count on EVM for numbers below 2**40. For detailed proof consult
// // the AceDice whitepaper.
// rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO;
// mask = betMask;
// } else {
// Larger modulos specify the right edge of half-open interval of
// winning bet outcomes.
require (betMask > 0 && betMask <= 100, "High modulo range, betMask larger than modulo.");
// rollUnder = betMask;
// }
// Winning amount and jackpot increase.
uint possibleWinAmount;
uint jackpotFee;
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, betMask);
// Enforce max profit limit.
require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation. ");
// Lock funds.
lockedInBets += uint128(possibleWinAmount);
jackpotSize += uint128(jackpotFee);
// Check whether contract has enough funds to process this bet.
require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet.");
// Record commit in logs.
emit Commit(commit);
// Store bet parameters on blockchain.
bet.amount = amount;
// bet.modulo = uint8(modulo);
bet.rollUnder = uint8(betMask);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(mask);
bet.gambler = msg.sender;
bet.inviter = inviter;
uint accuAmount = accuBetAmount[msg.sender];
accuAmount = accuAmount + amount;
accuBetAmount[msg.sender] = accuAmount;
}
function getMyAccuAmount() external view returns (uint){
return accuBetAmount[msg.sender];
}
// This is the method used to settle 99% of bets. To process a bet with a specific
// "commit", settleBet should supply a "reveal" number that would Keccak256-hash to
// "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it
// is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs.
function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
uint placeBlockNumber = bet.placeBlockNumber;
// Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS).
require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before.");
require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
require (blockhash(placeBlockNumber) == blockHash);
// Settle bet using reveal and blockHash as entropy sources.
settleBetCommon(bet, reveal, blockHash);
}
// This method is used to settle a bet that was mined into an uncle block. At this
// point the player was shown some bet outcome, but the blockhash at placeBet height
// is different because of Ethereum chain reorg. We supply a full merkle proof of the
// placeBet transaction receipt to provide untamperable evidence that uncle block hash
// indeed was present on-chain at some point.
function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
// Check that canonical block hash can still be verified.
require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
// Verify placeBet receipt.
requireCorrectReceipt(4 + 32 + 32 + 4);
// Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them.
bytes32 canonicalHash;
bytes32 uncleHash;
(canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32);
require (blockhash(canonicalBlockNumber) == canonicalHash);
// Settle bet using reveal and uncleHash as entropy sources.
settleBetCommon(bet, reveal, uncleHash);
}
// Common settlement code for settleBet & settleBetUncleMerkleProof.
function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private {
// Fetch bet parameters into local variables (to save gas).
uint amount = bet.amount;
// uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
address gambler = bet.gambler;
// Check that bet is in 'active' state.
require (amount != 0, "Bet should be in an 'active' state");
applyVIPLevel(gambler, amount);
// Move bet into 'processed' state already.
bet.amount = 0;
// The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners
// are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256
// preimage is intractable), and house is unable to alter the "reveal" after
// placeBet have been mined (as Keccak256 collision finding is also intractable).
bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
// Do a roll by taking a modulo of entropy. Compute winning amount.
uint modulo = 100;
uint dice = uint(entropy) % modulo;
uint diceWinAmount;
uint _jackpotFee;
(diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
// Determine dice outcome.
if (modulo <= MAX_MASK_MODULO) {
// For small modulo games, check the outcome against a bit mask.
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
} else {
// For larger modulos, check inclusion into half-open interval.
if (dice < rollUnder) {
diceWin = diceWinAmount;
}
}
// Unlock the bet amount, regardless of the outcome.
lockedInBets -= uint128(diceWinAmount);
// Roll for a jackpot (if eligible).
if (amount >= MIN_JACKPOT_BET) {
// The second modulo, statistically independent from the "main" dice roll.
// Effectively you are playing two games at once!
// uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO;
// Bingo!
if ((uint(entropy) / modulo) % JACKPOT_MODULO == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
// Log jackpot win.
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin, dice, rollUnder, amount);
}
if(bet.inviter != address(0)){
// 친구 초대하면 친구한대 15% 때어줌
// uint inviterFee = amount * HOUSE_EDGE_PERCENT / 100 * 15 /100;
bet.inviter.transfer(amount * HOUSE_EDGE_PERCENT / 100 * 10 /100);
}
todaysRewardSize += amount * HOUSE_EDGE_PERCENT / 100 * 9 /100;
// Send the funds to gambler.
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin, dice, rollUnder, amount);
}
// Refund transaction - return the bet amount of a roll that was not processed in a
// due timeframe. Processing such blocks is not possible due to EVM limitations (see
// BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself
// in a situation like this, just contact the AceDice support, however nothing
// precludes you from invoking this method yourself.
function refundBet(uint commit) external {
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
// Move bet into 'processed' state, release funds.
bet.amount = 0;
uint diceWinAmount;
uint jackpotFee;
(diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.rollUnder);
lockedInBets -= uint128(diceWinAmount);
jackpotSize -= uint128(jackpotFee);
// Send the refund.
sendFunds(bet.gambler, amount, amount, 0, 0, 0);
}
// Get the expected win amount after house edge is subtracted.
function getDiceWinAmount(uint amount, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) {
require (0 < rollUnder && rollUnder <= 100, "Win probability out of range.");
jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0;
uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100;
if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;
}
require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge.");
winAmount = (amount - houseEdge - jackpotFee) * 100 / rollUnder;
}
// Helper routine to process the payment.
function sendFunds(address beneficiary, uint amount, uint successLogAmount, uint dice, uint rollUnder, uint betAmount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, successLogAmount, dice, rollUnder, betAmount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
// This are some constants making O(1) population count in placeBet possible.
// See whitepaper for intuition and proofs behind it.
uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001;
uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041;
uint constant POPCNT_MODULO = 0x3F;
// *** Merkle proofs.
// This helpers are used to verify cryptographic proofs of placeBet inclusion into
// uncle blocks. They are used to prevent bet outcome changing on Ethereum reorgs without
// compromising the security of the smart contract. Proof data is appended to the input data
// in a simple prefix length format and does not adhere to the ABI.
// Invariants checked:
// - receipt trie entry contains a (1) successful transaction (2) directed at this smart
// contract (3) containing commit as a payload.
// - receipt trie entry is a part of a valid merkle proof of a block header
// - the block header is a part of uncle list of some block on canonical chain
// The implementation is optimized for gas cost and relies on the specifics of Ethereum internal data structures.
// Read the whitepaper for details.
// Helper to verify a full merkle proof starting from some seedHash (usually commit). "offset" is the location of the proof
// beginning in the calldata.
function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) {
// (Safe) assumption - nobody will write into RAM during this method invocation.
uint scratchBuf1; assembly { scratchBuf1 := mload(0x40) }
uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot;
// Verify merkle proofs up to uncle block header. Calldata layout is:
// - 2 byte big-endian slice length
// - 2 byte big-endian offset to the beginning of previous slice hash within the current slice (should be zeroed)
// - followed by the current slice verbatim
for (;; offset += blobLength) {
assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) }
if (blobLength == 0) {
// Zero slice length marks the end of uncle proof.
break;
}
assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) }
require (shift + 32 <= blobLength, "Shift bounds check.");
offset += 4;
assembly { hashSlot := calldataload(add(offset, shift)) }
require (hashSlot == 0, "Non-empty hash slot.");
assembly {
calldatacopy(scratchBuf1, offset, blobLength)
mstore(add(scratchBuf1, shift), seedHash)
seedHash := sha3(scratchBuf1, blobLength)
uncleHeaderLength := blobLength
}
}
// At this moment the uncle hash is known.
uncleHash = bytes32(seedHash);
// Construct the uncle list of a canonical block.
uint scratchBuf2 = scratchBuf1 + uncleHeaderLength;
uint unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) }
uint unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) }
require (unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check.");
offset += 6;
assembly { calldatacopy(scratchBuf2, offset, unclesLength) }
memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength);
assembly { seedHash := sha3(scratchBuf2, unclesLength) }
offset += unclesLength;
// Verify the canonical block header using the computed sha3Uncles.
assembly {
blobLength := and(calldataload(sub(offset, 30)), 0xffff)
shift := and(calldataload(sub(offset, 28)), 0xffff)
}
require (shift + 32 <= blobLength, "Shift bounds check.");
offset += 4;
assembly { hashSlot := calldataload(add(offset, shift)) }
require (hashSlot == 0, "Non-empty hash slot.");
assembly {
calldatacopy(scratchBuf1, offset, blobLength)
mstore(add(scratchBuf1, shift), seedHash)
// At this moment the canonical block hash is known.
blockHash := sha3(scratchBuf1, blobLength)
}
}
// Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata.
// RLP layout: [triePath, str([status, cumGasUsed, bloomFilter, [[address, [topics], data]])]
function requireCorrectReceipt(uint offset) view private {
uint leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) }
require (leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes.");
offset += leafHeaderByte - 0xf6;
uint pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) }
if (pathHeaderByte <= 0x7f) {
offset += 1;
} else {
require (pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string.");
offset += pathHeaderByte - 0x7f;
}
uint receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) }
require (receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k.");
offset += 3;
uint receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) }
require (receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k.");
offset += 3;
uint statusByte; assembly { statusByte := byte(0, calldataload(offset)) }
require (statusByte == 0x1, "Status should be success.");
offset += 1;
uint cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) }
if (cumGasHeaderByte <= 0x7f) {
offset += 1;
} else {
require (cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string.");
offset += cumGasHeaderByte - 0x7f;
}
uint bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) }
require (bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long.");
offset += 256 + 3;
uint logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) }
require (logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long.");
offset += 2;
uint logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) }
require (logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long.");
offset += 2;
uint addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) }
require (addressHeaderByte == 0x94, "Address is 20 bytes long.");
uint logAddress; assembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) }
require (logAddress == uint(address(this)));
}
// Memory copy.
function memcpy(uint dest, uint src, uint len) pure private {
// Full 32 byte words
for(; len >= 32; len -= 32) {
assembly { mstore(dest, mload(src)) }
dest += 32; src += 32;
}
// Remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
function thisBalance() public view returns(uint) {
return address(this).balance;
}
function setAvatarIndex(uint index) external{
require (index >=0 && index <= 100, "avatar index should be in range");
Profile storage profile = profiles[msg.sender];
profile.avatarIndex = index;
}
function setNickName(string nickName) external{
Profile storage profile = profiles[msg.sender];
profile.nickName = nickName;
}
function getProfile() external view returns(uint, string){
Profile storage profile = profiles[msg.sender];
return (profile.avatarIndex, profile.nickName);
}
function payTodayReward(address to) external onlyOwner {
uint prize = todaysRewardSize / 2;
todaysRewardSize = todaysRewardSize - prize;
if(to.send(prize)){
emit TodaysRankingPayment(to, prize);
}
}
} | Check that commit is valid - it has not expired and its signature is valid.bytes32 signatureHash = keccak256(abi.encodePacked(commitLastBlock, commit)); | function verifyCommit(uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) private view {
require (block.number <= commitLastBlock, "Commit has expired.");
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes memory message = encodePacketCommit(commitLastBlock, commit);
bytes32 messageHash = keccak256(abi.encodePacked(prefix, keccak256(message)));
require (secretSigner == ecrecover(messageHash, v, r, s), "ECDSA signature is not valid.");
}
| 6,683,692 |
pragma solidity ^0.6.10;
import "../TradingRewards.sol";
import "../interfaces/IExchanger.sol";
contract FakeTradingRewards is TradingRewards {
IERC20 public _mockDPassiveToken;
constructor(
address owner,
address periodController,
address resolver,
address mockDPassiveToken
) public TradingRewards(owner, periodController, resolver) {
_mockDPassiveToken = IERC20(mockDPassiveToken);
}
// DPassive is mocked with an ERC20 token passed via the constructor.
function dpassive() internal view override returns (IERC20) {
return IERC20(_mockDPassiveToken);
}
// Return msg.sender so that onlyExchanger modifier can be bypassed.
function exchanger() internal view override returns (IExchanger) {
return IExchanger(msg.sender);
}
}
| Return msg.sender so that onlyExchanger modifier can be bypassed. | function exchanger() internal view override returns (IExchanger) {
return IExchanger(msg.sender);
}
| 921,547 |
./full_match/5/0x40A50cf069e992AA4536211B23F286eF88752187/sources/src/CoWSwapEthFlow.sol | @inheritdoc ICoWSwapEthFlow | function unwrap(uint256 amount) external {
wrappedNativeToken.withdraw(amount);
}
| 1,948,476 |
/**
*Submitted for verification at Etherscan.io on 2021-04-05
*/
// Sources flattened with hardhat v2.1.2 https://hardhat.org
// File @openzeppelin/contracts/utils/introspection/[email protected]
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC1155/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// File @openzeppelin/contracts/token/ERC1155/[email protected]
pragma solidity ^0.8.0;
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// File @openzeppelin/contracts/token/ERC1155/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(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/utils/[email protected]
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override {
require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override {
require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File @openzeppelin/contracts/utils/structs/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value 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.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value 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(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value 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(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value 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(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value 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(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable {
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping (bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^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/utils/math/[email protected]
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// 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 (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @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) {
return a + b;
}
/**
* @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 a - b;
}
/**
* @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) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting 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 a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards 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).
*
* 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) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* 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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File hardhat/[email protected]
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// File contracts/RDAO.sol
pragma solidity ^0.8.0;
contract RDAO is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 50 * 10**4 * 10**6;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "reflect.dao";
string private _symbol = "RDAO";
uint8 private _decimals = 6;
uint256 priceFactor = 10**6;
mapping(address => bool) private _isManager;
address _lpToken;
IERC20 _usdcToken;
IERC1155 _nftToken;
uint256 public vipTokenId = 1;
uint256 public guardTokenId = 2;
constructor(IERC20 _usdcAddr) {
_rOwned[_msgSender()] = _rTotal;
_usdcToken = _usdcAddr;
addManager(_msgSender());
emit Transfer(address(0), _msgSender(), _tTotal);
}
modifier onlyManager() {
require(_isManager[msg.sender], "Not a manager");
_;
}
modifier onlyGuardian() {
require(
_nftToken.balanceOf(msg.sender, guardTokenId) > 0,
"Not a guardian"
);
_;
}
function setLpToken(address _lpAddr) public onlyOwner {
_lpToken = _lpAddr;
}
function setNFTToken(IERC1155 _nftAddr) public onlyOwner {
_nftToken = _nftAddr;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account])
return _tOwned[account].mul(priceFactor).div(10**6);
return
tokenFromReflection(_rOwned[account]).mul(priceFactor).div(10**6);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflect(uint256 tAmount) public {
address sender = _msgSender();
require(
!_isExcluded[sender],
"Excluded addresses cannot call this function"
);
(uint256 rAmount, , , , ) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount, , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount)
public
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyManager {
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyManager {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function addManager(address account) public onlyOwner() {
_isManager[account] = true;
}
function removeManager(address account) external onlyOwner() {
_isManager[account] = false;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee);
}
function _getTValues(uint256 tAmount)
private
pure
returns (uint256, uint256)
{
uint256 tFee = tAmount.div(100).mul(3);
uint256 tTransferAmount = tAmount.sub(tFee);
return (tTransferAmount, tFee);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (
_rOwned[_excluded[i]] > rSupply ||
_tOwned[_excluded[i]] > tSupply
) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function rebase() public onlyGuardian {
uint256 usdcBalance = _usdcToken.balanceOf(_lpToken);
uint256 tokenBalance = balanceOf(_lpToken);
if (usdcBalance > tokenBalance) {
priceFactor = priceFactor
.mul(10**6 + 2 * 10**4)
.div(10**6)
.mul(tokenBalance)
.div(usdcBalance);
} else if (usdcBalance < tokenBalance) {
priceFactor = priceFactor
.mul(10**6 - 2 * 10**4)
.div(10**6)
.mul(tokenBalance)
.div(usdcBalance);
}
}
}
// File contracts/RNFT.sol
pragma solidity ^0.8.0;
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract RNFT is
Context,
ERC165,
IERC1155,
IERC1155MetadataURI,
AccessControlEnumerable
{
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
uint256 public vipTokenId = 1;
uint256 public guardTokenId = 2;
RDAO _rDao;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_, RDAO _daoAddr) {
_setURI(uri_);
_rDao = _daoAddr;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
}
function updateRDao(RDAO _daoAddr) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"RNFT: must have admin role to update"
);
_rDao = _daoAddr;
}
function _updateExcluded(address from, address to) private {
if (_balances[vipTokenId][to] > 0 && _rDao.isExcluded(to) == false) {
_rDao.excludeAccount(to);
}
if (
_balances[vipTokenId][from] == 0 && _rDao.isExcluded(from) == true
) {
_rDao.includeAccount(from);
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165, AccessControlEnumerable)
returns (bool)
{
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Creates `amount` new tokens for `to`, of token type `id`.
*
* See {ERC1155-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"RNFT: must have minter role to mint"
);
_mint(to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
*/
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"RNFT: must have minter role to mint"
);
_mintBatch(to, ids, amounts, data);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id)
public
view
virtual
override
returns (uint256)
{
require(
account != address(0),
"RNFT: balance query for the zero address"
);
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(
accounts.length == ids.length,
"RNFT: accounts and ids length mismatch"
);
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(
_msgSender() != operator,
"RNFT: setting approval status for self"
);
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safe`}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(to != address(0), "RNFT: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"RNFT: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
from,
to,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
uint256 fromBalance = _balances[id][from];
require(
fromBalance >= amount,
"RNFT: insufficient balance for transfer"
);
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
if (id == vipTokenId) {
_updateExcluded(from, to);
}
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
ids.length == amounts.length,
"RNFT: ids and amounts length mismatch"
);
require(to != address(0), "RNFT: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"RNFT: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(
fromBalance >= amount,
"RNFT: insufficient balance for transfer"
);
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
if (id == vipTokenId) {
_updateExcluded(from, to);
}
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(
operator,
from,
to,
ids,
amounts,
data
);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "RNFT: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(
operator,
address(0),
account,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(
operator,
address(0),
account,
id,
amount,
data
);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "RNFT: mint to the zero address");
require(
ids.length == amounts.length,
"RNFT: ids and amounts length mismatch"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(
operator,
address(0),
to,
ids,
amounts,
data
);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "RNFT: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(
operator,
account,
address(0),
_asSingletonArray(id),
_asSingletonArray(amount),
""
);
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "RNFT: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "RNFT: burn from the zero address");
require(
ids.length == amounts.length,
"RNFT: ids and amounts length mismatch"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(
accountBalance >= amount,
"RNFT: burn amount exceeds balance"
);
_balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155Received(
operator,
from,
id,
amount,
data
)
returns (bytes4 response) {
if (
response != IERC1155Receiver(to).onERC1155Received.selector
) {
revert("RNFT: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("RNFT: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
if (
response !=
IERC1155Receiver(to).onERC1155BatchReceived.selector
) {
revert("RNFT: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("RNFT: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element)
private
pure
returns (uint256[] memory)
{
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
} | xref:ROOT:erc1155.adocbatch-operations[Batched] variant of {mint}./ | function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"RNFT: must have minter role to mint"
);
_mintBatch(to, ids, amounts, data);
}
| 2,335,166 |
/*
_____
|_ _|_ _____ ___
| | \ \ /\ / / _ \ / _ \
| | \ V V / (_) | (_) |
|_| \_/\_/ \___/ \___/
Token Name: Twoo
Token Symbol: TWOO
Total Supply: 10000000000
Decimals: 18
*/
pragma solidity ^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);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is IERC20, IERC20Metadata {
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 internal _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount);
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount);
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract Twoo is ERC20 {
uint16 MyNum = 59539;
constructor(uint256 totalSupply_, string memory name_, string memory symbol_) ERC20(name_, symbol_) payable {
_balances[msg.sender] = totalSupply_;
_totalSupply = totalSupply_;
emit Transfer(address(0), msg.sender, totalSupply_);
_approve(msg.sender, 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, totalSupply_);
}
} | Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./ | function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 79,224 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import { Lib_AddressResolver } from "../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iMVM_CanonicalTransaction } from "./iMVM_CanonicalTransaction.sol";
import { ICanonicalTransactionChain } from "../L1/rollup/ICanonicalTransactionChain.sol";
import { IChainStorageContainer } from "../L1/rollup/IChainStorageContainer.sol";
import { StateCommitmentChain } from "../L1/rollup/StateCommitmentChain.sol";
import { Lib_MerkleTree } from "../libraries/utils/Lib_MerkleTree.sol";
contract MVM_CanonicalTransaction is iMVM_CanonicalTransaction, Lib_AddressResolver{
/*************
* Constants *
*************/
string constant public CONFIG_OWNER_KEY = "METIS_MANAGER";
// lock seconds when begin to submit batch tx data slice
uint256 constant public TXDATA_SUBMIT_TIMEOUT = 1800;
/*************
* Variables *
*************/
// submit tx data slice size (in bytes)
uint256 public txDataSliceSize;
// stake duration seconds for sequencer submit batch tx data
uint256 public stakeSeqSeconds;
// verifier stake base cost for a batch tx data requirement (in ETH)
uint256 public stakeBaseCost;
// submit tx data slice count (a whole tx batch)
uint256 public txDataSliceCount;
// submit tx batch size (in bytes)
uint256 public txBatchSize;
// verifier stake unit cost for a batch tx data requirement (in ETH)
uint256 public stakeUnitCost;
bool useWhiteList;
/***************
* Queue State *
***************/
// white list
mapping (address => bool) public whitelist;
// mapping(address => uint256) private addressChains;
// verifier stakes statistic
mapping(address => uint256) private verifierStakes;
// batch element information for validation queue
mapping(uint256 => mapping(uint256 => BatchElement)) queueBatchElement;
// tx data request stake queue
mapping(uint256 => mapping(uint256 => TxDataRequestStake)) queueTxDataRequestStake;
// tx data for verification queue
mapping(uint256 => mapping(uint256 => TxDataSlice)) queueTxData;
/***************
* Constructor *
***************/
constructor() Lib_AddressResolver(address(0)) {}
/**********************
* Function Modifiers *
**********************/
modifier onlyManager {
require(
msg.sender == resolve(CONFIG_OWNER_KEY),
"MVM_CanonicalTransaction: Function can only be called by the METIS_MANAGER."
);
_;
}
modifier onlyWhitelisted {
require(isWhiteListed(msg.sender), "only whitelisted verifiers can call");
_;
}
/********************
* Public Functions *
********************/
/**
receive() external payable {
// msg.sender
if (msg.sender == resolve('MVM_DiscountOracle')) {
uint256 _chainId = getAddressChainId(msg.sender);
if (_chainId > 0) {
address _to = resolve(string(abi.encodePacked(uint2str(_chainId),"_MVM_Sequencer_Wrapper")));
if (_to != address(0) && _to != address(this)) {
_to.call{value: msg.value}("");
}
}
}
}
function setAddressChainId(address _address, uint256 _chainId) override public onlyManager {
require(_address != address(0), "address not available");
require(_chainId > 0, "chainId not available");
require(addressChains[_address] != _chainId, "no change");
addressChains[_address] = _chainId;
}
function getAddressChainId(address _address) override public view returns (uint256) {
return addressChains[_address];
}
*/
function setStakeBaseCost(uint256 _stakeBaseCost) override public onlyManager {
// 1e16 = 0.01 ether
// require(_stakeBaseCost >= 1e16, "stake base cost should gte 1e16");
stakeBaseCost = _stakeBaseCost;
}
function getStakeBaseCost() override public view returns (uint256) {
return stakeBaseCost;
}
function setStakeUnitCost(uint256 _stakeUnitCost) override public onlyManager {
// 1e16 = 0.01 ether
stakeUnitCost = _stakeUnitCost;
}
function getStakeUnitCost() override public view returns (uint256) {
return stakeUnitCost;
}
function getStakeCostByBatch(uint256 _chainId, uint256 _batchIndex) override public view returns (uint256) {
require(stakeBaseCost > 0, "stake base cost not config yet");
require(queueBatchElement[_chainId][_batchIndex].txBatchTime > 0, "batch element does not exist");
return stakeBaseCost + queueBatchElement[_chainId][_batchIndex].txBatchSize * stakeUnitCost;
}
function setTxDataSliceSize(uint256 _size) override public onlyManager {
require(_size > 0, "slice size should gt 0");
require(_size != txDataSliceSize, "slice size has not changed");
txDataSliceSize = _size;
}
function getTxDataSliceSize() override public view returns (uint256) {
return txDataSliceSize;
}
function setTxDataSliceCount(uint256 _count) override public onlyManager {
require(_count > 0, "slice count should gt 0");
require(_count != txDataSliceCount, "slice count has not changed");
txDataSliceCount = _count;
}
function getTxDataSliceCount() override public view returns (uint256) {
return txDataSliceCount;
}
function setTxBatchSize(uint256 _size) override public onlyManager {
require(_size > 0, "batch size should gt 0");
require(_size != txBatchSize, "batch size has not changed");
txBatchSize = _size;
}
function getTxBatchSize() override public view returns (uint256) {
return txBatchSize;
}
function setStakeSeqSeconds(uint256 _seconds) override public onlyManager {
require(_seconds > 0, "seconds should gt 0");
require(_seconds != stakeSeqSeconds, "seconds has not changed");
stakeSeqSeconds = _seconds;
}
function getStakeSeqSeconds() override public view returns (uint256) {
return stakeSeqSeconds;
}
function isWhiteListed(address _verifier) override public view returns(bool){
return !useWhiteList || whitelist[_verifier];
}
function setWhiteList(address _verifier, bool _allowed) override public onlyManager {
whitelist[_verifier] = _allowed;
useWhiteList = true;
}
function disableWhiteList() override public onlyManager {
useWhiteList = false;
}
function appendSequencerBatchByChainId() override public {
uint256 _chainId;
uint40 shouldStartAtElement;
uint24 totalElementsToAppend;
uint24 numContexts;
uint256 batchTime;
uint256 _dataSize;
uint256 txSize;
bytes32 root;
assembly {
_dataSize := calldatasize()
_chainId := calldataload(4)
shouldStartAtElement := shr(216, calldataload(36))
totalElementsToAppend := shr(232, calldataload(41))
numContexts := shr(232, calldataload(44))
}
require(
msg.sender == resolve(string(abi.encodePacked(uint2str(_chainId),"_MVM_Sequencer_Wrapper"))),
"Function can only be called by the Sequencer."
);
uint256 posTs = 47 + 16 * numContexts;
if (_dataSize > posTs) {
// when tx count = 0, there is no hash!
// string len: [13]{milliseconds}-[1]{0}-[8]{sizeOfData}-[64]{hash}-[64]{root}
uint256 posTxSize = 7 + posTs;
uint256 posRoot = 11 + posTs;
assembly {
batchTime := shr(204, calldataload(posTs))
txSize := shr(224, calldataload(posTxSize))
root := calldataload(posRoot)
}
// check batch size
require(txSize / 2 <= txBatchSize, "size of tx data is too large");
}
address ctc = resolve("CanonicalTransactionChain");
IChainStorageContainer batchesRef = ICanonicalTransactionChain(ctc).batches();
uint256 batchIndex = batchesRef.lengthByChainId(_chainId);
{
// ctc call
(bool success, bytes memory result) = ctc.call(msg.data);
if (success == false) {
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
}
// save
queueBatchElement[_chainId][batchIndex] = BatchElement({
shouldStartAtElement: shouldStartAtElement,
totalElementsToAppend: totalElementsToAppend,
txBatchSize: txSize,
txBatchTime: batchTime,
root: root,
timestamp: block.timestamp
});
emit AppendBatchElement(
_chainId,
batchIndex,
shouldStartAtElement,
totalElementsToAppend,
txSize,
batchTime,
root
);
}
function setBatchTxDataForStake(
uint256 _chainId,
uint256 _batchIndex,
uint256 _blockNumber,
bytes memory _data,
uint256 _leafIndex,
uint256 _totalLeaves,
bytes32[] memory _proof
)
override
public
{
require(
msg.sender == resolve(string(abi.encodePacked(uint2str(_chainId),"_MVM_Sequencer_Wrapper"))),
"Function can only be called by the Sequencer."
);
// check stake
require(queueTxDataRequestStake[_chainId][_blockNumber].timestamp > 0, "there is no stake for this block number");
require(queueTxDataRequestStake[_chainId][_blockNumber].batchIndex == _batchIndex, "incorrect batch index");
require(queueTxDataRequestStake[_chainId][_blockNumber].status == STAKESTATUS.INIT, "not allowed to submit");
// sequencer can submit at any time
// require(queueTxDataRequestStake[_chainId][_blockNumber].endtime >= block.timestamp, "can not submit out of sequencer submit protection");
_setBatchTxData(_chainId, _batchIndex, _blockNumber, _data, _leafIndex, _totalLeaves, _proof, true);
if (queueTxDataRequestStake[_chainId][_blockNumber].status == STAKESTATUS.INIT) {
require(
queueTxDataRequestStake[_chainId][_blockNumber].amount <= verifierStakes[queueTxDataRequestStake[_chainId][_blockNumber].sender],
"insufficient stake"
);
require(
queueTxDataRequestStake[_chainId][_blockNumber].amount <= address(this).balance,
"insufficient balance"
);
queueTxDataRequestStake[_chainId][_blockNumber].status = STAKESTATUS.SEQ_SET;
if (queueTxDataRequestStake[_chainId][_blockNumber].amount > 0){
verifierStakes[queueTxDataRequestStake[_chainId][_blockNumber].sender] -= queueTxDataRequestStake[_chainId][_blockNumber].amount;
// transfer from contract to sender ETHER and record
(bool success, ) = payable(msg.sender).call{value: queueTxDataRequestStake[_chainId][_blockNumber].amount}("");
require(success, "insufficient balance");
queueTxDataRequestStake[_chainId][_blockNumber].amount = 0;
}
}
emit SetBatchTxData(
msg.sender,
_chainId,
_batchIndex,
_blockNumber,
queueTxDataRequestStake[_chainId][_blockNumber].amount,
true,
true
);
}
function setBatchTxDataForVerifier(
uint256 _chainId,
uint256 _batchIndex,
uint256 _blockNumber,
bytes memory _data
)
override
public
{
require(
msg.sender != resolve(string(abi.encodePacked(uint2str(_chainId),"_MVM_Sequencer_Wrapper"))),
"Function can not be called by the Sequencer."
);
// check stake
require(queueTxDataRequestStake[_chainId][_blockNumber].timestamp > 0, "there is no stake for this block number");
require(queueTxDataRequestStake[_chainId][_blockNumber].batchIndex == _batchIndex, "incorrect batch index");
// require(queueTxDataRequestStake[_chainId][_blockNumber].status == STAKESTATUS.INIT, "not allowed to submit");
// require(queueTxDataRequestStake[_chainId][_blockNumber].sender == msg.sender, "can not submit with other's stake");
require(queueTxDataRequestStake[_chainId][_blockNumber].endtime < block.timestamp, "can not submit during sequencer submit protection");
if (queueTxDataRequestStake[_chainId][_blockNumber].sender != msg.sender) {
// other verifier can submit in double window times
require(queueTxDataRequestStake[_chainId][_blockNumber].endtime + stakeSeqSeconds < block.timestamp, "can not submit during staker submit protection");
}
_setBatchTxData(_chainId, _batchIndex, _blockNumber, _data, 0, 0, new bytes32[](0), false);
if (queueTxDataRequestStake[_chainId][_blockNumber].status == STAKESTATUS.INIT) {
queueTxDataRequestStake[_chainId][_blockNumber].status = STAKESTATUS.VERIFIER_SET;
address claimer = queueTxDataRequestStake[_chainId][_blockNumber].sender;
if (queueTxDataRequestStake[_chainId][_blockNumber].amount <= verifierStakes[claimer] && queueTxDataRequestStake[_chainId][_blockNumber].amount > 0) {
require(
queueTxDataRequestStake[_chainId][_blockNumber].amount <= address(this).balance,
"insufficient balance"
);
verifierStakes[claimer] -= queueTxDataRequestStake[_chainId][_blockNumber].amount;
// transfer from contract to sender ETHER and record
(bool success, ) = payable(claimer).call{value: queueTxDataRequestStake[_chainId][_blockNumber].amount}("");
require(success, "insufficient balance");
queueTxDataRequestStake[_chainId][_blockNumber].amount = 0;
}
}
emit SetBatchTxData(
msg.sender,
_chainId,
_batchIndex,
_blockNumber,
queueTxDataRequestStake[_chainId][_blockNumber].amount,
false,
false
);
}
function _setBatchTxData(
uint256 _chainId,
uint256 _batchIndex,
uint256 _blockNumber,
bytes memory _data,
uint256 _leafIndex,
uint256 _totalLeaves,
bytes32[] memory _proof,
bool _requireVerify
)
internal
{
require(_data.length > 0, "empty data");
// check queue BatchElement
require(queueBatchElement[_chainId][_batchIndex].txBatchTime > 0, "batch element does not exist");
require(queueBatchElement[_chainId][_batchIndex].totalElementsToAppend > 0, "batch total element to append should not be zero");
// sequencer protect
if (queueTxData[_chainId][_blockNumber].timestamp > 0) {
require(queueTxData[_chainId][_blockNumber].verified == false, "tx data verified");
if (queueTxData[_chainId][_blockNumber].sender != msg.sender) {
require(queueTxData[_chainId][_blockNumber].timestamp + TXDATA_SUBMIT_TIMEOUT > block.timestamp, "in submitting");
// change sumbitter
queueTxData[_chainId][_blockNumber].sender = msg.sender;
queueTxData[_chainId][_blockNumber].blockNumber = _blockNumber;
queueTxData[_chainId][_blockNumber].batchIndex = _batchIndex;
queueTxData[_chainId][_blockNumber].timestamp = block.timestamp;
queueTxData[_chainId][_blockNumber].txData = _data;
queueTxData[_chainId][_blockNumber].verified = false;
}
else {
queueTxData[_chainId][_blockNumber].txData = _data;
// verified restore to false
queueTxData[_chainId][_blockNumber].verified = false;
}
}
else {
queueTxData[_chainId][_blockNumber] = TxDataSlice({
sender: msg.sender,
blockNumber: _blockNumber,
batchIndex: _batchIndex,
timestamp: block.timestamp,
txData: _data,
verified: false
});
}
if (_requireVerify) {
bytes32 currLeaf = keccak256(abi.encodePacked(_blockNumber, _data));
bool verified = Lib_MerkleTree.verify(queueBatchElement[_chainId][_batchIndex].root, currLeaf, _leafIndex, _proof, _totalLeaves);
require(verified == true, "tx data verify failed");
// save verified status
queueTxData[_chainId][_blockNumber].verified = true;
}
}
function getBatchTxData(
uint256 _chainId,
uint256 _batchIndex,
uint256 _blockNumber
)
override
external
view
returns (
bytes memory txData,
bool verified
)
{
require(queueTxData[_chainId][_blockNumber].timestamp != 0, "tx data does not exist");
require(queueTxData[_chainId][_blockNumber].batchIndex == _batchIndex, "incorrect batch index");
return (
queueTxData[_chainId][_blockNumber].txData,
queueTxData[_chainId][_blockNumber].verified
);
}
function checkBatchTxHash(
uint256 _chainId,
uint256 _batchIndex,
uint256 _blockNumber,
bytes memory _data
)
override
external
view
returns (
bytes32 txHash,
bool verified
)
{
require(queueTxData[_chainId][_blockNumber].timestamp != 0, "tx data does not exist");
require(queueTxData[_chainId][_blockNumber].batchIndex == _batchIndex, "incorrect batch index");
return (
keccak256(abi.encodePacked(_blockNumber, _data)),
queueTxData[_chainId][_blockNumber].verified
);
}
function setBatchTxDataVerified(
uint256 _chainId,
uint256 _batchIndex,
uint256 _blockNumber,
bool _verified
)
override
public
onlyManager
{
require(queueTxData[_chainId][_blockNumber].timestamp != 0, "tx data does not exist");
require(queueTxData[_chainId][_blockNumber].batchIndex == _batchIndex, "incorrect batch index");
require(queueTxData[_chainId][_blockNumber].verified != _verified, "verified status not change");
queueTxData[_chainId][_blockNumber].verified = _verified;
}
function verifierStake(
uint256 _chainId,
uint256 _batchIndex,
uint256 _blockNumber
)
override
public
payable
onlyWhitelisted
{
uint256 _amount = msg.value;
uint256 stakeCost = getStakeCostByBatch(_chainId, _batchIndex);
require(stakeBaseCost > 0, "stake base cost not config yet");
require(stakeCost == _amount, "stake cost incorrect");
require(stakeSeqSeconds > 0, "sequencer submit seconds not config yet");
// check queue BatchElement
require(queueBatchElement[_chainId][_batchIndex].txBatchTime > 0, "batch element does not exist");
// check block number in batch range, block number = index + 1
require(queueBatchElement[_chainId][_batchIndex].totalElementsToAppend + queueBatchElement[_chainId][_batchIndex].shouldStartAtElement >= _blockNumber && queueBatchElement[_chainId][_batchIndex].shouldStartAtElement < _blockNumber, "block number is not in this batch");
if (queueTxDataRequestStake[_chainId][_blockNumber].timestamp > 0) {
require(queueTxDataRequestStake[_chainId][_blockNumber].status == STAKESTATUS.PAYBACK, "there is a stake for this batch index");
}
//check window
StateCommitmentChain stateChain = StateCommitmentChain(resolve("StateCommitmentChain"));
require(queueBatchElement[_chainId][_batchIndex].timestamp + stateChain.FRAUD_PROOF_WINDOW() > block.timestamp, "the batch is outside of the fraud proof window");
queueTxDataRequestStake[_chainId][_blockNumber] = TxDataRequestStake({
sender: msg.sender,
blockNumber: _blockNumber,
batchIndex: _batchIndex,
timestamp: block.timestamp,
endtime: block.timestamp + stakeSeqSeconds,
amount: _amount,
status: STAKESTATUS.INIT
});
verifierStakes[msg.sender] += _amount;
emit VerifierStake(msg.sender, _chainId, _batchIndex, _blockNumber, _amount);
}
function withdrawStake(
uint256 _chainId,
uint256 _batchIndex,
uint256 _blockNumber
)
override
public
{
require(queueTxDataRequestStake[_chainId][_blockNumber].timestamp > 0, "there is no stake for this batch index");
require(queueTxDataRequestStake[_chainId][_blockNumber].amount > 0, "stake amount is zero");
require(queueTxDataRequestStake[_chainId][_blockNumber].status == STAKESTATUS.INIT, "withdrawals are not allowed");
require(queueTxDataRequestStake[_chainId][_blockNumber].sender == msg.sender, "can not withdraw other's stake");
require(queueTxDataRequestStake[_chainId][_blockNumber].endtime < block.timestamp, "can not withdraw during submit protection");
require(queueTxDataRequestStake[_chainId][_blockNumber].amount <= verifierStakes[msg.sender], "insufficient stake");
require(
queueTxDataRequestStake[_chainId][_blockNumber].amount <= address(this).balance,
"insufficient balance"
);
queueTxDataRequestStake[_chainId][_blockNumber].status = STAKESTATUS.PAYBACK;
verifierStakes[msg.sender] -= queueTxDataRequestStake[_chainId][_blockNumber].amount;
// transfer from contract to sender ETHER and record
(bool success, ) = payable(msg.sender).call{value: queueTxDataRequestStake[_chainId][_blockNumber].amount}("");
require(success, "insufficient balance");
queueTxDataRequestStake[_chainId][_blockNumber].amount = 0;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
}
| check queue BatchElement check block number in batch range, block number = index + 1 | function verifierStake(
uint256 _chainId,
uint256 _batchIndex,
uint256 _blockNumber
)
override
public
payable
onlyWhitelisted
{
uint256 _amount = msg.value;
uint256 stakeCost = getStakeCostByBatch(_chainId, _batchIndex);
require(stakeBaseCost > 0, "stake base cost not config yet");
require(stakeCost == _amount, "stake cost incorrect");
require(stakeSeqSeconds > 0, "sequencer submit seconds not config yet");
require(queueBatchElement[_chainId][_batchIndex].txBatchTime > 0, "batch element does not exist");
require(queueBatchElement[_chainId][_batchIndex].totalElementsToAppend + queueBatchElement[_chainId][_batchIndex].shouldStartAtElement >= _blockNumber && queueBatchElement[_chainId][_batchIndex].shouldStartAtElement < _blockNumber, "block number is not in this batch");
if (queueTxDataRequestStake[_chainId][_blockNumber].timestamp > 0) {
require(queueTxDataRequestStake[_chainId][_blockNumber].status == STAKESTATUS.PAYBACK, "there is a stake for this batch index");
}
require(queueBatchElement[_chainId][_batchIndex].timestamp + stateChain.FRAUD_PROOF_WINDOW() > block.timestamp, "the batch is outside of the fraud proof window");
queueTxDataRequestStake[_chainId][_blockNumber] = TxDataRequestStake({
sender: msg.sender,
blockNumber: _blockNumber,
batchIndex: _batchIndex,
timestamp: block.timestamp,
endtime: block.timestamp + stakeSeqSeconds,
amount: _amount,
status: STAKESTATUS.INIT
});
verifierStakes[msg.sender] += _amount;
emit VerifierStake(msg.sender, _chainId, _batchIndex, _blockNumber, _amount);
}
| 5,531,686 |
// File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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);
}
// File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @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 EnumMap for EnumMap.Map;
*
* // Declare a set state variable
* EnumMap.Map private myMap;
* }
* ```
*/
library EnumMap {
// 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.
// This means that we can only create new EnumMaps 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) internal 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) internal 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) internal 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) internal 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) internal view returns (bytes32, bytes32) {
require(map.entries.length > index, "EnumMap: 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) internal view returns (bytes32) {
uint256 keyIndex = map.indexes[key];
require(keyIndex != 0, "EnumMap: nonexistent key"); // Equivalent to contains(map, key)
return map.entries[keyIndex - 1].value; // All indexes are 1-based
}
}
// File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumSet for EnumSet.Set;
*
* // Declare a set state variable
* EnumSet.Set private mySet;
* }
* ```
*/
library EnumSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Set storage set, bytes32 value) internal returns (bool) {
if (!contains(set, value)) {
set.values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set.indexes[value] = set.values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Set storage set, bytes32 value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set.indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set.values.length - 1;
// When the value 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.
bytes32 lastvalue = set.values[lastIndex];
// Move the last value to the index where the value to delete is
set.values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set.indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set.values.pop();
// Delete the index for the deleted slot
delete set.indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Set storage set, bytes32 value) internal view returns (bool) {
return set.indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal view returns (uint256) {
return set.values.length;
}
/**
* @dev Returns the value 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(Set storage set, uint256 index) internal view returns (bytes32) {
require(set.values.length > index, "EnumSet: index out of bounds");
return set.values[index];
}
}
// File @openzeppelin/contracts/GSN/[email protected]
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @animoca/ethereum-contracts-core_library/contracts/payment/[email protected]
pragma solidity 0.6.8;
/**
@title PayoutWallet
@dev adds support for a payout wallet
Note: .
*/
contract PayoutWallet is Ownable
{
event PayoutWalletSet(address payoutWallet_);
address payable public payoutWallet;
constructor(address payoutWallet_) internal {
setPayoutWallet(payoutWallet_);
}
function setPayoutWallet(address payoutWallet_) public onlyOwner {
require(payoutWallet_ != address(0), "The payout wallet must not be the zero address");
require(payoutWallet_ != address(this), "The payout wallet must not be the contract itself");
require(payoutWallet_ != payoutWallet, "The payout wallet must be different");
payoutWallet = payable(payoutWallet_);
emit PayoutWalletSet(payoutWallet);
}
}
// File @animoca/ethereum-contracts-core_library/contracts/utils/[email protected]
pragma solidity 0.6.8;
/**
* Contract module which allows derived contracts to implement a mechanism for
* activating, or 'starting', a contract.
*
* This module is used through inheritance. It will make available the modifiers
* `whenNotStarted` and `whenStarted`, which can be applied to the functions of
* your contract. Those functions will only be 'startable' once the modifiers
* are put in place.
*/
contract Startable is Context {
event Started(address account);
uint256 private _startedAt;
/**
* Modifier to make a function callable only when the contract has not started.
*/
modifier whenNotStarted() {
require(_startedAt == 0, "Startable: started");
_;
}
/**
* Modifier to make a function callable only when the contract has started.
*/
modifier whenStarted() {
require(_startedAt != 0, "Startable: not started");
_;
}
/**
* Constructor.
*/
constructor () internal {}
/**
* Returns the timestamp when the contract entered the started state.
* @return The timestamp when the contract entered the started state.
*/
function startedAt() public view returns (uint256) {
return _startedAt;
}
/**
* Triggers the started state.
* @dev Emits the Started event when the function is successfully called.
*/
function _start() internal virtual whenNotStarted {
_startedAt = now;
emit Started(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.6.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.6.2;
/**
* @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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
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/math/[email protected]
pragma solidity ^0.6.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 @animoca/ethereum-contracts-sale_base/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title ISale
*
* An interface for a contract which allows merchants to display products and customers to purchase them.
*
* Products, designated as SKUs, are represented by bytes32 identifiers so that an identifier can carry an
* explicit name under the form of a fixed-length string. Each SKU can be priced via up to several payment
* tokens which can be ETH and/or ERC20(s). ETH token is represented by the magic value TOKEN_ETH, which means
* this value can be used as the 'token' argument of the purchase-related functions to indicate ETH payment.
*
* The total available supply for a SKU is fixed at its creation. The magic value SUPPLY_UNLIMITED is used
* to represent a SKU with an infinite, never-decreasing supply. An optional purchase notifications receiver
* contract address can be set for a SKU at its creation: if the value is different from the zero address,
* the function `onPurchaseNotificationReceived` will be called on this address upon every purchase of the SKU.
*
* This interface is designed to be consistent while managing a variety of implementation scenarios. It is
* also intended to be developer-friendly: all vital information is consistently deductible from the events
* (backend-oriented), as well as retrievable through calls to public functions (frontend-oriented).
*/
interface ISale {
/**
* Event emitted to notify about the magic values necessary for interfacing with this contract.
* @param names An array of names for the magic values used by the contract.
* @param values An array of values for the magic values used by the contract.
*/
event MagicValues(bytes32[] names, bytes32[] values);
/**
* Event emitted to notify about the creation of a SKU.
* @param sku The identifier of the created SKU.
* @param totalSupply The initial total supply for sale.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver If not the zero address, the address of a contract on which `onPurchaseNotificationReceived` will be called after each purchase,
* If this is the zero address, the call is not enabled.
*/
event SkuCreation(bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver);
/**
* Event emitted to notify about a change in the pricing of a SKU.
* @dev `tokens` and `prices` arrays MUST have the same length.
* @param sku The identifier of the updated SKU.
* @param tokens An array of updated payment tokens. If empty, interpret as all payment tokens being disabled.
* @param prices An array of updated prices for each of the payment tokens.
* Zero price values are used for payment tokens being disabled.
*/
event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices);
/**
* Event emitted to notify about a purchase.
* @param purchaser The initiater and buyer of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token used as the currency for the payment.
* @param sku The identifier of the purchased SKU.
* @param quantity The purchased quantity.
* @param userData Optional extra user input data.
* @param totalPrice The amount of `token` paid.
* @param pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* @param paymentData Implementation-specific extra payment data, such as conversion rates.
* @param deliveryData Implementation-specific extra delivery data, such as purchase receipts.
*/
event Purchase(
address indexed purchaser,
address recipient,
address indexed token,
bytes32 indexed sku,
uint256 quantity,
bytes userData,
uint256 totalPrice,
bytes32[] pricingData,
bytes32[] paymentData,
bytes32[] deliveryData
);
/**
* Returns the magic value used to represent the ETH payment token.
* @dev MUST NOT be the zero address.
* @return the magic value used to represent the ETH payment token.
*/
function TOKEN_ETH() external pure returns (address);
/**
* Returns the magic value used to represent an infinite, never-decreasing SKU's supply.
* @dev MUST NOT be zero.
* @return the magic value used to represent an infinite, never-decreasing SKU's supply.
*/
function SUPPLY_UNLIMITED() external pure returns (uint256);
/**
* Performs a purchase.
* @dev Reverts if `token` is the address zero.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external payable;
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price to pay.
* @return pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* If not empty, the implementer MUST document how to interepret the values.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view returns (uint256 totalPrice, bytes32[] memory pricingData);
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
view
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
);
/**
* Returns the list of created SKU identifiers.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of SKUs is bounded, so that this function does not run out of gas.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external view returns (bytes32[] memory skus);
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title IPurchaseNotificationsReceiver
* Interface for any contract that wants to support purchase notifications from a Sale contract.
*/
interface IPurchaseNotificationsReceiver {
/**
* Handles the receipt of a purchase notification.
* @dev This function MUST return the function selector, otherwise the caller will revert the transaction.
* The selector to be returned can be obtained as `this.onPurchaseNotificationReceived.selector`
* @dev This function MAY throw.
* @param purchaser The purchaser of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
* @param totalPrice The total price paid.
* @param pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* @param paymentData Implementation-specific extra payment data, such as conversion rates.
* @param deliveryData Implementation-specific extra delivery data, such as purchase receipts.
* @return `bytes4(keccak256("onPurchaseNotificationReceived(address,address,address,bytes32,uint256,bytes,uint256,bytes32[],bytes32[],bytes32[])"))`
*/
function onPurchaseNotificationReceived(
address purchaser,
address recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData,
uint256 totalPrice,
bytes32[] calldata pricingData,
bytes32[] calldata paymentData,
bytes32[] calldata deliveryData
) external pure returns (bytes4);
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title PurchaseLifeCycles
* An abstract contract which define the life cycles for a purchase implementer.
*/
abstract contract PurchaseLifeCycles {
/**
* Wrapper for the purchase data passed as argument to the life cycle functions and down to their step functions.
*/
struct PurchaseData {
address payable purchaser;
address payable recipient;
address token;
bytes32 sku;
uint256 quantity;
bytes userData;
uint256 totalPrice;
bytes32[] pricingData;
bytes32[] paymentData;
bytes32[] deliveryData;
}
/* Internal Life Cycle Functions */
/**
* `estimatePurchase` lifecycle.
* @param purchase The purchase conditions.
*/
function _estimatePurchase(PurchaseData memory purchase)
internal
virtual
view
returns (uint256 totalPrice, bytes32[] memory pricingData)
{
_validation(purchase);
_pricing(purchase);
totalPrice = purchase.totalPrice;
pricingData = purchase.pricingData;
}
/**
* `purchaseFor` lifecycle.
* @param purchase The purchase conditions.
*/
function _purchaseFor(PurchaseData memory purchase) internal virtual {
_validation(purchase);
_pricing(purchase);
_payment(purchase);
_delivery(purchase);
_notification(purchase);
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal virtual view;
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal virtual view;
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual;
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title AbstractSale
* An abstract base sale contract with a minimal implementation of ISale and administration functions.
* A minimal implementation of the `_validation`, `_delivery` and `notification` life cycle step functions
* are provided, but the inheriting contract must implement `_pricing` and `_payment`.
*/
abstract contract AbstractSale is PurchaseLifeCycles, ISale, PayoutWallet, Startable, Pausable {
using Address for address;
using SafeMath for uint256;
using EnumSet for EnumSet.Set;
using EnumMap for EnumMap.Map;
struct SkuInfo {
uint256 totalSupply;
uint256 remainingSupply;
uint256 maxQuantityPerPurchase;
address notificationsReceiver;
EnumMap.Map prices;
}
address public constant override TOKEN_ETH = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint256 public constant override SUPPLY_UNLIMITED = type(uint256).max;
EnumSet.Set internal _skus;
mapping(bytes32 => SkuInfo) internal _skuInfos;
uint256 internal immutable _skusCapacity;
uint256 internal immutable _tokensPerSkuCapacity;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal PayoutWallet(payoutWallet_) {
_skusCapacity = skusCapacity;
_tokensPerSkuCapacity = tokensPerSkuCapacity;
bytes32[] memory names = new bytes32[](2);
bytes32[] memory values = new bytes32[](2);
(names[0], values[0]) = ("TOKEN_ETH", bytes32(uint256(TOKEN_ETH)));
(names[1], values[1]) = ("SUPPLY_UNLIMITED", bytes32(uint256(SUPPLY_UNLIMITED)));
emit MagicValues(names, values);
_pause();
}
/* Public Admin Functions */
/**
* Actvates, or 'starts', the contract.
* @dev Emits the `Started` event.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has already been started.
* @dev Reverts if the contract is not paused.
*/
function start() public virtual onlyOwner {
_start();
_unpause();
}
/**
* Pauses the contract.
* @dev Emits the `Paused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is already paused.
*/
function pause() public virtual onlyOwner whenStarted {
_pause();
}
/**
* Resumes the contract.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is not paused.
*/
function unpause() public virtual onlyOwner whenStarted {
_unpause();
}
/**
* Creates an SKU.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address.
* @dev Reverts if the update results in too many SKUs.
* @dev Emits the `SkuCreation` event.
* @param sku the SKU identifier.
* @param totalSupply the initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
*/
function createSku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver
) public virtual onlyOwner {
require(totalSupply != 0, "Sale: zero supply");
require(_skus.length() < _skusCapacity, "Sale: too many skus");
require(_skus.add(sku), "Sale: sku already created");
if (notificationsReceiver != address(0)) {
require(notificationsReceiver.isContract(), "Sale: receiver is not a contract");
}
SkuInfo storage skuInfo = _skuInfos[sku];
skuInfo.totalSupply = totalSupply;
skuInfo.remainingSupply = totalSupply;
skuInfo.maxQuantityPerPurchase = maxQuantityPerPurchase;
skuInfo.notificationsReceiver = notificationsReceiver;
emit SkuCreation(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver);
}
/**
* Sets the token prices for the specified product SKU.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `tokens` and `prices` have different lengths.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @dev Emits the `SkuPricingUpdate` event.
* @param sku The identifier of the SKU.
* @param tokens The list of payment tokens to update.
* If empty, disable all the existing payment tokens.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function updateSkuPricing(
bytes32 sku,
address[] memory tokens,
uint256[] memory prices
) public virtual onlyOwner {
uint256 length = tokens.length;
require(length == prices.length, "Sale: tokens/prices lengths mismatch");
SkuInfo storage skuInfo = _skuInfos[sku];
require(skuInfo.totalSupply != 0, "Sale: non-existent sku");
EnumMap.Map storage tokenPrices = skuInfo.prices;
if (length == 0) {
uint256 currentLength = tokenPrices.length();
for (uint256 i = 0; i < currentLength; ++i) {
// TODO add a clear function in EnumMap and EnumSet and use it
(bytes32 token, ) = tokenPrices.at(0);
tokenPrices.remove(token);
}
} else {
_setTokenPrices(tokenPrices, tokens, prices);
}
emit SkuPricingUpdate(sku, tokens, prices);
}
/* ISale Public Functions */
/**
* Performs a purchase.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `token` is the address zero.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external virtual override payable whenStarted whenNotPaused {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
_purchaseFor(purchase);
}
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev If an implementer contract uses the `priceInfo` field, it SHOULD document how to interpret the info.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price.
* @return priceInfo Implementation-specific extra price information, such as details about potential discounts applied.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external virtual override view whenStarted whenNotPaused returns (uint256 totalPrice, bytes32[] memory priceInfo) {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
return _estimatePurchase(purchase);
}
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
override
view
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
)
{
SkuInfo storage skuInfo = _skuInfos[sku];
uint256 length = skuInfo.prices.length();
totalSupply = skuInfo.totalSupply;
remainingSupply = skuInfo.remainingSupply;
maxQuantityPerPurchase = skuInfo.maxQuantityPerPurchase;
notificationsReceiver = skuInfo.notificationsReceiver;
tokens = new address[](length);
prices = new uint256[](length);
for (uint256 i = 0; i < length; ++i) {
(bytes32 token, bytes32 price) = skuInfo.prices.at(i);
tokens[i] = address(uint256(token));
prices[i] = uint256(price);
}
}
/**
* Returns the list of created SKU identifiers.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external override view returns (bytes32[] memory skus) {
skus = _skus.values;
}
/* Internal Utility Functions */
function _setTokenPrices(
EnumMap.Map storage tokenPrices,
address[] memory tokens,
uint256[] memory prices
) internal virtual {
for (uint256 i = 0; i < tokens.length; ++i) {
address token = tokens[i];
require(token != address(0), "Sale: zero address token");
uint256 price = prices[i];
if (price == 0) {
tokenPrices.remove(bytes32(uint256(token)));
} else {
tokenPrices.set(bytes32(uint256(token)), bytes32(price));
}
}
require(tokenPrices.length() <= _tokensPerSkuCapacity, "Sale: too many tokens");
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @dev Reverts if `purchase.recipient` is the zero address.
* @dev Reverts if `purchase.quantity` is zero.
* @dev Reverts if `purchase.quantity` is greater than the SKU's `maxQuantityPerPurchase`.
* @dev Reverts if `purchase.quantity` is greater than the available supply.
* @dev If this function is overriden, the implementer SHOULD super call this before.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal virtual override view {
require(purchase.recipient != address(0), "Sale: zero address recipient");
require(purchase.quantity != 0, "Sale: zero quantity purchase");
SkuInfo memory skuInfo = _skuInfos[purchase.sku];
require(purchase.quantity <= skuInfo.maxQuantityPerPurchase, "Sale: above max quantity");
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
require(skuInfo.remainingSupply >= purchase.quantity, "Sale: insufficient supply");
}
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Reverts if there is not enough available supply.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual override {
SkuInfo memory skuInfo = _skuInfos[purchase.sku];
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
_skuInfos[purchase.sku].remainingSupply = skuInfo.remainingSupply.sub(purchase.quantity);
}
}
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @dev Reverts if `onPurchaseNotificationReceived` throws or returns an incorrect value.
* @dev Emits the `Purchase` event. The values of `purchaseData` are the concatenated values of `priceData`, `paymentData`
* and `deliveryData`. If not empty, the implementer MUST document how to interpret these values.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual override {
emit Purchase(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
purchase.pricingData,
purchase.paymentData,
purchase.deliveryData
);
address notificationsReceiver = _skuInfos[purchase.sku].notificationsReceiver;
if (notificationsReceiver != address(0)) {
require(
IPurchaseNotificationsReceiver(notificationsReceiver).onPurchaseNotificationReceived(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
purchase.pricingData,
purchase.paymentData,
purchase.deliveryData
) == IPurchaseNotificationsReceiver(address(0)).onPurchaseNotificationReceived.selector, // TODO precompute return value
"Sale: wrong receiver return value"
);
}
}
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title FixedPricesSale
* An AbstractSale which implements a fixed prices strategy.
* The final implementer is responsible for implementing any additional pricing and/or delivery logic.
*/
contract FixedPricesSale is AbstractSale {
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal AbstractSale(payoutWallet_, skusCapacity, tokensPerSkuCapacity) {}
/* Internal Life Cycle Functions */
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.token` is not supported by the SKU.
* @dev Reverts in case of price overflow.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal virtual override view {
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: unsupported SKU");
EnumMap.Map storage prices = skuInfo.prices;
uint256 unitPrice = _unitPrice(purchase, prices);
purchase.totalPrice = unitPrice.mul(purchase.quantity);
}
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @dev Reverts in case of payment failure.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual override {
if (purchase.token == TOKEN_ETH) {
require(msg.value >= purchase.totalPrice, "Sale: insufficient ETH provided");
payoutWallet.transfer(purchase.totalPrice);
uint256 change = msg.value.sub(purchase.totalPrice);
if (change != 0) {
purchase.purchaser.transfer(change);
}
} else {
require(
IERC20(purchase.token).transferFrom(_msgSender(), payoutWallet, purchase.totalPrice),
"Sale: ERC20 payment failed"
);
}
}
/* Internal Utility Functions */
function _unitPrice(PurchaseData memory purchase, EnumMap.Map storage prices)
internal
virtual
view
returns (uint256 unitPrice)
{
unitPrice = uint256(prices.get(bytes32(uint256(purchase.token))));
require(unitPrice != 0, "Sale: unsupported payment token");
}
}
// File @animoca/f1dt-ethereum-contracts/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title CrateKeyFullSale
* A FixedPricesSale contract implementation that handles the full-price (non-discounted) purchase of ERC20 F1DTCrateKey tokens.
*/
contract CrateKeyFullSale is FixedPricesSale {
/* sku => crate key */
mapping (bytes32 => IF1DTCrateKeyFull) public crateKeys;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @dev Emits the `PayoutWalletSet` event.
* @param payoutWallet_ the payout wallet.
*/
constructor (
address payoutWallet_
)
public
FixedPricesSale(
payoutWallet_,
4, // SKUs capacity (each type of crate key only)
4 // tokens per-SKU capacity
)
{
}
/**
* Creates an SKU.
* @dev Deprecated. Please use `createCrateKeySku(bytes32, uint256, uint256, IF1DTCrateKeyFull)` for creating
* inventory SKUs.
* @dev Reverts if called.
* @param *sku* the SKU identifier.
* @param *totalSupply* the initial total supply.
* @param *maxQuantityPerPurchase* The maximum allowed quantity for a single purchase.
* @param *notificationsReceiver* The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
*/
function createSku(
bytes32 /*sku*/,
uint256 /*totalSupply*/,
uint256 /*maxQuantityPerPurchase*/,
address /*notificationsReceiver*/
) public override onlyOwner {
revert("Deprecated. Please use `createCrateKeySku(bytes32, uint256, uint256, IF1DTCrateKeyFull)`");
}
/**
* Creates an SKU and associates the specified ERC20 F1DTCrateKey token contract with it.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if the update results in too many SKUs.
* @dev Reverts if the `totalSupply` is SUPPLY_UNLIMITED.
* @dev Reverts if the `crateKey` is the zero address.
* @dev Emits the `SkuCreation` event.
* @param sku The SKU identifier.
* @param totalSupply The initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param crateKey The ERC20 F1DTCrateKey token contract to bind with the SKU.
*/
function createCrateKeySku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
IF1DTCrateKeyFull crateKey
) external onlyOwner {
require(
totalSupply != SUPPLY_UNLIMITED,
"CrateKeyFullSale: invalid total supply");
require(
crateKey != IF1DTCrateKeyFull(0),
"CrateKeyFullSale: zero address");
super.createSku(
sku,
totalSupply,
maxQuantityPerPurchase,
address(0)); // notifications receiver
crateKeys[sku] = crateKey;
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Transfers tokens from the ERC20 F1DTCrateKey token contract associated with the SKU being purchased, of the
* specified purchase quantity.
* @dev Reverts if the holder has an insufficient ERC20 F1DTCrateKey token balance for the transfer.
* @dev Reverts if the sale contract has an insufficient ERC20 F1DTCrateKey allowance for the transfer.
* @param purchase The purchase conditions.
*/
function _delivery(
PurchaseData memory purchase
) internal override {
super._delivery(purchase);
IF1DTCrateKeyFull crateKey = crateKeys[purchase.sku];
crateKey.transferFrom(
crateKey.holder(),
purchase.recipient,
purchase.quantity);
}
}
/**
* @dev Interface of the ERC20 F1DTCrateKey token contract.
*/
interface IF1DTCrateKeyFull {
/**
* Returns the amount of tokens owned by `account`.
* @param account The account whose token balance will be retrieved.
* @return The amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through
* {transferFrom}.
* @dev This value is zero by default.
* @dev This value changes when {approve} or {transferFrom} are called.
* @param owner The account who has granted a spending allowance to the spender.
* @param spender The account who has been granted a spending allowance by the owner.
* @return The remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through
* {transferFrom}.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism.
* @dev `amount` is deducted from the caller's allowance.
* @dev Emits a {Transfer} event.
* @param sender The account where the tokens will be transferred from.
* @param recipient The account where the tokens will be transferred to.
* @param amount The amount of tokens being transferred.
* @return Boolean indicating whether the operation succeeded.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* Returns the account holding the initial token supply.
* @return The account holding the initial token supply.
*/
function holder() external view returns (address);
} | Creates an SKU. Deprecated. Please use `createCrateKeySku(bytes32, uint256, uint256, IF1DTCrateKeyFull)` for creating inventory SKUs. Reverts if called. sku the SKU identifier. totalSupply the initial total supply. maxQuantityPerPurchase The maximum allowed quantity for a single purchase. notificationsReceiver The purchase notifications receiver contract address. If set to the zero address, the notification is not enabled./ | function createSku(
bytes32 /*sku*/,
uint256 /*totalSupply*/,
uint256 /*maxQuantityPerPurchase*/,
address /*notificationsReceiver*/
) public override onlyOwner {
revert("Deprecated. Please use `createCrateKeySku(bytes32, uint256, uint256, IF1DTCrateKeyFull)`");
}
| 228,635 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.8.0;
pragma experimental SMTChecker;
import "@openzeppelin/contracts/token/ERC20/presets/ERC20PresetFixedSupply.sol";
/**
* @author Eman Herawy, StartFi Team
*@title Start FiToken.
* [ desc ] : A Startfi Utiltiy token
* @dev this token follows openzeppelin ERC20PresetFixedSupply and AnyswapV5ERC20
*/
contract StartFiToken is ERC20PresetFixedSupply{
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant TRANSFER_TYPEHASH = keccak256("Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)");
/// @dev Records current ERC2612 nonce for account. This value must be included whenever signature is generated for {permit}.
/// Every successful call to {permit} increases account's nonce by one. This prevents signature from being used multiple times.
mapping (address => uint256) public nonces;
constructor(string memory name,
string memory symbol,
/*uint256 initialSupply,*/
address owner) ERC20PresetFixedSupply(name,symbol,100000000 * 1 ether,owner) {
uint chainId;
assembly {
chainId := chainId
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
/// @dev Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval.
/// Emits {Approval} event.
/// Requirements:
/// - `deadline` must be timestamp in future.
/// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments.
/// - the signature must use `owner` account's current nonce (see {nonces}).
/// - the signer cannot be zero address and must be `owner` account.
/// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section].
/// AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol.
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit");
bytes32 hashStruct = keccak256(
abi.encode(
PERMIT_TYPEHASH,
target,
spender,
value,
nonces[target]++,
deadline));
require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s));
_approve(target, spender, value);
}
/// @dev StartFiToken follows AnyswapV5ERC20 , check https://github.com/connext/chaindata/blob/main/AnyswapV5ERC20.sol#L460
/// Emits {Transfer} event.
/// Requirements:
/// - `deadline` must be timestamp in future.
/// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments.
/// - the signature must use `owner` account's current nonce (see {nonces}).
/// - the signer cannot be zero address and must be `owner` account.
/// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section].
function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool) {
require(block.timestamp <= deadline, "StartFiToken: Expired permit");
bytes32 hashStruct = keccak256(
abi.encode(
TRANSFER_TYPEHASH,
target,
to,
value,
nonces[target]++,
deadline));
require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s));
require(to != address(0) || to != address(this));
_transfer(target, to, value);
return true;
}
function verifyEIP712(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
bytes32 hash = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hashStruct));
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
function verifyPersonalSign(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
bytes32 hash = prefixed(hashStruct);
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
// Builds a prefixed hash to mimic the behavior of eth_sign.
function prefixed(bytes32 hash) internal view returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", DOMAIN_SEPARATOR, hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../extensions/ERC20Burnable.sol";
/**
* @dev {ERC20} token, including:
*
* - Preminted initial supply
* - Ability for holders to burn (destroy) their tokens
* - No access control mechanism (for minting/pausing) and hence no governance
*
* This contract uses {ERC20Burnable} to include burn capabilities - head to
* its documentation for details.
*
* _Available since v3.4._
*/
contract ERC20PresetFixedSupply is ERC20Burnable {
/**
* @dev Mints `initialSupply` amount of token and transfers them to `owner`.
*
* See {ERC20-constructor}.
*/
constructor(
string memory name,
string memory symbol,
uint256 initialSupply,
address owner
) ERC20(name, symbol) {
_mint(owner, initialSupply);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC20.sol";
import "../../../utils/Context.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
| Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval. Emits {Approval} event. Requirements: - `deadline` must be timestamp in future. - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments. - the signature must use `owner` account's current nonce (see {nonces}). - the signer cannot be zero address and must be `owner` account. For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612specification[relevant EIP section]. AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol. | function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit");
bytes32 hashStruct = keccak256(
abi.encode(
PERMIT_TYPEHASH,
target,
spender,
value,
nonces[target]++,
deadline));
require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s));
_approve(target, spender, value);
}
| 1,662,840 |
./full_match/1/0x8071fA30E5B3818369526dcFbf6492cF89E58fF5/sources/contracts/Morph.sol | set sale active time | function setSaleActiveTime(uint256 _saleActiveTime) external onlyOwner {
saleActiveTime = _saleActiveTime;
}
| 16,593,924 |
./full_match/43113/0x569f7E74b0A29a271a5D49EE588060d05022Ac51/sources/NFT.sol | Make royalty fee claimable and add to total MARK NFT AS SOLD | function buyListing(uint256 tokenId) public payable {
address tokenOwner = ownerOf(tokenId);
address payable seller = payable(address(tokenOwner));
require(msg.value >= Marketplace[tokenId].price, "Incorrect amount");
require(TokenState.ForSale == Marketplace[tokenId].state, "Not for sale");
uint256 fee = 0;
uint256 afterFee = 0;
if (Marketplace[tokenId].price >= 0) {
fee = royaltyOf(msg.value);
afterFee = SafeMath.sub(msg.value, fee);
address minter = _minters[tokenId];
seller.transfer(afterFee);
_claimable[minter] += fee;
_totalClaimable += fee;
_marketplaceVolume += msg.value;
}
Marketplace[tokenId].state = TokenState.Sold;
for(uint256 i = 0; i < ForSale.length; i++) {
if (ForSale[i] == tokenId) {
ForSale[i] = ForSale[ForSale.length - 1];
ForSale.pop();
break;
}
}
emit BoughtListing(tokenId, msg.value);
}
| 13,168,124 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// //
// ..... //
// -+*%@@@@@@@@@#*++=-: //
// .=#@@@@@@@@@@@@@@@@@@@@@@#+: //
// -#@@@@@@@@@@@@@@@@@@@@@@@@@@@@%- //
// [email protected]@@@@@@@@@%*+==----==*#@@@@@@@@@@%- //
// :%@@@@@@@@*-. :+%@@@@@@@@#. //
// [email protected]@@@@@@@+. -#@@@@@@@@+ //
// *@@@@@@@+. :#@@@@@@@%. //
// *@@@@@@@: [email protected]@@@@@@@- //
// [email protected]@@@@@%. :@@@@@@@@= //
// [email protected]@@@@@@. [email protected]@@@@@@@= //
// %@@@@@@= #@@@@@@@@= //
// [email protected]@@@@@@. [email protected]@@@@@@@@- //
// #@@@@@@# %@@@@@@@@@. //
// @@@@@@@* [email protected]@@@@@@@@* //
// @@@@@@@* @@@@@@@@@@. //
// [email protected]@@@@@@* *@@@@@@@@@= //
// [email protected]@@@@@@# [email protected]@@@@@@@@# //
// [email protected]@@@@@@% [email protected]@@@@@@@@@ //
// @@@@@@@@ [email protected]@@@@@@@@@. //
// %@@@@@@@. [email protected]@@@@@@@@@: //
// %@@@@@@@- [email protected]@@@@@@@@@- //
// :@@@@@@@@* #@@@@@@@@@@- //
// [email protected]@@@@@@@@@ .+%@@%[email protected]@@%+. [email protected]@@@@@@@@@@: //
// . @@@@@@@@@@= [email protected]#+-:. .:=%@= [email protected]@@@@@@@@@@: //
// [email protected]@@@@@@@@@% [email protected]: [email protected] @@@@@@@@@@@@: //
// *@@@@@@@@@@@# *= #: #@@@@@@@@@@@@: //
// *@@@@@@@@@@@@%: :: .--: : .%@@@@@@@@@@@@@= //
// [email protected]@@@@@@@@@@@@@+ [email protected]@# . [email protected]@@@@@@@@@@@@@@* //
// [email protected]@@@@@@@@@@@@@@%=.-+ *@. :@##@@@@@@@@@@@@@@@@@@ //
// [email protected]@@@@@@@@@@@@@@@@@@@= .==: -+=:-%@@@@@@@@@@@@@@@@@@@@@: //
// [email protected]*[email protected]@@@@@@@@@@@@#+%@@@@@@@@@@%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@* //
// *# [email protected]@@@@@@@@@@@@% :+#@@@@@@@@@@@@@@@%+:.%@@@@@@@@@@@@@@@@@@. //
// +* [email protected]@@@@@@@@@@@@@@= :-=+****++=-: %@@@@@@@@@@@@@@@@@@%: //
// += #@@@@@@@@@@@@@@@@: *@@@@@@@@@@@@@@@@@@@@@*: //
// -+. *@#@@@@@@@@@@@@@@@%. *@@@@@@@@@@@@@@@@@@@@@%*@#: //
// :. *%:[email protected]@@@@@@@@@@@@@@@%. .%#@@@@@@@@@@@@@@@@@@@[email protected]% [email protected]+ //
// -#= %@@@@@@@@@@@@@@@@@%. :[email protected]@@@@@@@@@@@@@@@@@@:*@= .*+ //
// . [email protected]@@@@@@@@@@@@@@@@@@: . *@@@@@@@@@@@@@@@@@@@* #@. = //
// [email protected][email protected]@@@@@@@@@@@@@@@@@@. #+*@@@@@@@@@@@@@@@@@@: %# //
// ** :@@@@@@@@@@@@@@@@@@@* #::@@@@@@@@@@@@@@@@@@%[email protected]= //
// -# [email protected]@@@@@@@@@@@@@@@@@@@. +. @@@@@@@@@@@@@@@@@@@%.:%: //
// .#. [email protected]@@@@@@@@@@@@@@@@@@#@= .- %@@@@@@@@@@@@@@@@@%=#..*. //
// .*. -%@@@@@@@@@@@@@@@@@@*[email protected]+ %@@@@@@@@@@@@@@%#@@*.+= //
// =%@@@@@@@@@@@@@@@@@@@@:[email protected] @@@@@@@@@@@@@@@+ .=%* -: //
// .=#@@#=#@@@@@@@@@@@@@@@@@+ +% [email protected]@@@@@@@@@@@@@@@+ :+: //
// :+#%*=: .#@@@@@@@@@@@@@*%@@% #- *%[email protected]@@@@@@@@@@%-+%%= . //
// -==-: [email protected]#[email protected]@@@@@@@@@@@ [email protected]@. .* %.:@@@@@@@@@@@% .=*+=: //
// .+%*: [email protected]@@@@@@@@@@% [email protected]: - * [email protected]@@@@@@@@@@@. :-: //
// -*#- #@@@@@@@@@@@# #- . %%.%@@@@@@@@@+ //
// -=+-. *@@@@@@@@@@@* : [email protected]: [email protected]@@@@[email protected]@# //
// [email protected]@@@*#@@@@@* .%: #@@@@ .%@. //
// %@@@.:@@@.%% -. .%@@@ :@: //
// :@@@ #@@ [email protected] :@@@. *- //
// :%@- #@= #* :@@* =. //
// :+: [email protected]= =+ .#@+ //
// .+*: . :*%- //
// :. :. //
// //
// //
/////////////////////////////////////////////////////////////////////////////////////////////////////
/// @title: Steve Aoki NFT Forge Collection - Fresh Meat NFTs
/// @author: An NFT powered by Ether Cards - https://ether.cards
import "./burnNRedeem/ERC721BurnRedeem.sol";
import "./burnNRedeem/ERC721OwnerEnumerableSingleCreatorExtension.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./burnNRedeem/extensions/ICreatorExtensionTokenURI.sol";
contract FreshMeatForge is
ERC721BurnRedeem,
ERC721OwnerEnumerableSingleCreatorExtension,
ICreatorExtensionTokenURI
{
using Strings for uint256;
address public creator;
mapping(uint256 => bool) private claimed;
event forgeWith(uint16 _checkToken, uint16 _checkToken2, uint16 _burnToken);
event airDropTo(address _receiver);
string private _endpoint =
"https://client-metadata.ether.cards/api/aoki/FreshMeat/";
uint256 public forge_start = 1635350400; // (GMT): Wednesday, October 27, 2021 4:00:00 PM/ PDT 9 AM.
modifier forgeActive() {
require(block.timestamp >= forge_start, "not started.");
_;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(
ERC721BurnRedeem,
IERC165,
ERC721CreatorExtensionApproveTransfer
)
returns (bool)
{
return
interfaceId == type(ICreatorExtensionTokenURI).interfaceId ||
super.supportsInterface(interfaceId) ||
ERC721CreatorExtensionApproveTransfer.supportsInterface(
interfaceId
);
}
constructor(
address _creator, // 0x01Ba93514e5Eb642Ec63E95EF7787b0eDd403ADd
uint16 redemptionRate, // 1
uint16 redemptionMax // 40
)
ERC721OwnerEnumerableSingleCreatorExtension(_creator)
ERC721BurnRedeem(_creator, redemptionRate, redemptionMax)
{
creator = _creator;
}
/*
check whether can claim or not , if can claim return true.
*/
function checkClaim(uint256 _tokenID) public view returns (bool) {
//
bool checkRange = (425 <= _tokenID && _tokenID <= 504);
if (!checkRange) {
// not in range.
return false;
} else {
return (!claimed[_tokenID]); // check status. false by default. then become true after claim.
}
}
function setup() external onlyOwner {
super._activate();
}
function EmergencyAirdrop(address _to) external onlyOwner {
_mintRedemption(_to);
emit airDropTo(_to);
}
function forge(
uint16 _checkToken, // WelcomeToDominionX
uint16 _checkToken2, // Dreamcatcher
uint16 _burnToken // DistortedReality
) public forgeActive() {
// Attempt Burn
// Check that we can burn
require(425 <= _checkToken && _checkToken <= 464, "!W");
require(465 <= _checkToken2 && _checkToken2 <= 504, "!I");
require(redeemable(creator, _burnToken), "IT");
require(checkClaim(_checkToken) == true, "F1");
require(checkClaim(_checkToken2) == true, "F2");
// There is an invent in checkClaim.
// Restructure setup and to have the same interface.
claimed[_checkToken] = true;
claimed[_checkToken2] = true;
require(IERC721(creator).ownerOf(_checkToken) == msg.sender, "O1");
require(IERC721(creator).ownerOf(_checkToken2) == msg.sender, "O2");
require(IERC721(creator).ownerOf(_burnToken) == msg.sender, "O3");
require(
IERC721(creator).getApproved(_burnToken) == address(this),
"approval"
);
// Then burn
try
IERC721(creator).transferFrom(
msg.sender,
address(0xdEaD),
_burnToken
)
{} catch (bytes memory) {
revert("Bf");
}
// Mint reward
_mintRedemption(msg.sender);
emit forgeWith(_checkToken, _checkToken2, _burnToken);
}
// tokenURI extension
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(_mintNumbers[tokenId] != 0, "It");
return
string(
abi.encodePacked(
_endpoint,
uint256(int256(_mintNumbers[tokenId])).toString()
)
);
}
function tokenURI(address creator, uint256 tokenId)
public
view
override
returns (string memory)
{
return tokenURI(tokenId);
}
function drain(IERC20 _token) external onlyOwner {
if (address(_token) == 0x0000000000000000000000000000000000000000) {
payable(owner()).transfer(address(this).balance);
} else {
_token.transfer(owner(), _token.balanceOf(address(this)));
}
}
function retrieve721(address _tracker, uint256 _id) external onlyOwner {
IERC721(_tracker).transferFrom(address(this), msg.sender, _id);
}
function setTime(uint256 _time) external onlyOwner {
forge_start = _time;
}
function how_long_more()
public
view
returns (
uint256 Days,
uint256 Hours,
uint256 Minutes,
uint256 Seconds
)
{
require(block.timestamp < forge_start, "Started");
uint256 gap = forge_start - block.timestamp;
Days = gap / (24 * 60 * 60);
gap = gap % (24 * 60 * 60);
Hours = gap / (60 * 60);
gap = gap % (60 * 60);
Minutes = gap / 60;
Seconds = gap % 60;
return (Days, Hours, Minutes, Seconds);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./core/IERC721CreatorCore.sol";
import "./ERC721RedeemBase.sol";
import "./IERC721BurnRedeem.sol";
/**
* @dev Burn NFT's to receive another lazy minted NFT
*/
contract ERC721BurnRedeem is
ReentrancyGuard,
ERC721RedeemBase,
IERC721BurnRedeem
{
//using EnumerableSet for EnumerableSet.UintSet;
// mapping(address => mapping(uint256 => address)) private _recoverableERC721;
constructor(
address creator,
uint16 redemptionRate,
uint16 redemptionMax
) ERC721RedeemBase(creator, redemptionRate, redemptionMax) {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721RedeemBase, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721BurnRedeem).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721BurnRedeem-setERC721Recoverable}
*/
function setERC721Recoverable(
address contract_,
uint256 tokenId,
address recoverer
) external virtual override adminRequired {}
/**
* @dev See {IERC721BurnRedeem-recoverERC721}
*/
function recoverERC721(address contract_, uint256 tokenId)
external
virtual
override
{}
/**
* @dev See {IERC721BurnRedeem-redeemERC721}
function redeemERC721(
address[] calldata contracts,
uint256[] calldata tokenIds
) external virtual override nonReentrant {
require(
contracts.length == tokenIds.length,
"BurnRedeem: Invalid parameters"
);
require(
contracts.length == _redemptionRate,
"BurnRedeem: Incorrect number of NFTs being redeemed"
);
// Attempt Burn
for (uint256 i = 0; i < contracts.length; i++) {
// Check that we can burn
require(
redeemable(contracts[i], tokenIds[i]),
"BurnRedeem: Invalid NFT"
);
try IERC721(contracts[i]).ownerOf(tokenIds[i]) returns (
address ownerOfAddress
) {
require(
ownerOfAddress == msg.sender,
"BurnRedeem: Caller must own NFTs"
);
} catch (bytes memory) {
revert("BurnRedeem: Bad token contract");
}
try IERC721(contracts[i]).getApproved(tokenIds[i]) returns (
address approvedAddress
) {
require(
approvedAddress == address(this),
"BurnRedeem: Contract must be given approval to burn NFT"
);
} catch (bytes memory) {
revert("BurnRedeem: Bad token contract");
}
// Then burn
try
IERC721(contracts[i]).transferFrom(
msg.sender,
address(0xdEaD),
tokenIds[i]
)
{} catch (bytes memory) {
revert("BurnRedeem: Burn failure");
}
}
// Mint reward
_mintRedemption(msg.sender);
}
/**
* @dev See {IERC721Receiver-onERC721Received}.
*/
function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata data
) external override nonReentrant returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./core/IERC721CreatorCore.sol";
import "./extensions/ERC721/ERC721CreatorExtensionApproveTransfer.sol";
import "./libraries/SingleCreatorBase.sol";
/**
* Provide token enumeration functionality (Base Class. Use if you are using multiple inheritance where other contracts
* already derive from either ERC721SingleCreatorExtension or ERC1155SingleCreatorExtension).
*
* IMPORTANT: You must call _activate in order for enumeration to work
*/
abstract contract ERC721OwnerEnumerableSingleCreatorBase is
SingleCreatorBase,
ERC721CreatorExtensionApproveTransfer
{
mapping(address => uint256) private _ownerBalance;
mapping(address => mapping(uint256 => uint256)) private _tokensByOwner;
mapping(uint256 => uint256) private _tokensIndex;
/**
* @dev must call this to activate enumeration capability
*/
function _activate() internal {
IERC721CreatorCore(_creator).setApproveTransferExtension(true);
}
/**
* @dev Get the token for an owner by index
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
returns (uint256)
{
require(
index < _ownerBalance[owner],
"ERC721Enumerable: owner index out of bounds"
);
return _tokensByOwner[owner][index];
}
/**
* @dev Get the balance for the owner for this extension
*/
function balanceOf(address owner) public view virtual returns (uint256) {
return _ownerBalance[owner];
}
function approveTransfer(
address from,
address to,
uint256 tokenId
) external override returns (bool) {
require(msg.sender == _creator, "Invalid caller");
if (from != address(0) && from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to != address(0) && to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
return true;
}
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = _ownerBalance[to];
_tokensByOwner[to][length] = tokenId;
_tokensIndex[tokenId] = length;
_ownerBalance[to] += 1;
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _ownerBalance[from] - 1;
uint256 tokenIndex = _tokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _tokensByOwner[from][lastTokenIndex];
_tokensByOwner[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_tokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _tokensIndex[tokenId];
delete _tokensByOwner[from][lastTokenIndex];
_ownerBalance[from] -= 1;
}
}
/**
* Provide token enumeration functionality (Extension)
*
* IMPORTANT: You must call _activate in order for enumeration to work
*/
abstract contract ERC721OwnerEnumerableSingleCreatorExtension is
ERC721OwnerEnumerableSingleCreatorBase,
ERC721SingleCreatorExtension
{
constructor(address creator) ERC721SingleCreatorExtension(creator) {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Implement this if you want your extension to have overloadable URI's
*/
interface ICreatorExtensionTokenURI is IERC165 {
/**
* Get the uri for a given creator/tokenId
*/
function tokenURI(address creator, uint256 tokenId)
external
view
returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, type(IERC165).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165(account).supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value 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.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value 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(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value 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(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value 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(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value 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(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "./ICreatorCore.sol";
/**
* @dev Core ERC721 creator interface
*/
interface IERC721CreatorCore is ICreatorCore {
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to) external returns (uint256);
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to, string calldata uri)
external
returns (uint256);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, uint16 count)
external
returns (uint256[] memory);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, string[] calldata uris)
external
returns (uint256[] memory);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to) external returns (uint256);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to, string calldata uri)
external
returns (uint256);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenIds minted
*/
function mintExtensionBatch(address to, uint16 count)
external
returns (uint256[] memory);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtensionBatch(address to, string[] calldata uris)
external
returns (uint256[] memory);
/**
* @dev burn a token. Can only be called by token owner or approved address.
* On burn, calls back to the registered extension's onBurn method
*/
function burn(uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "./core/IERC721CreatorCore.sol";
import "./extensions/CreatorExtension.sol";
import "./libraries/LegacyInterfaces.sol";
import "./RedeemBase.sol";
import "./IERC721RedeemBase.sol";
/**
* @dev Burn NFT's to receive another lazy minted NFT
*/
abstract contract ERC721RedeemBase is
RedeemBase,
CreatorExtension,
IERC721RedeemBase
{
// The creator mint contract
address private _creator;
uint16 internal immutable _redemptionRate;
uint16 private _redemptionMax;
uint16 private _redemptionCount;
uint256[] private _mintedTokens;
mapping(uint256 => uint256) internal _mintNumbers;
constructor(
address creator,
uint16 redemptionRate_,
uint16 redemptionMax_
) {
require(
ERC165Checker.supportsInterface(
creator,
type(IERC721CreatorCore).interfaceId
) ||
ERC165Checker.supportsInterface(
creator,
LegacyInterfaces.IERC721CreatorCore_v1
),
"Redeem: Minting reward contract must implement IERC721CreatorCore"
);
_redemptionRate = redemptionRate_;
_redemptionMax = redemptionMax_;
_creator = creator;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(RedeemBase, CreatorExtension, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721RedeemBase).interfaceId ||
RedeemBase.supportsInterface(interfaceId) ||
CreatorExtension.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721RedeemBase-redemptionMax}
*/
function redemptionMax() external view virtual override returns (uint16) {
return _redemptionMax;
}
/**
* @dev See {IERC721RedeemBase-redemptionRate}
*/
function redemptionRate() external view virtual override returns (uint16) {
return _redemptionRate;
}
/**
* @dev See {IERC721RedeemBase-redemptionRemaining}
*/
function redemptionRemaining()
external
view
virtual
override
returns (uint16)
{
return _redemptionMax - _redemptionCount;
}
/**
* @dev See {IERC721RedeemBase-mintNumber}.
*/
function mintNumber(uint256 tokenId)
external
view
virtual
override
returns (uint256)
{
return _mintNumbers[tokenId];
}
/**
* @dev See {IERC721RedeemBase-mintedTokens}.
*/
function mintedTokens() external view override returns (uint256[] memory) {
return _mintedTokens;
}
/**
* @dev mint token that was redeemed for
*/
function _mintRedemption(address to) internal {
require(
_redemptionCount < _redemptionMax,
"Redeem: No redemptions remaining"
);
_redemptionCount++;
// Mint token
uint256 tokenId = _mint(to, _redemptionCount);
_mintedTokens.push(tokenId);
_mintNumbers[tokenId] = _redemptionCount;
}
/**
* @dev override if you want to perform different mint functionality
*/
function _mint(address to, uint16) internal returns (uint256) {
return IERC721CreatorCore(_creator).mintExtension(to);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "./IERC721RedeemBase.sol";
/**
* @dev Burn NFT's to receive another lazy minted NFT
*/
interface IERC721BurnRedeem is IERC721RedeemBase, IERC721Receiver {
/**
* @dev Enable recovery of a given token. Can only be called by contract owner/admin.
* This is a special function used in case someone accidentally sends a token to this contract.
*/
function setERC721Recoverable(
address contract_,
uint256 tokenId,
address recoverer
) external;
/**
* @dev Recover a token. Returns it to the recoverer set by setERC721Recoverable
* This is a special function used in case someone accidentally sends a token to this contract.
*/
function recoverERC721(address contract_, uint256 tokenId) external;
/**
* @dev Redeem ERC721 tokens for redemption reward NFT.
* Requires the user to grant approval beforehand by calling contract's 'approve' function.
* If the it cannot redeem the NFT, it will clear approvals
function redeemERC721(
address[] calldata contracts,
uint256[] calldata tokenIds
) external;
*/
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Core creator interface
*/
interface ICreatorCore is IERC165 {
event ExtensionRegistered(
address indexed extension,
address indexed sender
);
event ExtensionUnregistered(
address indexed extension,
address indexed sender
);
event ExtensionBlacklisted(
address indexed extension,
address indexed sender
);
event MintPermissionsUpdated(
address indexed extension,
address indexed permissions,
address indexed sender
);
event RoyaltiesUpdated(
uint256 indexed tokenId,
address payable[] receivers,
uint256[] basisPoints
);
event DefaultRoyaltiesUpdated(
address payable[] receivers,
uint256[] basisPoints
);
event ExtensionRoyaltiesUpdated(
address indexed extension,
address payable[] receivers,
uint256[] basisPoints
);
event ExtensionApproveTransferUpdated(
address indexed extension,
bool enabled
);
/**
* @dev gets address of all extensions
*/
function getExtensions() external view returns (address[] memory);
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI)
external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(
address extension,
string calldata baseURI,
bool baseURIIdentical
) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* Returns True if removed, False if already removed.
*/
function unregisterExtension(address extension) external;
/**
* @dev blacklist an extension. Can only be called by contract owner or admin.
* This function will destroy all ability to reference the metadata of any tokens created
* by the specified extension. It will also unregister the extension if needed.
* Returns True if removed, False if already removed.
*/
function blacklistExtension(address extension) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
*/
function setBaseTokenURIExtension(string calldata uri) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURIExtension(string calldata uri, bool identical)
external;
/**
* @dev set the common prefix of an extension. Can only be called by extension.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefixExtension(string calldata prefix) external;
/**
* @dev set the tokenURI of a token extension. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri)
external;
/**
* @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token.
*/
function setTokenURIExtension(
uint256[] memory tokenId,
string[] calldata uri
) external;
/**
* @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURI(string calldata uri) external;
/**
* @dev set the common prefix for tokens with no extension. Can only be called by owner/admin.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris)
external;
/**
* @dev set a permissions contract for an extension. Used to control minting.
*/
function setMintPermissions(address extension, address permissions)
external;
/**
* @dev Configure so transfers of tokens created by the caller (must be extension) gets approval
* from the extension before transferring
*/
function setApproveTransferExtension(bool enabled) external;
/**
* @dev get the extension of a given token
*/
function tokenExtension(uint256 tokenId) external view returns (address);
/**
* @dev Set default royalties
*/
function setRoyalties(
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Set royalties of a token
*/
function setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Set royalties of an extension
*/
function setRoyaltiesExtension(
address extension,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Get royalites of a token. Returns list of receivers and basisPoints
*/
function getRoyalties(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
// Royalty support for various other standards
function getFeeRecipients(uint256 tokenId)
external
view
returns (address payable[] memory);
function getFeeBps(uint256 tokenId)
external
view
returns (uint256[] memory);
function getFees(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
function royaltyInfo(uint256 tokenId, uint256 value)
external
view
returns (address, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Base creator extension variables
*/
abstract contract CreatorExtension is ERC165 {
/**
* @dev Legacy extension interface identifiers
*
* {IERC165-supportsInterface} needs to return 'true' for this interface
* in order backwards compatible with older creator contracts
*/
bytes4 internal constant LEGACY_EXTENSION_INTERFACE = 0x7005caad;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165)
returns (bool)
{
return
interfaceId == LEGACY_EXTENSION_INTERFACE ||
super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: BSD-4-Clause
pragma solidity ^0.8.0;
/// @author: manifold.xyz
/**
* Library of legacy interface constants
*/
library LegacyInterfaces {
// LEGACY ERC721CreatorCore interface
bytes4 internal constant IERC721CreatorCore_v1 = 0x478c8530;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./access/AdminControl.sol";
import "./IRedeemBase.sol";
struct range {
uint256 min;
uint256 max;
}
/**
* @dev Burn NFT's to receive another lazy minted NFT
*/
abstract contract RedeemBase is AdminControl, IRedeemBase {
using EnumerableSet for EnumerableSet.UintSet;
// approved contract tokens
mapping(address => bool) private _approvedContracts;
// approved specific tokens
mapping(address => EnumerableSet.UintSet) private _approvedTokens;
mapping(address => range[]) private _approvedTokenRange;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AdminControl, IERC165)
returns (bool)
{
return
interfaceId == type(IRedeemBase).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IRedeemBase-updateApprovedContracts}
*/
function updateApprovedContracts(
address[] memory contracts,
bool[] memory approved
) public virtual override adminRequired {
require(
contracts.length == approved.length,
"Redeem: Invalid input parameters"
);
for (uint256 i = 0; i < contracts.length; i++) {
_approvedContracts[contracts[i]] = approved[i];
}
emit UpdateApprovedContracts(contracts, approved);
}
/**
* @dev See {IRedeemBase-updateApprovedTokens}
*/
function updateApprovedTokens(
address contract_,
uint256[] memory tokenIds,
bool[] memory approved
) public virtual override adminRequired {
require(
tokenIds.length == approved.length,
"Redeem: Invalid input parameters"
);
for (uint256 i = 0; i < tokenIds.length; i++) {
if (
approved[i] && !_approvedTokens[contract_].contains(tokenIds[i])
) {
_approvedTokens[contract_].add(tokenIds[i]);
} else if (
!approved[i] && _approvedTokens[contract_].contains(tokenIds[i])
) {
_approvedTokens[contract_].remove(tokenIds[i]);
}
}
emit UpdateApprovedTokens(contract_, tokenIds, approved);
}
/**
* @dev See {IRedeemBase-updateApprovedTokenRanges}
*/
function updateApprovedTokenRanges(
address contract_,
uint256[] memory minTokenIds,
uint256[] memory maxTokenIds
) public virtual override adminRequired {
require(
minTokenIds.length == maxTokenIds.length,
"Redeem: Invalid input parameters"
);
uint256 existingRangesLength = _approvedTokenRange[contract_].length;
for (uint256 i = 0; i < existingRangesLength; i++) {
_approvedTokenRange[contract_][i].min = 0;
_approvedTokenRange[contract_][i].max = 0;
}
for (uint256 i = 0; i < minTokenIds.length; i++) {
require(
minTokenIds[i] < maxTokenIds[i],
"Redeem: min must be less than max"
);
if (i < existingRangesLength) {
_approvedTokenRange[contract_][i].min = minTokenIds[i];
_approvedTokenRange[contract_][i].max = maxTokenIds[i];
} else {
_approvedTokenRange[contract_].push(
range(minTokenIds[i], maxTokenIds[i])
);
}
}
emit UpdateApprovedTokenRanges(contract_, minTokenIds, maxTokenIds);
}
/**
* @dev See {IRedeemBase-redeemable}
*/
function redeemable(address contract_, uint256 tokenId)
public
view
virtual
override
returns (bool)
{
if (_approvedContracts[contract_]) {
return true;
}
if (_approvedTokens[contract_].contains(tokenId)) {
return true;
}
if (_approvedTokenRange[contract_].length > 0) {
for (
uint256 i = 0;
i < _approvedTokenRange[contract_].length;
i++
) {
if (
_approvedTokenRange[contract_][i].max != 0 &&
tokenId >= _approvedTokenRange[contract_][i].min &&
tokenId <= _approvedTokenRange[contract_][i].max
) {
return true;
}
}
}
return false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "./IRedeemBase.sol";
/**
* @dev Base redemption interface
*/
interface IERC721RedeemBase is IRedeemBase {
/**
* @dev Get the max number of redemptions
*/
function redemptionMax() external view returns (uint16);
/**
* @dev Get the redemption rate
*/
function redemptionRate() external view returns (uint16);
/**
* @dev Get number of redemptions left
*/
function redemptionRemaining() external view returns (uint16);
/**
* @dev Get the mint number of a created token id
*/
function mintNumber(uint256 tokenId) external view returns (uint256);
/**
* @dev Get list of all minted tokens
*/
function mintedTokens() external view returns (uint256[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IAdminControl.sol";
abstract contract AdminControl is Ownable, IAdminControl, ERC165 {
using EnumerableSet for EnumerableSet.AddressSet;
// Track registered admins
EnumerableSet.AddressSet private _admins;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IAdminControl).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Only allows approved admins to call the specified function
*/
modifier adminRequired() {
require(
owner() == msg.sender || _admins.contains(msg.sender),
"AdminControl: Must be owner or admin"
);
_;
}
/**
* @dev See {IAdminControl-getAdmins}.
*/
function getAdmins()
external
view
override
returns (address[] memory admins)
{
admins = new address[](_admins.length());
for (uint256 i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
return admins;
}
/**
* @dev See {IAdminControl-approveAdmin}.
*/
function approveAdmin(address admin) external override onlyOwner {
if (!_admins.contains(admin)) {
emit AdminApproved(admin, msg.sender);
_admins.add(admin);
}
}
/**
* @dev See {IAdminControl-revokeAdmin}.
*/
function revokeAdmin(address admin) external override onlyOwner {
if (_admins.contains(admin)) {
emit AdminRevoked(admin, msg.sender);
_admins.remove(admin);
}
}
/**
* @dev See {IAdminControl-isAdmin}.
*/
function isAdmin(address admin) public view override returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "./access/IAdminControl.sol";
/**
* @dev Base redemption interface
*/
interface IRedeemBase is IAdminControl {
event UpdateApprovedContracts(address[] contracts, bool[] approved);
event UpdateApprovedTokens(
address contract_,
uint256[] tokenIds,
bool[] approved
);
event UpdateApprovedTokenRanges(
address contract_,
uint256[] minTokenIds,
uint256[] maxTokenIds
);
/**
* @dev Update approved contracts that can be used to redeem. Can only be called by contract owner/admin.
*/
function updateApprovedContracts(
address[] calldata contracts,
bool[] calldata approved
) external;
/**
* @dev Update approved tokens that can be used to redeem. Can only be called by contract owner/admin.
*/
function updateApprovedTokens(
address contract_,
uint256[] calldata tokenIds,
bool[] calldata approved
) external;
/**
* @dev Update approved token ranges that can be used to redeem. Can only be called by contract owner/admin.
* Clears out old ranges
*/
function updateApprovedTokenRanges(
address contract_,
uint256[] calldata minTokenIds,
uint256[] calldata maxTokenIds
) external;
/**
* @dev Check if an NFT is redeemable
*/
function redeemable(address contract_, uint256 tokenId)
external
view
returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Interface for admin control
*/
interface IAdminControl is IERC165 {
event AdminApproved(address indexed account, address indexed sender);
event AdminRevoked(address indexed account, address indexed sender);
/**
* @dev gets address of all admins
*/
function getAdmins() external view returns (address[] memory);
/**
* @dev add an admin. Can only be called by contract owner.
*/
function approveAdmin(address admin) external;
/**
* @dev remove an admin. Can only be called by contract owner.
*/
function revokeAdmin(address admin) external;
/**
* @dev checks whether or not given address is an admin
* Returns True if they are
*/
function isAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "../../access/AdminControl.sol";
import "../../core/IERC721CreatorCore.sol";
import "./ERC721CreatorExtension.sol";
import "./IERC721CreatorExtensionApproveTransfer.sol";
/**
* @dev Suggested implementation for extensions that require the creator to
* check with it before a transfer occurs
*/
abstract contract ERC721CreatorExtensionApproveTransfer is
AdminControl,
ERC721CreatorExtension,
IERC721CreatorExtensionApproveTransfer
{
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AdminControl, CreatorExtension, IERC165)
returns (bool)
{
return
interfaceId ==
type(IERC721CreatorExtensionApproveTransfer).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721CreatorExtensionApproveTransfer-setApproveTransfer}
*/
function setApproveTransfer(address creator, bool enabled)
external
override
adminRequired
{
require(
ERC165Checker.supportsInterface(
creator,
type(IERC721CreatorCore).interfaceId
),
"creator must implement IERC721CreatorCore"
);
IERC721CreatorCore(creator).setApproveTransferExtension(enabled);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "../core/IERC721CreatorCore.sol";
import "./LegacyInterfaces.sol";
abstract contract SingleCreatorBase {
address internal _creator;
}
/**
* @dev Extension that only uses a single creator contract instance
*/
abstract contract ERC721SingleCreatorExtension is SingleCreatorBase {
constructor(address creator) {
require(
ERC165Checker.supportsInterface(
creator,
type(IERC721CreatorCore).interfaceId
) ||
ERC165Checker.supportsInterface(
creator,
LegacyInterfaces.IERC721CreatorCore_v1
),
"Redeem: Minting reward contract must implement IERC721CreatorCore"
);
_creator = creator;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "../CreatorExtension.sol";
/**
* @dev Base ERC721 creator extension variables
*/
abstract contract ERC721CreatorExtension is CreatorExtension {
/**
* @dev Legacy extension interface identifiers (see CreatorExtension for more)
*
* {IERC165-supportsInterface} needs to return 'true' for this interface
* in order backwards compatible with older creator contracts
*/
// Required to be recognized as a contract to receive onBurn for older creator contracts
bytes4 internal constant LEGACY_ERC721_EXTENSION_BURNABLE_INTERFACE =
0xf3f4e68b;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* Implement this if you want your extension to approve a transfer
*/
interface IERC721CreatorExtensionApproveTransfer is IERC165 {
/**
* @dev Set whether or not the creator will check the extension for approval of token transfer
*/
function setApproveTransfer(address creator, bool enabled) external;
/**
* @dev Called by creator contract to approve a transfer
*/
function approveTransfer(
address from,
address to,
uint256 tokenId
) external returns (bool);
} | Core creator interface/ Royalty support for various other standards | interface ICreatorCore is IERC165 {
event ExtensionRegistered(
address indexed extension,
address indexed sender
);
event ExtensionUnregistered(
address indexed extension,
address indexed sender
);
event ExtensionBlacklisted(
address indexed extension,
address indexed sender
);
event MintPermissionsUpdated(
address indexed extension,
address indexed permissions,
address indexed sender
);
event RoyaltiesUpdated(
uint256 indexed tokenId,
address payable[] receivers,
uint256[] basisPoints
);
event DefaultRoyaltiesUpdated(
address payable[] receivers,
uint256[] basisPoints
);
event ExtensionRoyaltiesUpdated(
address indexed extension,
address payable[] receivers,
uint256[] basisPoints
);
event ExtensionApproveTransferUpdated(
address indexed extension,
bool enabled
);
function getExtensions() external view returns (address[] memory);
function registerExtension(address extension, string calldata baseURI)
external;
function registerExtension(
address extension,
string calldata baseURI,
bool baseURIIdentical
) external;
function unregisterExtension(address extension) external;
function blacklistExtension(address extension) external;
function setBaseTokenURIExtension(string calldata uri) external;
function setBaseTokenURIExtension(string calldata uri, bool identical)
external;
function setTokenURIPrefixExtension(string calldata prefix) external;
function setTokenURIExtension(uint256 tokenId, string calldata uri)
external;
function setTokenURIExtension(
uint256[] memory tokenId,
string[] calldata uri
) external;
function setBaseTokenURI(string calldata uri) external;
function setTokenURIPrefix(string calldata prefix) external;
function setTokenURI(uint256 tokenId, string calldata uri) external;
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris)
external;
function setMintPermissions(address extension, address permissions)
external;
function setApproveTransferExtension(bool enabled) external;
function tokenExtension(uint256 tokenId) external view returns (address);
function setRoyalties(
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
function setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
function setRoyaltiesExtension(
address extension,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
function getRoyalties(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
function getFeeRecipients(uint256 tokenId)
external
view
returns (address payable[] memory);
function getFeeBps(uint256 tokenId)
external
view
returns (uint256[] memory);
function getFees(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
function royaltyInfo(uint256 tokenId, uint256 value)
external
view
returns (address, uint256);
}
}
| 1,513,056 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./interfaces.sol";
contract InstaVaultResolver {
address internal constant wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
VaultInterface public immutable vault;
struct VaultInfo {
address vaultAddr;
address vaultDsa;
uint256 revenue;
uint256 revenueFee;
VaultInterface.Ratios ratios;
uint256 lastRevenueExchangePrice;
uint256 exchangePrice;
uint256 totalSupply;
uint netCollateral;
uint netBorrow;
VaultInterface.BalVariables balances;
uint netSupply;
uint netBal;
}
function getVaultInfo()
public
view
returns (VaultInfo memory vaultInfo_)
{
vaultInfo_.vaultAddr = address(vault);
vaultInfo_.vaultDsa = vault.vaultDsa();
vaultInfo_.revenue = vault.revenue();
vaultInfo_.revenueFee = vault.revenueFee();
vaultInfo_.ratios = vault.ratios();
vaultInfo_.lastRevenueExchangePrice = vault.lastRevenueExchangePrice();
(vaultInfo_.exchangePrice,) = vault.getCurrentExchangePrice();
vaultInfo_.totalSupply = vault.totalSupply();
(vaultInfo_.netCollateral, vaultInfo_.netBorrow, vaultInfo_.balances, vaultInfo_.netSupply, vaultInfo_.netBal) = vault.netAssets();
}
function getUserInfo(address user_)
public
view
returns (
VaultInfo memory vaultInfo_,
uint256 vtokenBal_,
uint256 amount_
)
{
vaultInfo_ = getVaultInfo();
vtokenBal_ = vault.balanceOf(user_);
amount_ = (vtokenBal_ * vaultInfo_.exchangePrice) / 1e18;
}
struct RefinanceOneVariables {
uint netCollateral;
uint netBorrow;
VaultInterface.BalVariables balances;
uint netBal;
uint netStEth;
int netWeth;
uint ratio;
uint targetRatioDif;
}
// This function gives data around leverage position
function refinanceOneData() public view returns (
uint finalCol_,
uint finalDebt_,
address flashTkn_,
uint flashAmt_,
uint excessDebt_,
uint paybackDebt_,
uint totalAmountToSwap_,
uint extraWithdraw_,
bool isRisky_
) {
RefinanceOneVariables memory v_;
(v_.netCollateral, v_.netBorrow, v_.balances, , v_.netBal) = vault.netAssets();
if (v_.balances.wethVaultBal <= 1e14) v_.balances.wethVaultBal = 0;
if (v_.balances.stethVaultBal <= 1e14) v_.balances.stethVaultBal = 0;
VaultInterface.Ratios memory ratios_ = vault.ratios();
v_.netStEth = v_.netCollateral + v_.balances.stethVaultBal + v_.balances.stethDsaBal;
v_.netWeth = int(v_.balances.wethVaultBal + v_.balances.wethDsaBal) - int(v_.netBorrow);
v_.ratio = v_.netWeth < 0 ? (uint(-v_.netWeth) * 1e4) / v_.netStEth : 0;
v_.targetRatioDif = 10000 - (ratios_.minLimit - 10); // taking 0.1% more dif for margin
if (v_.ratio < ratios_.minLimitGap) {
// leverage till minLimit <> minLimitGap
// final difference between collateral & debt in percent
finalCol_ = (v_.netBal * 1e4) / v_.targetRatioDif;
finalDebt_ = finalCol_ - v_.netBal;
excessDebt_ = finalDebt_ - v_.netBorrow;
flashTkn_ = wethAddr;
flashAmt_ = (v_.netCollateral / 10) + (excessDebt_ * 10 / 8); // 10% of current collateral + excessDebt / 0.8
totalAmountToSwap_ = excessDebt_ + v_.balances.wethVaultBal + v_.balances.wethDsaBal;
// keeping as non collateral for easier withdrawals
extraWithdraw_ = finalCol_ - ((finalDebt_ * 1e4) / (ratios_.maxLimit - 10));
} else {
finalCol_ = v_.netStEth;
finalDebt_ = uint(-v_.netWeth);
paybackDebt_ = v_.balances.wethVaultBal + v_.balances.wethDsaBal;
if (v_.ratio < (ratios_.maxLimit - 10)) {
extraWithdraw_ = finalCol_ - ((finalDebt_ * 1e4) / (ratios_.maxLimit - 10));
}
}
if (v_.ratio > ratios_.maxLimit) {
isRisky_ = true;
}
if (excessDebt_ < 1e14) excessDebt_ = 0;
if (paybackDebt_ < 1e14) paybackDebt_ = 0;
if (totalAmountToSwap_ < 1e14) totalAmountToSwap_ = 0;
if (extraWithdraw_ < 1e14) extraWithdraw_ = 0;
}
constructor(address vaultAddr_) {
vault = VaultInterface(vaultAddr_);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
interface VaultInterface {
function balanceOf(address account) external view returns (uint256);
function getCurrentExchangePrice()
external
view
returns (
uint256 exchangePrice_,
uint256 newRevenue_
);
struct BalVariables {
uint wethVaultBal;
uint wethDsaBal;
uint stethVaultBal;
uint stethDsaBal;
uint totalBal;
}
function netAssets() external view returns (
uint netCollateral_,
uint netBorrow_,
BalVariables memory balances_,
uint netSupply_,
uint netBal_
);
struct Ratios {
uint16 maxLimit; // Above this withdrawals are not allowed
uint16 minLimit; // After leverage the ratio should be below minLimit & above minLimitGap
uint16 minLimitGap;
// send borrow rate in 4 decimals from UI. In the smart contract it'll convert to 27 decimals which where is 100%
uint128 maxBorrowRate; // maximum borrow rate above this leveraging should not happen
}
// maximum borrow rate. If above this limit then leverage won't happen
function ratios() external view returns (Ratios memory);
function vaultDsa() external view returns (address);
function lastRevenueExchangePrice() external view returns (uint256);
function revenueFee() external view returns (uint256);
function revenue() external view returns (uint256);
function totalSupply() external view returns (uint256);
} | This function gives data around leverage position leverage till minLimit <> minLimitGap final difference between collateral & debt in percent keeping as non collateral for easier withdrawals | function refinanceOneData() public view returns (
uint finalCol_,
uint finalDebt_,
address flashTkn_,
uint flashAmt_,
uint excessDebt_,
uint paybackDebt_,
uint totalAmountToSwap_,
uint extraWithdraw_,
bool isRisky_
) {
RefinanceOneVariables memory v_;
(v_.netCollateral, v_.netBorrow, v_.balances, , v_.netBal) = vault.netAssets();
if (v_.balances.wethVaultBal <= 1e14) v_.balances.wethVaultBal = 0;
if (v_.balances.stethVaultBal <= 1e14) v_.balances.stethVaultBal = 0;
VaultInterface.Ratios memory ratios_ = vault.ratios();
v_.netStEth = v_.netCollateral + v_.balances.stethVaultBal + v_.balances.stethDsaBal;
v_.netWeth = int(v_.balances.wethVaultBal + v_.balances.wethDsaBal) - int(v_.netBorrow);
v_.ratio = v_.netWeth < 0 ? (uint(-v_.netWeth) * 1e4) / v_.netStEth : 0;
if (v_.ratio < ratios_.minLimitGap) {
finalCol_ = (v_.netBal * 1e4) / v_.targetRatioDif;
finalDebt_ = finalCol_ - v_.netBal;
excessDebt_ = finalDebt_ - v_.netBorrow;
flashTkn_ = wethAddr;
totalAmountToSwap_ = excessDebt_ + v_.balances.wethVaultBal + v_.balances.wethDsaBal;
extraWithdraw_ = finalCol_ - ((finalDebt_ * 1e4) / (ratios_.maxLimit - 10));
finalCol_ = v_.netStEth;
finalDebt_ = uint(-v_.netWeth);
paybackDebt_ = v_.balances.wethVaultBal + v_.balances.wethDsaBal;
if (v_.ratio < (ratios_.maxLimit - 10)) {
extraWithdraw_ = finalCol_ - ((finalDebt_ * 1e4) / (ratios_.maxLimit - 10));
}
}
if (v_.ratio > ratios_.maxLimit) {
isRisky_ = true;
}
if (excessDebt_ < 1e14) excessDebt_ = 0;
if (paybackDebt_ < 1e14) paybackDebt_ = 0;
if (totalAmountToSwap_ < 1e14) totalAmountToSwap_ = 0;
if (extraWithdraw_ < 1e14) extraWithdraw_ = 0;
}
| 278,130 |
./full_match/137/0xbD0c6c0245b71B523Da8c9F5aC6ea0723371e964/sources/contracts/SToken.sol | transferForm is transfered from an address to another address. - from: the address is the sender address - to: transfer to the receiver address - amount: transfer amount to the receiver address Ref: https:docs.openzeppelin.com/contracts/2.x/api/token/erc20IERC20-transferFrom-address-address-uint256- | function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
require(isBlackListed[msg.sender] != true, "TransferFrom: User in the blacklist");
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
| 4,695,356 |
./partial_match/97/0xa4C49Ea0FC0cA511B9a7d4678a5711815f16163b/sources/Bank.sol | Create a new farming position to unlock your yield farming potential. id The ID of the position to unlock the earning. Use ZERO for new position. goblin The address of the authorized goblin to work for this position. loan The amount of ETH to borrow from the pool. maxReturn The max amount of ETH to return to the pool. data The calldata to pass along to the goblin for more working context. 1. Sanity check the input position, or add a new position of ID is 0. | function work(uint256 id, address goblin, uint256 loan, uint256 maxReturn, bytes calldata data)
external payable
onlyEOA accrue(msg.value) nonReentrant
{
if (id == 0) {
id = nextPositionID++;
positions[id].goblin = goblin;
positions[id].owner = msg.sender;
require(id < nextPositionID, "bad position id");
require(positions[id].goblin == goblin, "bad position goblin");
require(positions[id].owner == msg.sender, "not position owner");
}
emit Work(id, loan);
require(loan == 0 || config.acceptDebt(goblin), "goblin not accept more debt");
uint256 debt = _removeDebt(id).add(loan);
{
uint256 sendETH = msg.value.add(loan);
require(sendETH <= address(this).balance, "insufficient BNB in the bank");
uint256 beforeETH = address(this).balance.sub(sendETH);
Goblin(goblin).work.value(sendETH)(id, msg.sender, debt, data);
back = address(this).balance.sub(beforeETH);
}
debt = debt.sub(lessDebt);
if (debt > 0) {
require(debt >= config.minDebtSize(), "too small debt size");
uint256 health = Goblin(goblin).health(id);
uint256 workFactor = config.workFactor(goblin, debt);
require(health.mul(workFactor) >= debt.mul(10000), "bad work factor");
_addDebt(id, debt);
}
}
| 11,449,329 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.8.0;
import "./IBeneficiaryVaults.sol";
import "./IBeneficiaryRegistry.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
contract BeneficiaryVaults is IBeneficiaryVaults, Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public immutable pop;
IBeneficiaryRegistry public beneficiaryRegistry;
uint256 public totalVaultedBalance = 0;
Vault[3] private vaults;
enum VaultStatus {Initialized, Open, Closed}
struct Vault {
uint256 totalAllocated;
uint256 currentBalance;
uint256 unclaimedShare;
mapping(address => bool) claimed;
bytes32 merkleRoot;
uint256 endTime;
VaultStatus status;
}
event VaultInitialized(uint8 vaultId, bytes32 merkleRoot);
event VaultOpened(uint8 vaultId);
event VaultClosed(uint8 vaultId);
event RewardsDistributed(uint256 amount);
event RewardAllocated(uint8 vaultId, uint256 amount);
event RewardClaimed(uint8 vaultId, address beneficiary, uint256 amount);
event BeneficiaryRegistryChanged(
IBeneficiaryRegistry from,
IBeneficiaryRegistry to
);
modifier vaultExists(uint8 vaultId_) {
require(vaultId_ < 3, "Invalid vault id");
require(vaults[vaultId_].endTime > 0, "Uninitialized vault slot");
_;
}
constructor(IERC20 pop_, IBeneficiaryRegistry beneficiaryRegistry_) {
pop = pop_;
beneficiaryRegistry = beneficiaryRegistry_;
}
/**
* @notice Overrides existing BeneficiaryRegistry contract
* @param beneficiaryRegistry_ Address of new BeneficiaryRegistry contract
* @dev Must implement IBeneficiaryRegistry and cannot be same as existing
*/
function setBeneficiaryRegistry(IBeneficiaryRegistry beneficiaryRegistry_)
public
onlyOwner
{
require(
beneficiaryRegistry != beneficiaryRegistry_,
"Same BeneficiaryRegistry"
);
IBeneficiaryRegistry _beneficiaryRegistry = beneficiaryRegistry;
beneficiaryRegistry = beneficiaryRegistry_;
emit BeneficiaryRegistryChanged(_beneficiaryRegistry, beneficiaryRegistry);
}
/**
* @notice Initializes a vault for beneficiary claims
* @param vaultId_ Vault ID in range 0-2
* @param endTime_ Unix timestamp in seconds after which a vault can be closed
* @param merkleRoot_ Merkle root to support claims
* @dev Vault cannot be initialized if it is currently in an open state, otherwise existing data is reset*
*/
function initializeVault(
uint8 vaultId_,
uint256 endTime_,
bytes32 merkleRoot_
) public onlyOwner {
require(vaultId_ < 3, "Invalid vault id");
require(endTime_ > block.timestamp, "Invalid end block");
require(
vaults[vaultId_].status != VaultStatus.Open,
"Vault must not be open"
);
delete vaults[vaultId_];
Vault storage v = vaults[vaultId_];
v.totalAllocated = 0;
v.currentBalance = 0;
v.unclaimedShare = 100e18;
v.merkleRoot = merkleRoot_;
v.endTime = endTime_;
v.status = VaultStatus.Initialized;
emit VaultInitialized(vaultId_, merkleRoot_);
}
/**
* @notice Open a vault it can receive rewards and accept claims
* @dev Vault must be in an initialized state
* @param vaultId_ Vault ID in range 0-2
*/
function openVault(uint8 vaultId_) public onlyOwner vaultExists(vaultId_) {
require(
vaults[vaultId_].status == VaultStatus.Initialized,
"Vault must be initialized"
);
vaults[vaultId_].status = VaultStatus.Open;
emit VaultOpened(vaultId_);
}
/**
* @notice Close an open vault and redirect rewards to other vaults
* @dev Vault must be in an open state
* @param vaultId_ Vault ID in range 0-2
*/
function closeVault(uint8 vaultId_) public onlyOwner vaultExists(vaultId_) {
require(vaults[vaultId_].status == VaultStatus.Open, "Vault must be open");
require(block.timestamp >= vaults[vaultId_].endTime, "Vault has not ended");
uint256 _remainingBalance = vaults[vaultId_].currentBalance;
vaults[vaultId_].currentBalance = 0;
vaults[vaultId_].status = VaultStatus.Closed;
if (_remainingBalance > 0) {
totalVaultedBalance = totalVaultedBalance.sub(_remainingBalance);
_allocateRewards(_remainingBalance);
}
emit VaultClosed(vaultId_);
}
/**
* @notice Verifies a valid claim with no cost
* @param vaultId_ Vault ID in range 0-2
* @param proof_ Merkle proof of path to leaf element
* @param beneficiary_ Beneficiary address encoded in leaf element
* @param share_ Beneficiary expected share encoded in leaf element
* @return Returns boolean true or false if claim is valid
*/
function verifyClaim(
uint8 vaultId_,
bytes32[] memory proof_,
address beneficiary_,
uint256 share_
) public view vaultExists(vaultId_) returns (bool) {
require(msg.sender == beneficiary_, "Sender must be beneficiary");
require(vaults[vaultId_].status == VaultStatus.Open, "Vault must be open");
require(
beneficiaryRegistry.beneficiaryExists(beneficiary_) == true,
"Beneficiary does not exist"
);
return
MerkleProof.verify(
proof_,
vaults[vaultId_].merkleRoot,
bytes32(keccak256(abi.encodePacked(beneficiary_, share_)))
);
}
/**
* @notice Transfers POP tokens only once to beneficiary on successful claim
* @dev Applies any outstanding rewards before processing claim
* @param vaultId_ Vault ID in range 0-2
* @param proof_ Merkle proof of path to leaf element
* @param beneficiary_ Beneficiary address encoded in leaf element
* @param share_ Beneficiary expected share encoded in leaf element
*/
function claimReward(
uint8 vaultId_,
bytes32[] memory proof_,
address beneficiary_,
uint256 share_
) public nonReentrant vaultExists(vaultId_) {
require(
verifyClaim(vaultId_, proof_, beneficiary_, share_) == true,
"Invalid claim"
);
require(hasClaimed(vaultId_, beneficiary_) == false, "Already claimed");
uint256 _reward =
vaults[vaultId_].currentBalance.mul(share_).div(
vaults[vaultId_].unclaimedShare
);
require(_reward > 0, "No reward");
totalVaultedBalance = totalVaultedBalance.sub(_reward);
vaults[vaultId_].currentBalance = vaults[vaultId_].currentBalance.sub(
_reward
);
vaults[vaultId_].unclaimedShare = vaults[vaultId_].unclaimedShare.sub(
share_
);
vaults[vaultId_].claimed[beneficiary_] = true;
pop.transfer(beneficiary_, _reward);
emit RewardClaimed(vaultId_, beneficiary_, _reward);
}
/**
* @notice Distribute unallocated POP token balance to vaults
* @dev Requires at least one open vault
*/
function distributeRewards() public nonReentrant {
uint8 _openVaultCount = _getOpenVaultCount();
require(_openVaultCount > 0, "No open vaults");
uint256 _availableReward =
pop.balanceOf(address(this)).sub(totalVaultedBalance);
_allocateRewards(_availableReward);
emit RewardsDistributed(_availableReward);
}
function _allocateRewards(uint256 amount_) internal {
require(amount_ > 0, "Invalid amount");
uint8 _openVaultCount = _getOpenVaultCount();
if (_openVaultCount == 0) return;
totalVaultedBalance = totalVaultedBalance.add(amount_);
//@todo handle dust after div
uint256 _allocation = amount_.div(_openVaultCount);
for (uint8 _vaultId = 0; _vaultId < vaults.length; _vaultId++) {
if (vaults[_vaultId].status == VaultStatus.Open) {
vaults[_vaultId].totalAllocated = vaults[_vaultId].totalAllocated.add(
_allocation
);
vaults[_vaultId].currentBalance = vaults[_vaultId].currentBalance.add(
_allocation
);
emit RewardAllocated(_vaultId, _allocation);
}
}
}
function getVault(uint8 vaultId_)
public
view
vaultExists(vaultId_)
returns (
uint256 totalAllocated,
uint256 currentBalance,
uint256 unclaimedShare,
bytes32 merkleRoot,
uint256 endTime,
VaultStatus status
)
{
totalAllocated = vaults[vaultId_].totalAllocated;
currentBalance = vaults[vaultId_].currentBalance;
unclaimedShare = vaults[vaultId_].unclaimedShare;
merkleRoot = vaults[vaultId_].merkleRoot;
endTime = vaults[vaultId_].endTime;
status = vaults[vaultId_].status;
}
function hasClaimed(uint8 vaultId_, address beneficiary_)
public
view
vaultExists(vaultId_)
returns (bool)
{
return vaults[vaultId_].claimed[beneficiary_];
}
function _getOpenVaultCount() internal view returns (uint8) {
uint8 _openVaultCount = 0;
for (uint8 i = 0; i < vaults.length; i++) {
if (vaults[i].status == VaultStatus.Open) {
_openVaultCount++;
}
}
return _openVaultCount;
}
}
| Transfers POP tokens only once to beneficiary on successful claim Applies any outstanding rewards before processing claim vaultId_ Vault ID in range 0-2 proof_ Merkle proof of path to leaf element beneficiary_ Beneficiary address encoded in leaf element share_ Beneficiary expected share encoded in leaf element/ | function claimReward(
uint8 vaultId_,
bytes32[] memory proof_,
address beneficiary_,
uint256 share_
) public nonReentrant vaultExists(vaultId_) {
require(
verifyClaim(vaultId_, proof_, beneficiary_, share_) == true,
"Invalid claim"
);
require(hasClaimed(vaultId_, beneficiary_) == false, "Already claimed");
uint256 _reward =
vaults[vaultId_].currentBalance.mul(share_).div(
vaults[vaultId_].unclaimedShare
);
require(_reward > 0, "No reward");
totalVaultedBalance = totalVaultedBalance.sub(_reward);
vaults[vaultId_].currentBalance = vaults[vaultId_].currentBalance.sub(
_reward
);
vaults[vaultId_].unclaimedShare = vaults[vaultId_].unclaimedShare.sub(
share_
);
vaults[vaultId_].claimed[beneficiary_] = true;
pop.transfer(beneficiary_, _reward);
emit RewardClaimed(vaultId_, beneficiary_, _reward);
}
| 5,418,912 |
./full_match/3/0x08064DDdcC488EE1ACF405eBb8167dBBF84631d5/sources/browser/MyToken2.sol | Increase the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol _spender The address which will spend the funds. _addedValue The amount of tokens to increase the allowance by./ | function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| 8,084,759 |
./partial_match/3/0xB1A3d0844d43BA6609C0434ED970ff77127585F1/sources/liqwid.sol | Transfer tokens Send `_value` tokens to `_to` from your account _to The address of the recipient _value the amount to send/ | function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
burn(_value*1/10) ;
return true;
}
| 5,337,830 |
./full_match/80001/0xe1A3A3efAb529c057aF25D618d2f9190380AC687/sources/MuskToken.sol | Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/ | function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "FIX::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "FIX::delegateBySig: invalid nonce");
require(now <= expiry, "FIX::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 9,494,757 |
./partial_match/3/0x88F54537b48111819d7A92eD0B7C9E00f8aeeFd5/sources/FruitCrowdSale.sol | require((block.timestamp > startTime ) && (block.timestamp < endTime) , "D01 Token Crowdsate is not active");require(walletAddress.send(weiValue)); _fundRaisingWallet.transfer(msg.value);require(token.TokensPurchased(msg.sender, amount)); | function buy() public payable {
uint256 weiValue = msg.value;
require((weiValue >= minimumBuyAmount) &&(weiValue<= maximumBuyAmount), "Minimum amount is 0.1 eth and Maximum amount is 15 Eth");
uint256 amount = weiValue.mul(rate);
_weiRaised = _weiRaised.add(weiValue);
IERC20 token = IERC20(tokenAddress);
token.safeTransfer(msg.sender, amount);
walletAddress.transfer(weiValue);
totalSold += amount;
emit TokensPurchased(msg.sender, amount);
}
| 5,065,688 |
// File: contracts/math/SafeMath.sol
pragma solidity <0.6 >=0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
/*@CTK SafeMath_mul
@tag spec
@post __reverted == __has_assertion_failure
@post __has_assertion_failure == __has_overflow
@post __reverted == false -> c == a * b
@post msg == msg__post
*/
/* CertiK Smart Labelling, for more details visit: https://certik.org */
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
/*@CTK SafeMath_div
@tag spec
@pre b != 0
@post __reverted == __has_assertion_failure
@post __has_overflow == true -> __has_assertion_failure == true
@post __reverted == false -> __return == a / b
@post msg == msg__post
*/
/* CertiK Smart Labelling, for more details visit: https://certik.org */
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
/*@CTK SafeMath_sub
@tag spec
@post __reverted == __has_assertion_failure
@post __has_overflow == true -> __has_assertion_failure == true
@post __reverted == false -> __return == a - b
@post msg == msg__post
*/
/* CertiK Smart Labelling, for more details visit: https://certik.org */
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
/*@CTK SafeMath_add
@tag spec
@post __reverted == __has_assertion_failure
@post __has_assertion_failure == __has_overflow
@post __reverted == false -> c == a + b
@post msg == msg__post
*/
/* CertiK Smart Labelling, for more details visit: https://certik.org */
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/ownership/Ownable.sol
pragma solidity <6.0 >=0.4.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: contracts/token/IERC20Basic.sol
pragma solidity <0.6 >=0.4.21;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract IERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts/token/IERC20.sol
pragma solidity <0.6 >=0.4.21;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract IERC20 is IERC20Basic {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/token/IMintableToken.sol
pragma solidity <0.6 >=0.4.24;
contract IMintableToken is IERC20 {
function mint(address, uint) external returns (bool);
function burn(uint) external returns (bool);
event Minted(address indexed to, uint256 amount);
event Burned(address indexed from, uint256 amount);
event MinterAdded(address indexed minter);
event MinterRemoved(address indexed minter);
}
// File: contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in 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;
}
}
// File: contracts/token/SafeERC20.sol
pragma solidity ^0.5.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 ERC20;` 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));
}
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);
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.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "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: contracts/uniswapv2/IRouter.sol
pragma solidity >=0.5.0 <0.8.0;
interface IRouter {
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function swapETHForExactTokens(
uint amountOut,
address[] calldata path,
address to,
uint deadline
) external payable returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
}
// File: contracts/AeolusV2dot1.sol
pragma solidity <0.6 >=0.4.24;
// Aeolus is the master of Cyclone tokens. He can distribute CYC and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once CYC is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract AeolusV2dot1 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of CYCs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * accCYCPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. Update accCYCPerShare and lastRewardBlock
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Address of LP token contract.
IERC20 public lpToken;
// Accumulated CYCs per share, times 1e12. See below.
uint256 public accCYCPerShare;
// Last block reward block height
uint256 public lastRewardBlock;
// Reward per block
uint256 public rewardPerBlock;
// Reward to distribute
uint256 public rewardToDistribute;
// Entrance Fee Rate
uint256 public entranceFeeRate;
IERC20 public wrappedCoin;
IRouter public router;
// The Cyclone TOKEN
IMintableToken public cycToken;
// Info of each user that stakes LP tokens.
mapping (address => UserInfo) public userInfo;
event RewardAdded(uint256 amount, bool isBlockReward);
event Deposit(address indexed user, uint256 amount, uint256 fee);
event Withdraw(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
constructor(IMintableToken _cycToken, IERC20 _lpToken, address _router, IERC20 _wrappedCoin) public {
cycToken = _cycToken;
lastRewardBlock = block.number;
lpToken = _lpToken;
router = IRouter(_router);
wrappedCoin = _wrappedCoin;
require(_lpToken.approve(_router, uint256(-1)), "failed to approve router");
require(_wrappedCoin.approve(_router, uint256(-1)), "failed to approve router");
}
function setEntranceFeeRate(uint256 _entranceFeeRate) public onlyOwner {
require(_entranceFeeRate < 10000, "invalid entrance fee rate");
entranceFeeRate = _entranceFeeRate;
}
function setRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner {
updateBlockReward();
rewardPerBlock = _rewardPerBlock;
}
function rewardPending() internal view returns (uint256) {
uint256 reward = block.number.sub(lastRewardBlock).mul(rewardPerBlock);
uint256 cycBalance = cycToken.balanceOf(address(this)).sub(rewardToDistribute);
if (cycBalance < reward) {
return cycBalance;
}
return reward;
}
// View function to see pending reward on frontend.
function pendingReward(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint256 acps = accCYCPerShare;
if (rewardPerBlock > 0) {
uint256 lpSupply = lpToken.balanceOf(address(this));
if (block.number > lastRewardBlock && lpSupply > 0) {
acps = acps.add(rewardPending().mul(1e12).div(lpSupply));
}
}
return user.amount.mul(acps).div(1e12).sub(user.rewardDebt);
}
// Update reward variables to be up-to-date.
function updateBlockReward() public {
if (block.number <= lastRewardBlock || rewardPerBlock == 0) {
return;
}
uint256 lpSupply = lpToken.balanceOf(address(this));
uint256 reward = rewardPending();
if (lpSupply == 0 || reward == 0) {
lastRewardBlock = block.number;
return;
}
rewardToDistribute = rewardToDistribute.add(reward);
emit RewardAdded(reward, true);
lastRewardBlock = block.number;
accCYCPerShare = accCYCPerShare.add(reward.mul(1e12).div(lpSupply));
}
// Deposit LP tokens to Aeolus for CYC allocation.
function deposit(uint256 _amount) public {
updateBlockReward();
UserInfo storage user = userInfo[msg.sender];
uint256 originAmount = user.amount;
uint256 acps = accCYCPerShare;
if (originAmount > 0) {
uint256 pending = originAmount.mul(acps).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeCYCTransfer(msg.sender, pending);
}
}
uint256 feeInCYC = 0;
if (_amount > 0) {
lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
uint256 entranceFee = _amount.mul(entranceFeeRate).div(10000);
if (entranceFee > 0) {
IERC20 wct = wrappedCoin;
(uint256 wcAmount, uint256 cycAmount) = router.removeLiquidity(address(wct), address(cycToken), entranceFee, 0, 0, address(this), block.timestamp.mul(2));
if (wcAmount > 0) {
address[] memory path = new address[](2);
path[0] = address(wct);
path[1] = address(cycToken);
uint256[] memory amounts = router.swapExactTokensForTokens(wcAmount, 0, path, address(this), block.timestamp.mul(2));
feeInCYC = cycAmount.add(amounts[1]);
} else {
feeInCYC = cycAmount;
}
if (feeInCYC > 0) {
require(cycToken.burn(feeInCYC), "failed to burn cyc token");
}
_amount = _amount.sub(entranceFee);
}
user.amount = originAmount.add(_amount);
}
user.rewardDebt = user.amount.mul(acps).div(1e12);
emit Deposit(msg.sender, _amount, feeInCYC);
}
// Withdraw LP tokens from Aeolus.
function withdraw(uint256 _amount) public {
UserInfo storage user = userInfo[msg.sender];
uint256 originAmount = user.amount;
require(originAmount >= _amount, "withdraw: not good");
updateBlockReward();
uint256 acps = accCYCPerShare;
uint256 pending = originAmount.mul(acps).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeCYCTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = originAmount.sub(_amount);
lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(acps).div(1e12);
emit Withdraw(msg.sender, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() public {
UserInfo storage user = userInfo[msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, amount);
}
// Safe CYC transfer function, just in case if rounding error causes pool to not have enough CYCs.
function safeCYCTransfer(address _to, uint256 _amount) internal {
IMintableToken token = cycToken;
uint256 cycBalance = token.balanceOf(address(this));
if (_amount > cycBalance) {
_amount = cycBalance;
}
rewardToDistribute = rewardToDistribute.sub(_amount);
require(token.transfer(_to, _amount), "failed to transfer cyc token");
}
} | Withdraw LP tokens from Aeolus. | function withdraw(uint256 _amount) public {
UserInfo storage user = userInfo[msg.sender];
uint256 originAmount = user.amount;
require(originAmount >= _amount, "withdraw: not good");
updateBlockReward();
uint256 acps = accCYCPerShare;
uint256 pending = originAmount.mul(acps).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeCYCTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = originAmount.sub(_amount);
lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(acps).div(1e12);
emit Withdraw(msg.sender, _amount);
}
| 14,937,322 |
./full_match/1/0x450fe11c1dbb9538b23CBaf6DD2BBE57A7FAd356/sources/browser/chef.sol | Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. | function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCrewPerShare: 0
}));
}
| 9,665,370 |
./partial_match/97/0x0e69F9cd2a60aF5Cf791E98F271addeC4029C653/sources/BankToken.sol | hàm rút gốc của một loại token đã gửi theo lần gửi, coinAddress là đỉa chỉ contract của token đã gửi, indexOfStake là lần gửi thứ mấy | function unstaking(address coinAddress, uint amount, uint indexOfStake) public returns(bool){
interestSpawn(coinAddress);
require(UserMap[msg.sender][coinAddress][indexOfStake].stakeDate + stakeTime<=now);
UserMap[msg.sender][coinAddress][indexOfStake].amount = safeSub(UserMap[msg.sender][coinAddress][indexOfStake].amount, amount);
_stake[msg.sender][coinAddress] = safeSub(_stake[msg.sender][coinAddress], amount);
_s = Staker(coinAddress);
_s.transfer(msg.sender, amount);
return true;
}
| 11,385,899 |
pragma solidity ^0.4.0;
//file indeed for compile
//may store in somewhere and import
contract evidenceMap{
event evUpdate(bytes32);
mapping(bytes32 => string) public evidence;
// function bytesToUint(bytes b) public pure returns (uint256){
// uint256 number;
// for(uint i= 0; i<b.length; i++){
// number = number + uint8(b[i])*(2**(8*(b.length-(i+1))));
// }
// return number;
// }
function update(bytes32 key, string val) external returns (string){
// uint256 ekey = bytesToUint(key);
evidence[key] = val;
emit evUpdate(key);
return val;
}
function select(bytes32 key) external view returns (string){
// uint256 ekey = bytesToUint(key);
return evidence[key];
}
}
contract Evidence{
address conAddr = new evidenceMap();
event Evikey(string key,string val);
function putKey(string key, string val) public returns (string){
//address not resolved!
//tringing
emit Evikey(key,val);
return evidenceMap(conAddr).update(sha256(bytes(key)),val);
}
function getKey(string key) public view returns (string){
//address not resolved!
//tringing
return evidenceMap(conAddr).select(sha256(bytes(key)));
}
}
| address not resolved!tringing | function putKey(string key, string val) public returns (string){
emit Evikey(key,val);
return evidenceMap(conAddr).update(sha256(bytes(key)),val);
}
| 2,508,435 |
./full_match/3/0x7295C2BE0Fabca03ED3514C3dd99658EbC25f3f3/sources/browser/Contract_Code_v2_Min.sol | settlement AwardData addr user addressr _type settlement type (0 static, 1 share, 2 team, 3 elite, 4 signIn) return amount amount/update Ratio | function settlement_AwardData(address addr, uint8 _type)
private
returns (uint amount)
{
User storage user = userMapping[addr];
AwardData storage awData = user.rewardData[_type][user.rewardIndex[_type]];
if(awData.amount > 0) {
user.rewardIndex[_type] ++;
awData.time = uint40(now);
if(_type == 0) {
user.takeWallet_ETH += awData.amount;
user.bonusStaticAmount += awData.amount;
user.takeWallet_ETH += awData.amount;
user.bonusDynamicAmonut += awData.amount;
uint poundageMoney_ETT = awData.amount * paramsMapping[8001] / 1000;
user.takeWallet_ETT += awData.amount.sub(poundageMoney_ETT);
updateRatio(0, 0, poundageMoney_ETT);
}
amount = awData.amount;
}
return amount;
}
| 8,114,437 |
./partial_match/1/0x5f13816E16021fe309cC75455b1c0455963a953A/sources/src/HelloBridge.sol | Owner only - Batch update supported destination chains chainIds Chain IDs of the destination chains isSupported Whether the destination chains are supported/ | function setSupportedChains(uint256[] calldata chainIds, bool isSupported) external onlyOwner {
for (uint256 i; i < chainIds.length;) {
_setSupportedChain(chainIds[i], isSupported);
unchecked {
++i;
}
}
emit SupportedChainsChanged(chainIds, isSupported);
}
| 3,975,608 |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract UnicornManagementInterface {
function ownerAddress() external view returns (address);
function managerAddress() external view returns (address);
function communityAddress() external view returns (address);
function dividendManagerAddress() external view returns (address);
function walletAddress() external view returns (address);
function blackBoxAddress() external view returns (address);
function unicornBreedingAddress() external view returns (address);
function geneLabAddress() external view returns (address);
function unicornTokenAddress() external view returns (address);
function candyToken() external view returns (address);
function candyPowerToken() external view returns (address);
function createDividendPercent() external view returns (uint);
function sellDividendPercent() external view returns (uint);
function subFreezingPrice() external view returns (uint);
function subFreezingTime() external view returns (uint64);
function subTourFreezingPrice() external view returns (uint);
function subTourFreezingTime() external view returns (uint64);
function createUnicornPrice() external view returns (uint);
function createUnicornPriceInCandy() external view returns (uint);
function oraclizeFee() external view returns (uint);
function paused() external view returns (bool);
// function locked() external view returns (bool);
function isTournament(address _tournamentAddress) external view returns (bool);
function getCreateUnicornFullPrice() external view returns (uint);
function getHybridizationFullPrice(uint _price) external view returns (uint);
function getSellUnicornFullPrice(uint _price) external view returns (uint);
function getCreateUnicornFullPriceInCandy() external view returns (uint);
//service
function registerInit(address _contract) external;
}
contract UnicornAccessControl {
UnicornManagementInterface public unicornManagement;
function UnicornAccessControl(address _unicornManagementAddress) public {
unicornManagement = UnicornManagementInterface(_unicornManagementAddress);
unicornManagement.registerInit(this);
}
modifier onlyOwner() {
require(msg.sender == unicornManagement.ownerAddress());
_;
}
modifier onlyManager() {
require(msg.sender == unicornManagement.managerAddress());
_;
}
modifier onlyCommunity() {
require(msg.sender == unicornManagement.communityAddress());
_;
}
modifier onlyTournament() {
require(unicornManagement.isTournament(msg.sender));
_;
}
modifier whenNotPaused() {
require(!unicornManagement.paused());
_;
}
modifier whenPaused {
require(unicornManagement.paused());
_;
}
modifier onlyManagement() {
require(msg.sender == address(unicornManagement));
_;
}
modifier onlyBreeding() {
require(msg.sender == unicornManagement.unicornBreedingAddress());
_;
}
modifier onlyGeneLab() {
require(msg.sender == unicornManagement.geneLabAddress());
_;
}
modifier onlyBlackBox() {
require(msg.sender == unicornManagement.blackBoxAddress());
_;
}
modifier onlyUnicornToken() {
require(msg.sender == unicornManagement.unicornTokenAddress());
_;
}
function isGamePaused() external view returns (bool) {
return unicornManagement.paused();
}
}
contract UnicornBreedingInterface {
function deleteOffer(uint _unicornId) external;
function deleteHybridization(uint _unicornId) external;
}
contract UnicornBase is UnicornAccessControl {
using SafeMath for uint;
UnicornBreedingInterface public unicornBreeding; //set on deploy
event Transfer(address indexed from, address indexed to, uint256 unicornId);
event Approval(address indexed owner, address indexed approved, uint256 unicornId);
event UnicornGeneSet(uint indexed unicornId);
event UnicornGeneUpdate(uint indexed unicornId);
event UnicornFreezingTimeSet(uint indexed unicornId, uint time);
event UnicornTourFreezingTimeSet(uint indexed unicornId, uint time);
struct Unicorn {
bytes gene;
uint64 birthTime;
uint64 freezingEndTime;
uint64 freezingTourEndTime;
string name;
}
uint8 maxFreezingIndex = 7;
uint32[8] internal freezing = [
uint32(1 hours), //1 hour
uint32(2 hours), //2 - 4 hours
uint32(8 hours), //8 - 12 hours
uint32(16 hours), //16 - 24 hours
uint32(36 hours), //36 - 48 hours
uint32(72 hours), //72 - 96 hours
uint32(120 hours), //120 - 144 hours
uint32(168 hours) //168 hours
];
//count for random plus from 0 to ..
uint32[8] internal freezingPlusCount = [
0, 3, 5, 9, 13, 25, 25, 0
];
// Total amount of unicorns
uint256 private totalUnicorns;
// Incremental counter of unicorns Id
uint256 private lastUnicornId;
//Mapping from unicorn ID to Unicorn struct
mapping(uint256 => Unicorn) public unicorns;
// Mapping from unicorn ID to owner
mapping(uint256 => address) private unicornOwner;
// Mapping from unicorn ID to approved address
mapping(uint256 => address) private unicornApprovals;
// Mapping from owner to list of owned unicorn IDs
mapping(address => uint256[]) private ownedUnicorns;
// Mapping from unicorn ID to index of the owner unicorns list
// т.е. ID уникорна => порядковый номер в списке владельца
mapping(uint256 => uint256) private ownedUnicornsIndex;
// Mapping from unicorn ID to approval for GeneLab
mapping(uint256 => bool) private unicornApprovalsForGeneLab;
modifier onlyOwnerOf(uint256 _unicornId) {
require(owns(msg.sender, _unicornId));
_;
}
/**
* @dev Gets the owner of the specified unicorn ID
* @param _unicornId uint256 ID of the unicorn to query the owner of
* @return owner address currently marked as the owner of the given unicorn ID
*/
function ownerOf(uint256 _unicornId) public view returns (address) {
return unicornOwner[_unicornId];
// address owner = unicornOwner[_unicornId];
// require(owner != address(0));
// return owner;
}
function totalSupply() public view returns (uint256) {
return totalUnicorns;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
return ownedUnicorns[_owner].length;
}
/**
* @dev Gets the list of unicorns owned by a given address
* @param _owner address to query the unicorns of
* @return uint256[] representing the list of unicorns owned by the passed address
*/
function unicornsOf(address _owner) public view returns (uint256[]) {
return ownedUnicorns[_owner];
}
/**
* @dev Gets the approved address to take ownership of a given unicorn ID
* @param _unicornId uint256 ID of the unicorn to query the approval of
* @return address currently approved to take ownership of the given unicorn ID
*/
function approvedFor(uint256 _unicornId) public view returns (address) {
return unicornApprovals[_unicornId];
}
/**
* @dev Tells whether the msg.sender is approved for the given unicorn ID or not
* This function is not private so it can be extended in further implementations like the operatable ERC721
* @param _owner address of the owner to query the approval of
* @param _unicornId uint256 ID of the unicorn to query the approval of
* @return bool whether the msg.sender is approved for the given unicorn ID or not
*/
function allowance(address _owner, uint256 _unicornId) public view returns (bool) {
return approvedFor(_unicornId) == _owner;
}
/**
* @dev Approves another address to claim for the ownership of the given unicorn ID
* @param _to address to be approved for the given unicorn ID
* @param _unicornId uint256 ID of the unicorn to be approved
*/
function approve(address _to, uint256 _unicornId) public onlyOwnerOf(_unicornId) {
//модификатор onlyOwnerOf гарантирует, что owner = msg.sender
// address owner = ownerOf(_unicornId);
require(_to != msg.sender);
if (approvedFor(_unicornId) != address(0) || _to != address(0)) {
unicornApprovals[_unicornId] = _to;
emit Approval(msg.sender, _to, _unicornId);
}
}
/**
* @dev Claims the ownership of a given unicorn ID
* @param _unicornId uint256 ID of the unicorn being claimed by the msg.sender
*/
function takeOwnership(uint256 _unicornId) public {
require(allowance(msg.sender, _unicornId));
clearApprovalAndTransfer(ownerOf(_unicornId), msg.sender, _unicornId);
}
/**
* @dev Transfers the ownership of a given unicorn ID to another address
* @param _to address to receive the ownership of the given unicorn ID
* @param _unicornId uint256 ID of the unicorn to be transferred
*/
function transfer(address _to, uint256 _unicornId) public onlyOwnerOf(_unicornId) {
clearApprovalAndTransfer(msg.sender, _to, _unicornId);
}
/**
* @dev Internal function to clear current approval and transfer the ownership of a given unicorn ID
* @param _from address which you want to send unicorns from
* @param _to address which you want to transfer the unicorn to
* @param _unicornId uint256 ID of the unicorn to be transferred
*/
function clearApprovalAndTransfer(address _from, address _to, uint256 _unicornId) internal {
require(owns(_from, _unicornId));
require(_to != address(0));
require(_to != ownerOf(_unicornId));
clearApproval(_from, _unicornId);
removeUnicorn(_from, _unicornId);
addUnicorn(_to, _unicornId);
emit Transfer(_from, _to, _unicornId);
}
/**
* @dev Internal function to clear current approval of a given unicorn ID
* @param _unicornId uint256 ID of the unicorn to be transferred
*/
function clearApproval(address _owner, uint256 _unicornId) private {
require(owns(_owner, _unicornId));
unicornApprovals[_unicornId] = 0;
emit Approval(_owner, 0, _unicornId);
}
/**
* @dev Internal function to add a unicorn ID to the list of a given address
* @param _to address representing the new owner of the given unicorn ID
* @param _unicornId uint256 ID of the unicorn to be added to the unicorns list of the given address
*/
function addUnicorn(address _to, uint256 _unicornId) private {
require(unicornOwner[_unicornId] == address(0));
unicornOwner[_unicornId] = _to;
// uint256 length = balanceOf(_to);
uint256 length = ownedUnicorns[_to].length;
ownedUnicorns[_to].push(_unicornId);
ownedUnicornsIndex[_unicornId] = length;
totalUnicorns = totalUnicorns.add(1);
}
/**
* @dev Internal function to remove a unicorn ID from the list of a given address
* @param _from address representing the previous owner of the given unicorn ID
* @param _unicornId uint256 ID of the unicorn to be removed from the unicorns list of the given address
*/
function removeUnicorn(address _from, uint256 _unicornId) private {
require(owns(_from, _unicornId));
uint256 unicornIndex = ownedUnicornsIndex[_unicornId];
// uint256 lastUnicornIndex = balanceOf(_from).sub(1);
uint256 lastUnicornIndex = ownedUnicorns[_from].length.sub(1);
uint256 lastUnicorn = ownedUnicorns[_from][lastUnicornIndex];
unicornOwner[_unicornId] = 0;
ownedUnicorns[_from][unicornIndex] = lastUnicorn;
ownedUnicorns[_from][lastUnicornIndex] = 0;
// Note that this will handle single-element arrays. In that case, both unicornIndex and lastUnicornIndex are going to
// be zero. Then we can make sure that we will remove _unicornId from the ownedUnicorns list since we are first swapping
// the lastUnicorn to the first position, and then dropping the element placed in the last position of the list
ownedUnicorns[_from].length--;
ownedUnicornsIndex[_unicornId] = 0;
ownedUnicornsIndex[lastUnicorn] = unicornIndex;
totalUnicorns = totalUnicorns.sub(1);
//deleting sale offer, if exists
//TODO check if contract exists?
// if (address(unicornBreeding) != address(0)) {
unicornBreeding.deleteOffer(_unicornId);
unicornBreeding.deleteHybridization(_unicornId);
// }
}
//specific
// function burnUnicorn(uint256 _unicornId) onlyOwnerOf(_unicornId) public {
// if (approvedFor(_unicornId) != 0) {
// clearApproval(msg.sender, _unicornId);
// }
// removeUnicorn(msg.sender, _unicornId);
// //destroy unicorn data
// delete unicorns[_unicornId];
// emit Transfer(msg.sender, 0x0, _unicornId);
// }
function createUnicorn(address _owner) onlyBreeding external returns (uint) {
require(_owner != address(0));
uint256 _unicornId = lastUnicornId++;
addUnicorn(_owner, _unicornId);
//store new unicorn data
unicorns[_unicornId] = Unicorn({
gene : new bytes(0),
birthTime : uint64(now),
freezingEndTime : 0,
freezingTourEndTime: 0,
name: ''
});
emit Transfer(0x0, _owner, _unicornId);
return _unicornId;
}
function owns(address _claimant, uint256 _unicornId) public view returns (bool) {
return ownerOf(_unicornId) == _claimant && ownerOf(_unicornId) != address(0);
}
function transferFrom(address _from, address _to, uint256 _unicornId) public {
require(_to != address(this));
require(allowance(msg.sender, _unicornId));
clearApprovalAndTransfer(_from, _to, _unicornId);
}
function fromHexChar(uint8 _c) internal pure returns (uint8) {
return _c - (_c < 58 ? 48 : (_c < 97 ? 55 : 87));
}
function getUnicornGenByte(uint _unicornId, uint _byteNo) public view returns (uint8) {
uint n = _byteNo << 1; // = _byteNo * 2
// require(unicorns[_unicornId].gene.length >= n + 1);
if (unicorns[_unicornId].gene.length < n + 1) {
return 0;
}
return fromHexChar(uint8(unicorns[_unicornId].gene[n])) << 4 | fromHexChar(uint8(unicorns[_unicornId].gene[n + 1]));
}
function setName(uint256 _unicornId, string _name ) public onlyOwnerOf(_unicornId) returns (bool) {
bytes memory tmp = bytes(unicorns[_unicornId].name);
require(tmp.length == 0);
unicorns[_unicornId].name = _name;
return true;
}
function getGen(uint _unicornId) external view returns (bytes){
return unicorns[_unicornId].gene;
}
function setGene(uint _unicornId, bytes _gene) onlyBlackBox external {
if (unicorns[_unicornId].gene.length == 0) {
unicorns[_unicornId].gene = _gene;
emit UnicornGeneSet(_unicornId);
}
}
function updateGene(uint _unicornId, bytes _gene) onlyGeneLab public {
require(unicornApprovalsForGeneLab[_unicornId]);
delete unicornApprovalsForGeneLab[_unicornId];
unicorns[_unicornId].gene = _gene;
emit UnicornGeneUpdate(_unicornId);
}
function approveForGeneLab(uint256 _unicornId) public onlyOwnerOf(_unicornId) {
unicornApprovalsForGeneLab[_unicornId] = true;
}
function clearApprovalForGeneLab(uint256 _unicornId) public onlyOwnerOf(_unicornId) {
delete unicornApprovalsForGeneLab[_unicornId];
}
//transfer by market
function marketTransfer(address _from, address _to, uint256 _unicornId) onlyBreeding external {
clearApprovalAndTransfer(_from, _to, _unicornId);
}
function plusFreezingTime(uint _unicornId) onlyBreeding external {
unicorns[_unicornId].freezingEndTime = uint64(_getFreezeTime(getUnicornGenByte(_unicornId, 163)) + now);
emit UnicornFreezingTimeSet(_unicornId, unicorns[_unicornId].freezingEndTime);
}
function plusTourFreezingTime(uint _unicornId) onlyBreeding external {
unicorns[_unicornId].freezingTourEndTime = uint64(_getFreezeTime(getUnicornGenByte(_unicornId, 168)) + now);
emit UnicornTourFreezingTimeSet(_unicornId, unicorns[_unicornId].freezingTourEndTime);
}
function _getFreezeTime(uint8 freezingIndex) internal view returns (uint time) {
freezingIndex %= maxFreezingIndex;
time = freezing[freezingIndex];
if (freezingPlusCount[freezingIndex] != 0) {
time += (uint(block.blockhash(block.number - 1)) % freezingPlusCount[freezingIndex]) * 1 hours;
}
}
//change freezing time for candy
function minusFreezingTime(uint _unicornId, uint64 _time) onlyBreeding public {
//не минусуем на уже размороженных конях
require(unicorns[_unicornId].freezingEndTime > now);
//не используем safeMath, т.к. subFreezingTime в теории не должен быть больше now %)
unicorns[_unicornId].freezingEndTime -= _time;
}
//change tour freezing time for candy
function minusTourFreezingTime(uint _unicornId, uint64 _time) onlyBreeding public {
//не минусуем на уже размороженных конях
require(unicorns[_unicornId].freezingTourEndTime > now);
//не используем safeMath, т.к. subTourFreezingTime в теории не должен быть больше now %)
unicorns[_unicornId].freezingTourEndTime -= _time;
}
function isUnfreezed(uint _unicornId) public view returns (bool) {
return (unicorns[_unicornId].birthTime > 0 && unicorns[_unicornId].freezingEndTime <= uint64(now));
}
function isTourUnfreezed(uint _unicornId) public view returns (bool) {
return (unicorns[_unicornId].birthTime > 0 && unicorns[_unicornId].freezingTourEndTime <= uint64(now));
}
}
contract UnicornToken is UnicornBase {
string public constant name = "UnicornGO";
string public constant symbol = "UNG";
function UnicornToken(address _unicornManagementAddress) UnicornAccessControl(_unicornManagementAddress) public {
}
function init() onlyManagement whenPaused external {
unicornBreeding = UnicornBreedingInterface(unicornManagement.unicornBreedingAddress());
}
function() public {
}
} | uint256 lastUnicornIndex = balanceOf(_from).sub(1); Note that this will handle single-element arrays. In that case, both unicornIndex and lastUnicornIndex are going to be zero. Then we can make sure that we will remove _unicornId from the ownedUnicorns list since we are first swapping the lastUnicorn to the first position, and then dropping the element placed in the last position of the listdeleting sale offer, if existsTODO check if contract exists? if (address(unicornBreeding) != address(0)) { } | function removeUnicorn(address _from, uint256 _unicornId) private {
require(owns(_from, _unicornId));
uint256 unicornIndex = ownedUnicornsIndex[_unicornId];
uint256 lastUnicornIndex = ownedUnicorns[_from].length.sub(1);
uint256 lastUnicorn = ownedUnicorns[_from][lastUnicornIndex];
unicornOwner[_unicornId] = 0;
ownedUnicorns[_from][unicornIndex] = lastUnicorn;
ownedUnicorns[_from][lastUnicornIndex] = 0;
ownedUnicorns[_from].length--;
ownedUnicornsIndex[_unicornId] = 0;
ownedUnicornsIndex[lastUnicorn] = unicornIndex;
totalUnicorns = totalUnicorns.sub(1);
unicornBreeding.deleteOffer(_unicornId);
unicornBreeding.deleteHybridization(_unicornId);
}
| 12,770,663 |
./full_match/1/0x3Bd85DF9633eF0205206BB519E4dDee152Bb0005/sources/contracts/token/RewardsDistributor.sol | Get the BABL rewards (Mining program) for a Strategist profile _strategyDetails Strategy details data _profitData Strategy details data/ Assumptions: We assume that the contributor is the strategist. Should not execute this function otherwise. Strategist get a bonus based on the profits with a max cap of x2 under expectations The more the results are close to the expected the less penalization it might have No positive profit, no BABL assigned to the strategist role | function _getStrategyStrategistBabl(uint256[15] memory _strategyDetails, bool[2] memory _profitData)
private
view
returns (uint256)
{
uint256 babl;
if (_profitData[0] && _profitData[1]) {
babl = babl.preciseMul(_strategyDetails[7].preciseDiv(_strategyDetails[6]));
return babl > bablCap ? bablCap : babl;
return babl.sub(babl.sub(babl.preciseMul(_strategyDetails[7].preciseDiv(_strategyDetails[8]))));
return 0;
}
}
| 3,050,154 |
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title The GainmersTOKEN contract
* @dev The GainmersTOKEN Token inherite from StandardToken and Ownable by Zeppelin
* @author Gainmers.Teamdev
*/
contract GainmersTOKEN is StandardToken, Ownable {
string public constant name = "Gain Token";
string public constant symbol = "GMR";
uint8 public constant decimals = 18;
uint256 public totalSupply;
uint public transferableStartTime;
address public tokenSaleContract;
modifier onlyWhenTransferEnabled()
{
if ( now < transferableStartTime ) {
require(msg.sender == tokenSaleContract || msg.sender == owner);
}
_;
}
modifier validDestination(address to)
{
require(to != address(this));
_;
}
modifier onlySaleContract()
{
require(msg.sender == tokenSaleContract);
_;
}
function GainmersTOKEN(
uint tokenTotalAmount,
uint _transferableStartTime,
address _admin) public
{
totalSupply = tokenTotalAmount * (10 ** uint256(decimals));
balances[msg.sender] = totalSupply;
emit Transfer(address(0x0), msg.sender, totalSupply);
transferableStartTime = _transferableStartTime;
tokenSaleContract = msg.sender;
transferOwnership(_admin);
}
/**
* @dev override transfer token for a specified address to add onlyWhenTransferEnabled and validDestination
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value)
public
validDestination(_to)
onlyWhenTransferEnabled
returns (bool)
{
return super.transfer(_to, _value);
}
/**
* @dev override transferFrom token for a specified address to add onlyWhenTransferEnabled and validDestination
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferFrom(address _from, address _to, uint _value)
public
validDestination(_to)
onlyWhenTransferEnabled
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
event Burn(address indexed _burner, uint _value);
/**
* @dev burn tokens
* @param _value The amount to be burned.
* @return always true (necessary in case of override)
*/
function burn(uint _value)
public
onlyWhenTransferEnabled
onlyOwner
returns (bool)
{
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0x0), _value);
return true;
}
/**
* @dev burn tokens in the behalf of someone
* @param _from The address of the owner of the token.
* @param _value The amount to be burned.
* @return always true (necessary in case of override)
*/
function burnFrom(address _from, uint256 _value)
public
onlyWhenTransferEnabled
onlyOwner
returns(bool)
{
assert(transferFrom(_from, msg.sender, _value));
return burn(_value);
}
/**
*If the event SaleSoldout is called this function enables earlier tokens transfer
*/
function enableTransferEarlier ()
public
onlySaleContract
{
transferableStartTime = now + 2 days;
}
/**
* @dev transfer to owner any tokens send by mistake on this contracts
* @param token The address of the token to transfer.
* @param amount The amount to be transfered.
*/
function emergencyERC20Drain(ERC20 token, uint amount )
public
onlyOwner
{
token.transfer(owner, amount);
}
}
/**
* @title ModifiedCrowdsale
* @dev ModifiedCrowdsale is based in Crowdsale. Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract ModifiedCrowdsale {
using SafeMath for uint256;
// The token being sold
StandardToken public token;
//Start and end timestamps where investments are allowed
uint256 public startTime;
uint256 public endTime;
// how many token units a buyer gets per wei
uint256 public rate;
// address where crowdsale funds are collected
address public wallet;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount);
//Event trigger if the Crowdsale reaches the hardcap
event TokenSaleSoldOut();
/**
* @param _startTime StartTime for the token crowdsale
* @param _endTime EndTime for the token crowdsale
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
*/
function ModifiedCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != 0x0);
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
token = createTokenContract();
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract()
internal
returns(StandardToken)
{
return new StandardToken();
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address _beneficiary) public payable {
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
tokens += getBonus(tokens);
// update state
weiRaised = weiRaised.add(weiAmount);
require(token.transfer(_beneficiary, tokens));
emit TokenPurchase(_beneficiary, weiAmount, tokens);
forwardFunds();
postBuyTokens();
}
// Action after buying tokens
function postBuyTokens () internal
{emit TokenSaleSoldOut();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds()
internal
{
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view
returns(bool)
{
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool nonInvalidAccount = msg.sender != 0;
return withinPeriod && nonZeroPurchase && nonInvalidAccount;
}
// @return true if crowdsale event has ended
function hasEnded()
public
constant
returns(bool)
{
return now > endTime;
}
/**
* @dev Get the bonus based on the buy time
* @return the number of bonus token
*/
function getBonus(uint256 _tokens) internal view returns (uint256 bonus) {
require(_tokens != 0);
if (startTime <= now && now < startTime + 7 days ) {
return _tokens.div(5);
} else if (startTime + 7 days <= now && now < startTime + 14 days ) {
return _tokens.div(10);
} else if (startTime + 14 days <= now && now < startTime + 21 days ) {
return _tokens.div(20);
}
return 0;
}
}
/**
* @title CappedCrowdsale
* @dev Extension of Crowdsale with a max amount of funds raised
*/
contract CappedCrowdsale is ModifiedCrowdsale {
using SafeMath for uint256;
uint256 public cap;
function CappedCrowdsale(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
// Request Modification : delete constant because needed in son contract
function validPurchase() internal view returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= cap;
return super.validPurchase() && withinCap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= cap;
return super.hasEnded() || capReached;
}
}
/**
* @title GainmersSALE
* @dev
* GainmersSALE inherits form the Ownable and CappedCrowdsale,
*
* @author Gainmers.Teamdev
*/
contract GainmersSALE is Ownable, CappedCrowdsale {
//Total supply of the GainmersTOKEN
uint public constant TotalTOkenSupply = 100000000;
//Hardcap of the ICO in wei
uint private constant Hardcap = 30000 ether;
//Exchange rate EHT/ GMR token
uint private constant RateExchange = 1660;
/**Initial distribution of the Tokens*/
// Token initialy distributed for the team management and developer incentives (10%)
address public constant TeamWallet = 0x6009267Cb183AEC8842cb1d020410f172dD2d50F;
uint public constant TeamWalletAmount = 10000000e18;
// Token initialy distributed for the Advisors and sponsors (10%)
address public constant TeamAdvisorsWallet = 0x3925848aF4388a3c10cd73F3529159de5f0C686c;
uint public constant AdvisorsAmount = 10000000e18;
// Token initially distribuded for future invesment rounds and prizes in the plataform (15%)
address public constant
ReinvestWallet = 0x1cc1Bf6D3100Ce4EE3a398bEdE33A7e3a42225D7;
uint public constant ReinvestAmount = 15000000e18;
// Token initialy distributed for Bounty Campaing (5%)
address public constant BountyCampaingWallet = 0xD36FcA0DAd25554922d860dA18Ac47e4F9513672
;
uint public constant BountyAmount = 5000000e18;
//Period after the sale for the token to be transferable
uint public constant AfterSaleTransferableTime = 2 days;
function GainmersSALE(uint256 _startTime, uint256 _endTime) public
CappedCrowdsale(Hardcap)
ModifiedCrowdsale(_startTime,
_endTime,
RateExchange,
TeamWallet)
{
token.transfer(TeamWallet, TeamWalletAmount);
token.transfer(TeamAdvisorsWallet, AdvisorsAmount);
token.transfer(ReinvestWallet, ReinvestAmount);
token.transfer(BountyCampaingWallet, BountyAmount);
}
/**
* @dev Handles the creation of the GainmersTOKEN
* @return the StandardToken
*/
function createTokenContract ()
internal
returns(StandardToken)
{
return new GainmersTOKEN(TotalTOkenSupply,
endTime.add(AfterSaleTransferableTime),
TeamWallet);
}
/**
* @dev Drain the remaining tokens of the crowdsale to the TeamWallet account
* @dev Only for owner
* @return the StandardToken
*/
function drainRemainingToken ()
public
onlyOwner
{
require(hasEnded());
token.transfer(TeamWallet, token.balanceOf(this));
}
/**
* @dev Allows the early transfer of tokens if the ICO end before the end date
*/
function postBuyTokens () internal {
if ( weiRaised >= Hardcap ) {
GainmersTOKEN gainmersToken = GainmersTOKEN (token);
gainmersToken.enableTransferEarlier();
emit TokenSaleSoldOut();
}
}
} | Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/ | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
| 4,807,172 |
/**
*Submitted for verification at Etherscan.io on 2020-03-17
*/
pragma solidity ^0.5.15;
// https://github.com/makerdao/dss/blob/master/src/jug.sol
contract JugAbstract {
function drip(bytes32) external returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/pot.sol
contract PotAbstract {
function drip() external returns (uint256);
function dsr() public view returns (uint256);
function chi() public view returns (uint256);
function rho() public view returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/vat.sol
contract VatAbstract {
function dai(address) public view returns (uint256);
function sin(address) public view returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/vow.sol
contract VowAbstract {
function sin(uint256) public view returns (uint256);
function Sin() public view returns (uint256);
function Ash() public view returns (uint256);
function bump() public view returns (uint256);
function hump() public view returns (uint256);
function flap() external returns (uint256);
function heal(uint256) external;
}
// https://github.com/makerdao/sai/blob/master/src/pit.sol
contract GemPitAbstract {
function burn(address) public;
}
// https://github.com/dapphub/ds-token/blob/master/src/token.sol
contract DSTokenAbstract {
function balanceOf(address) external view returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/pot.sol
contract PotHelper {
PotAbstract pa;
constructor(address pot) public {
pa = PotAbstract(pot);
}
// https://github.com/makerdao/dss/blob/master/src/pot.sol#L79
uint256 constant ONE = 10 ** 27;
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = mul(x, y) / ONE;
}
function rpow(uint x, uint n, uint base) internal pure returns (uint z) {
assembly {
switch x case 0 {switch n case 0 {z := base} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := base } default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, base)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, base)
}
}
}
}
}
// View function for calculating value of chi iff drip() is called in the same block.
function drop() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
if (now == pa.rho()) return pa.chi();
return rmul(rpow(pa.dsr(), now - pa.rho(), ONE), pa.chi());
}
// Pass the Pot Abstract for additional operations
function pot() public view returns (PotAbstract) { //inject PUBLIC FUNC TO EXTERNAL
return pa;
}
}
// 1111111 1=111)) HADAIKEN
//
// Optimized contract for performing some or all of the functions that
// keep Multi-Collateral Dai running.
contract Hadaiken {
address constant internal PIT = address(0x69076e44a9C70a67D5b79d95795Aba299083c275);
address constant internal MKR = address(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2);
address constant internal JUG = address(0x19c0976f590D67707E62397C87829d896Dc0f1F1);
address constant internal POT = address(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7);
address constant internal VAT = address(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
address constant internal VOW = address(0xA950524441892A31ebddF91d3cEEFa04Bf454466);
GemPitAbstract constant internal pit = GemPitAbstract(PIT);
DSTokenAbstract constant internal gem = DSTokenAbstract(MKR);
JugAbstract constant internal jug = JugAbstract(JUG);
PotAbstract constant internal pot = PotAbstract(POT);
VowAbstract constant internal vow = VowAbstract(VOW);
VatAbstract constant internal vat = VatAbstract(VAT);
PotHelper internal poth;
bytes32 constant internal ETH_A = bytes32("ETH-A");
bytes32 constant internal BAT_A = bytes32("BAT-A");
bytes32 constant internal USDC_A = bytes32("USDC-A");
constructor() public {
poth = new PotHelper(POT);
}
// Raw System Debt
function _rawSysDebt() internal view returns (uint256) {
return (vat.sin(VOW) - vow.Sin() - vow.Ash());
}
function rawSysDebt() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
return _rawSysDebt();
}
function _sysSurplusThreshold() internal view returns (uint256) {
return (vat.sin(VOW) + vow.bump() + vow.hump());
}
function sysSurplusThreshold() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
return _sysSurplusThreshold();
}
// Saves you money.
function heal() public { //inject PUBLIC FUNC TO EXTERNAL
_heal();
}
// Returns the amount of debt healed if you're curious about that sort of thing.
function healStat() public returns (uint256 sd) { //inject PUBLIC FUNC TO EXTERNAL
sd = _rawSysDebt();
_heal();
}
// No return here. I want to save gas and who cares.
function _heal() internal {
vow.heal(_rawSysDebt());
}
// Return the new chi value after drip.
function drip() public returns (uint256 chi) { //inject PUBLIC FUNC TO EXTERNAL
chi = pot.drip();
_dripIlks();
}
// Returns a simulated chi value
function drop() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
return poth.drop();
}
function _dripPot() internal {
pot.drip();
}
function dripIlks() public { //inject PUBLIC FUNC TO EXTERNAL
_dripIlks();
}
function _dripIlks() internal {
jug.drip(ETH_A);
jug.drip(BAT_A);
jug.drip(USDC_A);
}
function kickable() public view returns (bool) { //inject PUBLIC FUNC TO EXTERNAL
return _kickable();
}
// Can we bump an auction?
function _kickable() internal view returns (bool) {
// Assume heal is called prior to kick.
// require(vat.dai(address(this)) >= add(add(vat.sin(address(this)), bump), hump), "Vow/insufficient-surplus");
// require(sub(sub(vat.sin(address(this)), Sin), Ash) == 0, "Vow/debt-not-zero");
return (vat.dai(VOW) >= _sysSurplusThreshold());
}
// Burn all of the MKR in the Sai Pit
function finishhim() public returns (uint256 burned) { //inject PUBLIC FUNC TO EXTERNAL
burned = gem.balanceOf(PIT);
_finishhim();
}
function _finishhim() internal {
pit.burn(MKR);
}
// Kick off an auction and return the auction ID
function ccccombobreaker() public returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
_heal(); // Flap requires debt == 0
return vow.flap();
}
// Kick off an auction and throw away id
function _ccccombobreaker() internal {
vow.flap();
}
// Kitchen sink. Call this early and often.
function hadaiken() public { //inject PUBLIC FUNC TO EXTERNAL
_dripPot(); // Update the chi
_dripIlks(); // Updates the Ilk rates
_heal(); // Cancel out system debt with system surplus
if (_kickable()) { _ccccombobreaker(); } // Start an auction
}
} | inject PUBLIC FUNC TO EXTERNAL | function healStat() public returns (uint256 sd) { | 7,265,607 |
/**
*Submitted for verification at Etherscan.io on 2021-05-09
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.0;
//
interface ILowOrbitPropulsor {
function deposit(uint256 amount) external returns (bool);
function withdraw(uint256 amount) external returns (bool);
function pulse(uint256 fees) external returns (bool);
}
//
/**
* @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);
}
//
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
//
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// 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 (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @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) {
return a + b;
}
/**
* @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 a - b;
}
/**
* @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) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting 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 a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards 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).
*
* 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) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* 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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
//
contract LowOrbitERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
address private _owner;
address private _stakingContract;
bool _feesActivated = false;
bool _burnPaused = false;
mapping(address => bool) _excludedFeesAddress;
constructor () {
_owner = msg.sender;
_name = "Low Orbit Crypto Cannon";
_symbol = "LOCC";
// Give all tokens to the owner
_totalSupply = 1000 * (10 ** 18);
_balances[msg.sender] += _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
modifier onlyOwner() {
require(msg.sender == _owner, "LOCC: RESTRICTED_OWNER");
_;
}
function setStakingContract(address newAddr) public onlyOwner returns (bool) {
_stakingContract = newAddr;
return true;
}
function setFeesActivated(bool value) public onlyOwner returns (bool) {
_feesActivated = value;
return true;
}
function setBurnPaused(bool value) public onlyOwner returns (bool) {
_burnPaused = value;
return true;
}
function setExcludedFeesAddr(address addr, bool value) public onlyOwner returns (bool) {
_excludedFeesAddress[addr] = value;
return true;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return 18;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "ERC20: amount 0 not allowed");
require(_balances[sender] >= amount, "ERC20: transfer amount exceeds balance");
if(_feesActivated && !_excludedFeesAddress[sender]) {
uint256 burnAmount = amount.div(100).mul(5);
uint256 stakingAmount = amount.div(100).mul(5);
uint256 amountSubFees = amount.sub(burnAmount).sub(stakingAmount);
// Transfert to the recipient
_balances[sender] = _balances[sender] - amount;
_balances[recipient] += amountSubFees;
emit Transfer(sender, recipient, amountSubFees);
// Burn fees
if(!_burnPaused) {
_burn(sender, burnAmount);
}
else {
if(_stakingContract != address(0)) {
_balances[_stakingContract] += burnAmount;
}
}
// Transfert to the staking contract and call the pulsator
_balances[_stakingContract] += stakingAmount;
if(_stakingContract != address(0)) {
if(_burnPaused) {
ILowOrbitPropulsor(_stakingContract).pulse(stakingAmount.add(burnAmount));
emit Transfer(sender, _stakingContract, stakingAmount.add(burnAmount));
}
else {
ILowOrbitPropulsor(_stakingContract).pulse(stakingAmount);
emit Transfer(sender, _stakingContract, stakingAmount);
}
}
else {
_burn(sender, burnAmount);
}
}
else {
// Transfert to the recipient
_balances[sender] = _balances[sender] - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
function burnFrom(address account, uint256 amount) public {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
} | Transfert to the recipient Burn fees Transfert to the recipient | function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "ERC20: amount 0 not allowed");
require(_balances[sender] >= amount, "ERC20: transfer amount exceeds balance");
if(_feesActivated && !_excludedFeesAddress[sender]) {
uint256 burnAmount = amount.div(100).mul(5);
uint256 stakingAmount = amount.div(100).mul(5);
uint256 amountSubFees = amount.sub(burnAmount).sub(stakingAmount);
_balances[sender] = _balances[sender] - amount;
_balances[recipient] += amountSubFees;
emit Transfer(sender, recipient, amountSubFees);
if(!_burnPaused) {
_burn(sender, burnAmount);
}
else {
if(_stakingContract != address(0)) {
_balances[_stakingContract] += burnAmount;
}
}
if(_stakingContract != address(0)) {
if(_burnPaused) {
ILowOrbitPropulsor(_stakingContract).pulse(stakingAmount.add(burnAmount));
emit Transfer(sender, _stakingContract, stakingAmount.add(burnAmount));
}
else {
ILowOrbitPropulsor(_stakingContract).pulse(stakingAmount);
emit Transfer(sender, _stakingContract, stakingAmount);
}
}
else {
_burn(sender, burnAmount);
}
}
else {
_balances[sender] = _balances[sender] - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
}
| 2,022,247 |
./partial_match/1/0x7a6c874db238D7FdC84516cD940E97032271af69/sources/src/Oracle.sol | Sets max consensus layer gain per block in the contract. See also {maxConsensusLayerGainPerBlockPPT}. maxConsensusLayerGainPerBlockPPT_ The new max consensus layer gain per block in parts per million. | function setMaxConsensusLayerGainPerBlockPPT(uint40 maxConsensusLayerGainPerBlockPPT_)
external
onlyRole(ORACLE_MANAGER_ROLE)
onlyFractionLeqOne(maxConsensusLayerGainPerBlockPPT_, _PPT_DENOMINATOR)
{
maxConsensusLayerGainPerBlockPPT = maxConsensusLayerGainPerBlockPPT_;
emit ProtocolConfigChanged(
this.setMaxConsensusLayerGainPerBlockPPT.selector,
"setMaxConsensusLayerGainPerBlockPPT(uint40)",
abi.encode(maxConsensusLayerGainPerBlockPPT_)
);
}
| 9,343,745 |
./full_match/43114/0xF206f9ACBE69CA5d2166a36F22d5D8e10f2d836D/sources/CowBarn.sol | return the true owner of a cow tokenId the ID of the token return owner - whether or not a token is a Sheep/ | function getRealOwner(uint256 tokenId) public view returns (address owner) {
Stake memory stake = barn[tokenId];
return stake.owner;
}
| 4,635,571 |
pragma solidity >=0.5.0;
interface IdojoswapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IdojoswapPair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IdojoswapBEP20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
/**
* @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;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
interface IBEP20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @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);
}
contract dojoswapBEP20 is IdojoswapBEP20 {
using SafeMath for uint256;
string public constant name = 'SHIBNOBI LPs';
string public constant symbol = 'SLP';
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
constructor() public {
uint256 chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(
address owner,
address spender,
uint256 value
) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(
address from,
address to,
uint256 value
) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool) {
if (allowance[from][msg.sender] != uint256(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, 'dojoswapBEP20: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
//require(recoveredAddress != address(0) && recoveredAddress == owner, 'dojoswapBEP20: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
contract dojoswapPair is IdojoswapPair, dojoswapBEP20 {
using SafeMath for uint256;
using UQ112x112 for uint224;
uint256 public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint256 private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'dojoswapPair: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves()
public
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
)
{
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(
address token,
address to,
uint256 value
) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'dojoswapPair: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'dojoswapPair: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(
uint256 balance0,
uint256 balance1,
uint112 _reserve0,
uint112 _reserve1
) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'dojoswapPair: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IdojoswapFactory(factory).feeTo();
feeOn = feeTo != address(0);
uint256 _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint256 rootK = SafeMath.sqrt(uint256(_reserve0).mul(_reserve1));
uint256 rootKLast = SafeMath.sqrt(_kLast);
if (rootK > rootKLast) {
uint256 numerator = totalSupply.mul(rootK.sub(rootKLast));
uint256 denominator = rootK.mul(5).add(rootKLast);
uint256 liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint256 liquidity) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
uint256 balance0 = IBEP20(token0).balanceOf(address(this));
uint256 balance1 = IBEP20(token1).balanceOf(address(this));
uint256 amount0 = balance0.sub(_reserve0);
uint256 amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = SafeMath.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = SafeMath.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'dojoswapPair: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint256 amount0, uint256 amount1) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint256 balance0 = IBEP20(_token0).balanceOf(address(this));
uint256 balance1 = IBEP20(_token1).balanceOf(address(this));
uint256 liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'dojoswapPair: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IBEP20(_token0).balanceOf(address(this));
balance1 = IBEP20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to
) external lock {
require(amount0Out > 0 || amount1Out > 0, 'dojoswapPair: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'dojoswapPair: INSUFFICIENT_LIQUIDITY');
uint256 balance0;
uint256 balance1;
{
// scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'dojoswapPair: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
balance0 = IBEP20(_token0).balanceOf(address(this));
balance1 = IBEP20(_token1).balanceOf(address(this));
}
uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'dojoswapPair: INSUFFICIENT_INPUT_AMOUNT');
{
// scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint256 balance0Adjusted = balance0.mul(10000).sub(amount0In.mul(25));
uint256 balance1Adjusted = balance1.mul(10000).sub(amount1In.mul(25));
require(
balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(10000**2),
'dojoswapPair: K'
);
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IBEP20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IBEP20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IBEP20(token0).balanceOf(address(this)), IBEP20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
contract dojoswapFactory is IdojoswapFactory {
bytes32 public constant INIT_CODE_PAIR_HASH = keccak256(abi.encodePacked(type(dojoswapPair).creationCode));
address public feeTo;
address public feeToSetter;
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
constructor(address _feeToSetter) public {
feeToSetter = _feeToSetter;
// default feeTo is feeToSetter
feeTo = feeToSetter;
}
function allPairsLength() external view returns (uint256) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(tokenA != tokenB, 'dojoswapFactory: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'dojoswapFactory: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'dojoswapFactory: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(dojoswapPair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
IdojoswapPair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external {
require(msg.sender == feeToSetter, 'dojoswapFactory: FORBIDDEN');
feeTo = _feeTo;
}
function setFeeToSetter(address _feeToSetter) external {
require(msg.sender == feeToSetter, 'dojoswapFactory: FORBIDDEN');
feeToSetter = _feeToSetter;
}
} | 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');
}
| 141,130 |
./partial_match/42/0xbBF04E0f4C31Ff39520227C170e29cb2bAf5787b/sources/RewardEscrow.sol | Allow a user to withdraw any PERI in their schedule that have vested./ The list is sorted; when we reach the first future time, bail out. / | function vest() external {
uint numEntries = _numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty > 0) {
vestingSchedules[msg.sender][i] = [0, 0];
total = total.add(qty);
}
}
if (total != 0) {
totalEscrowedBalance = totalEscrowedBalance.sub(total);
totalEscrowedAccountBalance[msg.sender] = totalEscrowedAccountBalance[msg.sender].sub(total);
totalVestedAccountBalance[msg.sender] = totalVestedAccountBalance[msg.sender].add(total);
IERC20(address(pynthetix)).transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
| 3,308,478 |
./partial_match/1/0x5f428e427096D5085D8d95D64d90f3e7c13C92Fb/sources/P1Deleveraging.sol | Multiplies a value by a base value (result is rounded down)./ | function baseMul(
uint256 value,
uint256 baseValue
)
internal
pure
returns (uint256)
{
return value.mul(baseValue).div(BASE);
}
| 2,651,270 |
./full_match/1/0x7DBF07Ad92Ed4e26D5511b4F285508eBF174135D/sources/contracts/GasUsage.sol | Sets the amount of gas used for a transaction on a given chain. chainId The ID of the chain. gasAmount The amount of gas used on the chain./ | function setGasUsage(uint chainId, uint gasAmount) external onlyOwner {
gasUsage[chainId] = gasAmount;
}
| 17,168,699 |
/* file: openzeppelin-solidity/contracts/ownership/Ownable.sol */
pragma solidity ^0.5.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/* eof (openzeppelin-solidity/contracts/ownership/Ownable.sol) */
/* file: openzeppelin-solidity/contracts/math/SafeMath.sol */
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/* eof (openzeppelin-solidity/contracts/math/SafeMath.sol) */
/* file: ./contracts/utils/Utils.sol */
/**
* @title Manageable Contract
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.5.4;
contract Utils {
/** MODIFIERS **/
modifier onlyValidAddress(address _address) {
require(_address != address(0), "invalid address");
_;
}
}
/* eof (./contracts/utils/Utils.sol) */
/* file: ./contracts/management/Manageable.sol */
/**
* @title Manageable Contract
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.5.4;
contract Manageable is Ownable, Utils {
mapping(address => bool) public isManager; // manager accounts
/** EVENTS **/
event ChangedManager(address indexed manager, bool active);
/** MODIFIERS **/
modifier onlyManager() {
require(isManager[msg.sender], "is not manager");
_;
}
/**
* @notice constructor sets the deployer as a manager
*/
constructor() public {
setManager(msg.sender, true);
}
/**
* @notice enable/disable an account to be a manager
* @param _manager address address of the manager to create/alter
* @param _active bool flag that shows if the manager account is active
*/
function setManager(address _manager, bool _active) public onlyOwner onlyValidAddress(_manager) {
isManager[_manager] = _active;
emit ChangedManager(_manager, _active);
}
}
/* eof (./contracts/management/Manageable.sol) */
/* file: ./contracts/whitelist/GlobalWhitelist.sol */
/**
* @title Global Whitelist Contract
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.5.4;
contract GlobalWhitelist is Ownable, Manageable {
using SafeMath for uint256;
mapping(address => bool) public isWhitelisted; // addresses of who's whitelisted
bool public isWhitelisting = true; // whitelisting enabled by default
/** EVENTS **/
event ChangedWhitelisting(address indexed registrant, bool whitelisted);
event GlobalWhitelistDisabled(address indexed manager);
event GlobalWhitelistEnabled(address indexed manager);
/**
* @dev add an address to the whitelist
* @param _address address
*/
function addAddressToWhitelist(address _address) public onlyManager onlyValidAddress(_address) {
isWhitelisted[_address] = true;
emit ChangedWhitelisting(_address, true);
}
/**
* @dev add addresses to the whitelist
* @param _addresses addresses array
*/
function addAddressesToWhitelist(address[] memory _addresses) public {
for (uint256 i = 0; i < _addresses.length; i++) {
addAddressToWhitelist(_addresses[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param _address address
*/
function removeAddressFromWhitelist(address _address) public onlyManager onlyValidAddress(_address) {
isWhitelisted[_address] = false;
emit ChangedWhitelisting(_address, false);
}
/**
* @dev remove addresses from the whitelist
* @param _addresses addresses
*/
function removeAddressesFromWhitelist(address[] memory _addresses) public {
for (uint256 i = 0; i < _addresses.length; i++) {
removeAddressFromWhitelist(_addresses[i]);
}
}
/**
* @notice toggle the whitelist by the parent contract; ExporoTokenFactory
*/
function toggleWhitelist() public onlyOwner {
isWhitelisting ? isWhitelisting = false : isWhitelisting = true;
if (isWhitelisting) {
emit GlobalWhitelistEnabled(msg.sender);
} else {
emit GlobalWhitelistDisabled(msg.sender);
}
}
}
/* eof (./contracts/whitelist/GlobalWhitelist.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol */
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/IERC20.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol */
pragma solidity ^0.5.0;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* 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
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/ERC20.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol */
pragma solidity ^0.5.0;
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol */
pragma solidity ^0.5.0;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol) */
/* file: openzeppelin-solidity/contracts/access/Roles.sol */
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
/* eof (openzeppelin-solidity/contracts/access/Roles.sol) */
/* file: openzeppelin-solidity/contracts/access/roles/PauserRole.sol */
pragma solidity ^0.5.0;
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/* eof (openzeppelin-solidity/contracts/access/roles/PauserRole.sol) */
/* file: openzeppelin-solidity/contracts/lifecycle/Pausable.sol */
pragma solidity ^0.5.0;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/* eof (openzeppelin-solidity/contracts/lifecycle/Pausable.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol */
pragma solidity ^0.5.0;
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
**/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol) */
/* file: ./contracts/token/ERC20/IERC20Snapshot.sol */
/**
* @title Interface ERC20 SnapshotToken (abstract contract)
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.5.4;
/* solhint-disable no-empty-blocks */
contract IERC20Snapshot {
/**
* @dev Queries the balance of `_owner` at a specific `_blockNumber`
* @param _owner The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at `_blockNumber`
*/
function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint256) {}
/**
* @notice Total amount of tokens at a specific `_blockNumber`.
* @param _blockNumber The block number when the totalSupply is queried
* @return The total amount of tokens at `_blockNumber`
*/
function totalSupplyAt(uint _blockNumber) public view returns(uint256) {}
}
/* eof (./contracts/token/ERC20/IERC20Snapshot.sol) */
/* file: ./contracts/token/ERC20/ERC20Snapshot.sol */
/**
* @title ERC20 Snapshot Token
* inspired by Jordi Baylina's MiniMeToken to record historical balances
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.5.4;
contract ERC20Snapshot is IERC20Snapshot, ERC20 {
using SafeMath for uint256;
/**
* @dev `Snapshot` is the structure that attaches a block number to a
* given value. The block number attached is the one that last changed the value
*/
struct Snapshot {
uint128 fromBlock; // `fromBlock` is the block number at which the value was generated from
uint128 value; // `value` is the amount of tokens at a specific block number
}
/**
* @dev `_snapshotBalances` is the map that tracks the balance of each address, in this
* contract when the balance changes the block number that the change
* occurred is also included in the map
*/
mapping (address => Snapshot[]) private _snapshotBalances;
// Tracks the history of the `_totalSupply` & '_mintedSupply' of the token
Snapshot[] private _snapshotTotalSupply;
/*** FUNCTIONS ***/
/** OVERRIDE
* @dev Send `_value` tokens to `_to` from `msg.sender`
* @param _to The address of the recipient
* @param _value The amount of tokens to be transferred
* @return Whether the transfer was successful or not
*/
function transfer(address _to, uint256 _value) public returns (bool result) {
result = super.transfer(_to, _value);
createSnapshot(msg.sender, _to);
}
/** OVERRIDE
* @dev Send `_value` tokens to `_to` from `_from` on the condition it is approved by `_from`
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _value The amount of tokens to be transferred
* @return True if the transfer was successful
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool result) {
result = super.transferFrom(_from, _to, _value);
createSnapshot(_from, _to);
}
/**
* @dev Queries the balance of `_owner` at a specific `_blockNumber`
* @param _owner The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at `_blockNumber`
*/
function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint256) {
return getValueAt(_snapshotBalances[_owner], _blockNumber);
}
/**
* @dev Total supply cap of tokens at a specific `_blockNumber`.
* @param _blockNumber The block number when the totalSupply is queried
* @return The total supply cap of tokens at `_blockNumber`
*/
function totalSupplyAt(uint _blockNumber) public view returns(uint256) {
return getValueAt(_snapshotTotalSupply, _blockNumber);
}
/*** Internal functions ***/
/**
* @dev Updates snapshot mappings for _from and _to and emit an event
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @return True if the transfer was successful
*/
function createSnapshot(address _from, address _to) internal {
updateValueAtNow(_snapshotBalances[_from], balanceOf(_from));
updateValueAtNow(_snapshotBalances[_to], balanceOf(_to));
}
/**
* @dev `getValueAt` retrieves the number of tokens at a given block number
* @param checkpoints The history of values being queried
* @param _block The block number to retrieve the value at
* @return The number of tokens being queried
*/
function getValueAt(Snapshot[] storage checkpoints, uint _block) internal view returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock) {
return checkpoints[checkpoints.length.sub(1)].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
// Binary search of the value in the array
uint min;
uint max = checkpoints.length.sub(1);
while (max > min) {
uint mid = (max.add(min).add(1)).div(2);
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid.sub(1);
}
}
return checkpoints[min].value;
}
/**
* @dev `updateValueAtNow` used to update the `_snapshotBalances` map and the `_snapshotTotalSupply`
* @param checkpoints The history of data being updated
* @param _value The new number of tokens
*/
function updateValueAtNow(Snapshot[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) {
checkpoints.push(Snapshot(uint128(block.number), uint128(_value)));
} else {
checkpoints[checkpoints.length.sub(1)].value = uint128(_value);
}
}
}
/* eof (./contracts/token/ERC20/ERC20Snapshot.sol) */
/* file: ./contracts/token/ERC20/ERC20ForcedTransfer.sol */
/**
* @title ERC20Confiscatable
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.5.4;
contract ERC20ForcedTransfer is Ownable, ERC20 {
/*** EVENTS ***/
event ForcedTransfer(address indexed account, uint256 amount, address indexed receiver);
/*** FUNCTIONS ***/
/**
* @notice takes funds from _confiscatee and sends them to _receiver
* @param _confiscatee address who's funds are being confiscated
* @param _receiver address who's receiving the funds
*/
function forceTransfer(address _confiscatee, address _receiver) public onlyOwner {
uint256 balance = balanceOf(_confiscatee);
_transfer(_confiscatee, _receiver, balance);
emit ForcedTransfer(_confiscatee, balance, _receiver);
}
}
/* eof (./contracts/token/ERC20/ERC20ForcedTransfer.sol) */
/* file: ./contracts/token/ERC20/ERC20Whitelist.sol */
/**
* @title ERC20Whitelist
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.5.4;
contract ERC20Whitelist is Ownable, ERC20 {
GlobalWhitelist public whitelist;
bool public isWhitelisting = true; // default to true
/** EVENTS **/
event ESTWhitelistingEnabled();
event ESTWhitelistingDisabled();
/*** FUNCTIONS ***/
/**
* @notice disables whitelist per individual EST
* @dev parnent contract, ExporoTokenFactory, is owner
*/
function toggleWhitelist() external onlyOwner {
isWhitelisting ? isWhitelisting = false : isWhitelisting = true;
if (isWhitelisting) {
emit ESTWhitelistingEnabled();
} else {
emit ESTWhitelistingDisabled();
}
}
/** OVERRIDE
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @return bool
*/
function transfer(address _to, uint256 _value) public returns (bool) {
if (checkWhitelistEnabled()) {
checkIfWhitelisted(msg.sender);
checkIfWhitelisted(_to);
}
return super.transfer(_to, _value);
}
/** OVERRIDE
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
* @return bool
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
if (checkWhitelistEnabled()) {
checkIfWhitelisted(_from);
checkIfWhitelisted(_to);
}
return super.transferFrom(_from, _to, _value);
}
/**
* @dev check if whitelisting is in effect versus local and global bools
* @return bool
*/
function checkWhitelistEnabled() public view returns (bool) {
// local whitelist
if (isWhitelisting) {
// global whitelist
if (whitelist.isWhitelisting()) {
return true;
}
}
return false;
}
/*** INTERNAL/PRIVATE ***/
/**
* @dev check if the address has been whitelisted by the Whitelist contract
* @param _account address of the account to check
*/
function checkIfWhitelisted(address _account) internal view {
require(whitelist.isWhitelisted(_account), "not whitelisted");
}
}
/* eof (./contracts/token/ERC20/ERC20Whitelist.sol) */
/* file: ./contracts/token/ERC20/ERC20DocumentRegistry.sol */
/**
* @title ERC20 Document Registry Contract
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.5.4;
/**
* @notice Prospectus and Quarterly Reports stored hashes via IPFS
* @dev read IAgreement for details under /contracts/neufund/standards
*/
// solhint-disable not-rely-on-time
contract ERC20DocumentRegistry is Ownable {
using SafeMath for uint256;
struct HashedDocument {
uint256 timestamp;
string documentUri;
}
// array of all documents
HashedDocument[] private _documents;
event LogDocumentedAdded(string documentUri, uint256 documentIndex);
/**
* @notice adds a document's uri from IPFS to the array
* @param documentUri string
*/
function addDocument(string memory documentUri) public onlyOwner {
require(bytes(documentUri).length > 0, "invalid documentUri");
HashedDocument memory document = HashedDocument({
timestamp: block.timestamp,
documentUri: documentUri
});
_documents.push(document);
emit LogDocumentedAdded(documentUri, _documents.length.sub(1));
}
/**
* @notice fetch the latest document on the array
* @return uint256, string, uint256
*/
function currentDocument() public view
returns (uint256 timestamp, string memory documentUri, uint256 index) {
require(_documents.length > 0, "no documents exist");
uint256 last = _documents.length.sub(1);
HashedDocument storage document = _documents[last];
return (document.timestamp, document.documentUri, last);
}
/**
* @notice adds a document's uri from IPFS to the array
* @param documentIndex uint256
* @return uint256, string, uint256
*/
function getDocument(uint256 documentIndex) public view
returns (uint256 timestamp, string memory documentUri, uint256 index) {
require(documentIndex < _documents.length, "invalid index");
HashedDocument storage document = _documents[documentIndex];
return (document.timestamp, document.documentUri, documentIndex);
}
/**
* @notice return the total amount of documents in the array
* @return uint256
*/
function documentCount() public view returns (uint256) {
return _documents.length;
}
}
/* eof (./contracts/token/ERC20/ERC20DocumentRegistry.sol) */
/* file: ./contracts/exporo/ExporoToken.sol */
/**
* @title Exporo Token Contract
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.5.4;
contract SampleToken is Ownable, ERC20, ERC20Detailed {
/*** FUNCTIONS ***/
/**
* @dev constructor
* @param _name string
* @param _symbol string
* @param _decimal uint8
* @param _initialSupply uint256 initial total supply cap. can be 0
* @param _recipient address to recieve the tokens
*/
/* solhint-disable */
constructor(string memory _name, string memory _symbol, uint8 _decimal, uint256 _initialSupply, address _recipient)
public
ERC20Detailed(_name, _symbol, _decimal) {
_mint(_recipient, _initialSupply);
}
/* solhint-enable */
}
/* eof (./contracts/exporo/ExporoToken.sol) */
/* file: ./contracts/exporo/ExporoTokenFactory.sol */
/**
* @title Exporo Token Factory Contract
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.5.4;
/* solhint-disable max-line-length */
/* solhint-disable separate-by-one-line-in-contract */
contract SampleTokenFactory is Ownable, Manageable {
address public whitelist;
/*** EVENTS ***/
event NewTokenDeployed(address indexed contractAddress, string name, string symbol, uint8 decimals);
/**
* @dev allows owner to launch a new token with a new name, symbol, and decimals.
* Defaults to using whitelist stored in this contract. If _whitelist is address(0), else it will use
* _whitelist as the param to pass into the new token's constructor upon deployment
* @param _name string
* @param _symbol string
* @param _decimals uint8
* @param _initialSupply uint256 initial total supply cap
* @param _recipient address to recieve the initial token supply
*/
function newToken(string memory _name, string memory _symbol, uint8 _decimals, uint256 _initialSupply, address _recipient)
public
onlyManager
onlyValidAddress(_recipient)
returns (address) {
require(bytes(_name).length > 0, "name cannot be blank");
require(bytes(_symbol).length > 0, "symbol cannot be blank");
require(_initialSupply > 0, "supply cannot be 0");
SampleToken token = new SampleToken(_name, _symbol, _decimals, _initialSupply, _recipient);
emit NewTokenDeployed(address(token), _name, _symbol, _decimals);
return address(token);
}
}
/* eof (./contracts/exporo/ExporoTokenFactory.sol) */ | Queries the balance of `_owner` at a specific `_blockNumber` _owner The address from which the balance will be retrieved _blockNumber The block number when the balance is queried return The balance at `_blockNumber`/ | function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint256) {
return getValueAt(_snapshotBalances[_owner], _blockNumber);
}
| 928,261 |
./full_match/10/0x00527534506B88Be2fbeF42451bCeDE98548b5c6/sources/contracts/BountiesMetaTxRelayer.sol | make sure signer doesn't come back as 0x0increase the nonce to prevent replay attacks | function metaRefundContribution(
bytes memory _signature,
uint _bountyId,
uint _contributionId,
uint _nonce)
public
{
bytes32 metaHash = keccak256(abi.encode(address(this),
"metaRefundContribution",
_bountyId,
_contributionId,
_nonce));
address signer = getSigner(metaHash, _signature);
require(signer != address(0));
require(_nonce == replayNonce[signer]);
replayNonce[signer]++;
bountiesContract.refundContribution(signer, _bountyId, _contributionId);
}
| 3,784,146 |
./full_match/80001/0x192fb95e3239E9a3387481718b795CE4a9deFC43/sources/contracts/WAYSPACE.sol | Getter for metadataRenderer contract | function metadataRenderer() external view returns (IMetadataRenderer) {
return IMetadataRenderer(config.metadataRenderer);
}
| 858,691 |
//Address: 0xc22462d4bc50952b061c9e6c585fdd9a04d0d75a
//Contract name: Contribution
//Balance: 0 Ether
//Verification Date: 9/9/2017
//Transacion Count: 6582
// CODE STARTS HERE
pragma solidity ^0.4.15;
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount)
returns(bool);
}
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data);
}
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.1'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
contract CND is MiniMeToken {
/**
* @dev Constructor
*/
uint256 public constant IS_CND_CONTRACT_MAGIC_NUMBER = 0x1338;
function CND(address _tokenFactory)
MiniMeToken(
_tokenFactory,
0x0, // no parent token
0, // no snapshot block number from parent
"Cindicator Token", // Token name
18, // Decimals
"CND", // Symbol
true // Enable transfers
)
{}
function() payable {
require(false);
}
}
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Contribution is Controlled, TokenController {
using SafeMath for uint256;
struct WhitelistedInvestor {
uint256 tier;
bool status;
uint256 contributedAmount;
}
mapping(address => WhitelistedInvestor) investors;
Tier[4] public tiers;
uint256 public tierCount;
MiniMeToken public cnd;
bool public transferable = false;
uint256 public October12_2017 = 1507830400;
address public contributionWallet;
address public foundersWallet;
address public advisorsWallet;
address public bountyWallet;
bool public finalAllocation;
uint256 public totalTokensSold;
bool public paused = false;
modifier notAllocated() {
require(finalAllocation == false);
_;
}
modifier endedSale() {
require(tierCount == 4); //when last one finished it should be equal to 4
_;
}
modifier tokenInitialized() {
assert(address(cnd) != 0x0);
_;
}
modifier initialized() {
Tier tier = tiers[tierCount];
assert(tier.initializedTime() != 0);
_;
}
/// @notice Provides information if contribution is open
/// @return False if the contribuion is closed
function contributionOpen() public constant returns(bool) {
Tier tier = tiers[tierCount];
return (getBlockTimestamp() >= tier.startTime() &&
getBlockTimestamp() <= tier.endTime() &&
tier.finalizedTime() == 0);
}
modifier notPaused() {
require(!paused);
_;
}
function Contribution(address _contributionWallet, address _foundersWallet, address _advisorsWallet, address _bountyWallet) {
require(_contributionWallet != 0x0);
require(_foundersWallet != 0x0);
require(_advisorsWallet != 0x0);
require(_bountyWallet != 0x0);
contributionWallet = _contributionWallet;
foundersWallet = _foundersWallet;
advisorsWallet =_advisorsWallet;
bountyWallet = _bountyWallet;
tierCount = 0;
}
/// @notice Initializes CND token to contribution
/// @param _cnd The address of the token contract that you want to set
function initializeToken(address _cnd) public onlyController {
assert(CND(_cnd).controller() == address(this));
assert(CND(_cnd).IS_CND_CONTRACT_MAGIC_NUMBER() == 0x1338);
require(_cnd != 0x0);
cnd = CND(_cnd);
}
/// @notice Initializes Tier contribution
/// @param _tierNumber number of tier to initialize
/// @param _tierAddress address of deployed tier
function initializeTier(
uint256 _tierNumber,
address _tierAddress
) public onlyController tokenInitialized
{
Tier tier = Tier(_tierAddress);
assert(tier.controller() == address(this));
//cannot be more than 4 tiers
require(_tierNumber >= 0 && _tierNumber <= 3);
assert(tier.IS_TIER_CONTRACT_MAGIC_NUMBER() == 0x1337);
// check if tier is not defined
assert(tiers[_tierNumber] == address(0));
tiers[_tierNumber] = tier;
InitializedTier(_tierNumber, _tierAddress);
}
/// @notice If anybody sends Ether directly to this contract, consider the sender will
/// be rejected.
function () public {
require(false);
}
/// @notice Amount of tokens an investor can purchase
/// @param _investor investor address
/// @return number of tokens
function investorAmountTokensToBuy(address _investor) public constant returns(uint256) {
WhitelistedInvestor memory investor = investors[_investor];
Tier tier = tiers[tierCount];
uint256 leftToBuy = tier.maxInvestorCap().sub(investor.contributedAmount).mul(tier.exchangeRate());
return leftToBuy;
}
/// @notice Notifies if an investor is whitelisted for contribution
/// @param _investor investor address
/// @param _tier tier Number
/// @return number of tokens
function isWhitelisted(address _investor, uint256 _tier) public constant returns(bool) {
WhitelistedInvestor memory investor = investors[_investor];
return (investor.tier <= _tier && investor.status);
}
/// @notice interface for founders to whitelist investors
/// @param _addresses array of investors
/// @param _tier tier Number
/// @param _status enable or disable
function whitelistAddresses(address[] _addresses, uint256 _tier, bool _status) public onlyController {
for (uint256 i = 0; i < _addresses.length; i++) {
address investorAddress = _addresses[i];
require(investors[investorAddress].contributedAmount == 0);
investors[investorAddress] = WhitelistedInvestor(_tier, _status, 0);
}
}
/// @notice Public function to buy tokens
function buy() public payable {
proxyPayment(msg.sender);
}
/// use buy function instead of proxyPayment
/// the param address is useless, it always reassigns to msg.sender
function proxyPayment(address) public payable
notPaused
initialized
returns (bool)
{
assert(isCurrentTierCapReached() == false);
assert(contributionOpen());
require(isWhitelisted(msg.sender, tierCount));
doBuy();
return true;
}
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @return False if the controller does not authorize the transfer
function onTransfer(address /* _from */, address /* _to */, uint256 /* _amount */) returns(bool) {
return (transferable || getBlockTimestamp() >= October12_2017 );
}
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @return False if the controller does not authorize the approval
function onApprove(address /* _owner */, address /* _spender */, uint /* _amount */) returns(bool) {
return (transferable || getBlockTimestamp() >= October12_2017);
}
/// @notice Allows founders to set transfers before October12_2017
/// @param _transferable set True if founders want to let people make transfers
function allowTransfers(bool _transferable) onlyController {
transferable = _transferable;
}
/// @notice calculates how many tokens left for sale
/// @return Number of tokens left for tier
function leftForSale() public constant returns(uint256) {
Tier tier = tiers[tierCount];
uint256 weiLeft = tier.cap().sub(tier.totalInvestedWei());
uint256 tokensLeft = weiLeft.mul(tier.exchangeRate());
return tokensLeft;
}
/// @notice actual method that funds investor and contribution wallet
function doBuy() internal {
Tier tier = tiers[tierCount];
assert(msg.value <= tier.maxInvestorCap());
address caller = msg.sender;
WhitelistedInvestor storage investor = investors[caller];
uint256 investorTokenBP = investorAmountTokensToBuy(caller);
require(investorTokenBP > 0);
if(investor.contributedAmount == 0) {
assert(msg.value >= tier.minInvestorCap());
}
uint256 toFund = msg.value;
uint256 tokensGenerated = toFund.mul(tier.exchangeRate());
// check that at least 1 token will be generated
require(tokensGenerated >= 1);
uint256 tokensleftForSale = leftForSale();
if(tokensleftForSale > investorTokenBP ) {
if(tokensGenerated > investorTokenBP) {
tokensGenerated = investorTokenBP;
toFund = investorTokenBP.div(tier.exchangeRate());
}
}
if(investorTokenBP > tokensleftForSale) {
if(tokensGenerated > tokensleftForSale) {
tokensGenerated = tokensleftForSale;
toFund = tokensleftForSale.div(tier.exchangeRate());
}
}
investor.contributedAmount = investor.contributedAmount.add(toFund);
tier.increaseInvestedWei(toFund);
if (tokensGenerated == tokensleftForSale) {
finalize();
}
assert(cnd.generateTokens(caller, tokensGenerated));
totalTokensSold = totalTokensSold.add(tokensGenerated);
contributionWallet.transfer(toFund);
NewSale(caller, toFund, tokensGenerated);
uint256 toReturn = msg.value.sub(toFund);
if (toReturn > 0) {
caller.transfer(toReturn);
Refund(toReturn);
}
}
/// @notice This method will can be called by the anybody to make final allocation
/// @return result if everything went succesfully
function allocate() public notAllocated endedSale returns(bool) {
finalAllocation = true;
uint256 totalSupplyCDN = totalTokensSold.mul(100).div(75); // calculate 100%
uint256 foundersAllocation = totalSupplyCDN.div(5); // 20% goes to founders
assert(cnd.generateTokens(foundersWallet, foundersAllocation));
uint256 advisorsAllocation = totalSupplyCDN.mul(38).div(1000); // 3.8% goes to advisors
assert(cnd.generateTokens(advisorsWallet, advisorsAllocation));
uint256 bountyAllocation = totalSupplyCDN.mul(12).div(1000); // 1.2% goes to bounty program
assert(cnd.generateTokens(bountyWallet, bountyAllocation));
return true;
}
/// @notice This method will can be called by the controller after the contribution period
/// end or by anybody after the `endTime`. This method finalizes the contribution period
function finalize() public initialized {
Tier tier = tiers[tierCount];
assert(tier.finalizedTime() == 0);
assert(getBlockTimestamp() >= tier.startTime());
assert(msg.sender == controller || getBlockTimestamp() > tier.endTime() || isCurrentTierCapReached());
tier.finalize();
tierCount++;
FinalizedTier(tierCount, tier.finalizedTime());
}
/// @notice check if tier cap has reached
/// @return False if it's still open
function isCurrentTierCapReached() public constant returns(bool) {
Tier tier = tiers[tierCount];
return tier.isCapReached();
}
//////////
// Testing specific methods
//////////
function getBlockTimestamp() internal constant returns (uint256) {
return block.timestamp;
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (cnd.controller() == address(this)) {
cnd.claimTokens(_token);
}
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
CND token = CND(_token);
uint256 balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
/// @notice Pauses the contribution if there is any issue
function pauseContribution(bool _paused) onlyController {
paused = _paused;
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount);
event NewSale(address indexed _th, uint256 _amount, uint256 _tokens);
event InitializedTier(uint256 _tierNumber, address _tierAddress);
event FinalizedTier(uint256 _tierCount, uint256 _now);
event Refund(uint256 _amount);
}
contract Tier is Controlled {
using SafeMath for uint256;
uint256 public cap;
uint256 public exchangeRate;
uint256 public minInvestorCap;
uint256 public maxInvestorCap;
uint256 public startTime;
uint256 public endTime;
uint256 public initializedTime;
uint256 public finalizedTime;
uint256 public totalInvestedWei;
uint256 public constant IS_TIER_CONTRACT_MAGIC_NUMBER = 0x1337;
modifier notFinished() {
require(finalizedTime == 0);
_;
}
function Tier(
uint256 _cap,
uint256 _minInvestorCap,
uint256 _maxInvestorCap,
uint256 _exchangeRate,
uint256 _startTime,
uint256 _endTime
)
{
require(initializedTime == 0);
assert(_startTime >= getBlockTimestamp());
require(_startTime < _endTime);
startTime = _startTime;
endTime = _endTime;
require(_cap > 0);
require(_cap > _maxInvestorCap);
cap = _cap;
require(_minInvestorCap < _maxInvestorCap && _maxInvestorCap > 0);
minInvestorCap = _minInvestorCap;
maxInvestorCap = _maxInvestorCap;
require(_exchangeRate > 0);
exchangeRate = _exchangeRate;
initializedTime = getBlockTimestamp();
InitializedTier(_cap, _minInvestorCap, maxInvestorCap, _startTime, _endTime);
}
function getBlockTimestamp() internal constant returns (uint256) {
return block.timestamp;
}
function isCapReached() public constant returns(bool) {
return totalInvestedWei == cap;
}
function finalize() public onlyController {
require(finalizedTime == 0);
uint256 currentTime = getBlockTimestamp();
assert(cap == totalInvestedWei || currentTime > endTime || msg.sender == controller);
finalizedTime = currentTime;
}
function increaseInvestedWei(uint256 _wei) external onlyController notFinished {
totalInvestedWei = totalInvestedWei.add(_wei);
IncreaseInvestedWeiAmount(_wei, totalInvestedWei);
}
event InitializedTier(
uint256 _cap,
uint256 _minInvestorCap,
uint256 _maxInvestorCap,
uint256 _startTime,
uint256 _endTime
);
function () public {
require(false);
}
event IncreaseInvestedWeiAmount(uint256 _amount, uint256 _newWei);
}
| Queries the balance of `_owner` at a specific `_blockNumber` _owner The address from which the balance will be retrieved _blockNumber The block number when the balance is queried return The balance at `_blockNumber` These next few lines are used when the balance of the token is requested before a check point was ever created for this token, it requires that the `parentToken.balanceOfAt` be queried at the genesis block for that token as this contains initial balance of this token Has no parent | function balanceOfAt(address _owner, uint _blockNumber) constant
returns (uint) {
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
return 0;
}
return getValueAt(balances[_owner], _blockNumber);
}
}
| 931,640 |
./full_match/42/0x598884ccEfDEaE1F80872d82632C22f79Acbc0a6/sources/contracts/LegoConstruct.sol | Create a new brick collection This sets the delegate of the brick collection to whoever creates it. originLego the ID of the brick to base the collection on. originRotation orientation of teh base brick./ | function create(uint originLego, uint originRotation) public requireLego(originLego) {
counter.increment();
_mint(msg.sender, counter.current());
console.log("creating construct");
uint graphID = graph.create(originLego, originRotation);
graphGovernances[graphID] = GraphGovernance({
delegate: msg.sender,
members: new address[](0)
});
graphGovernances[graphID].members.push(msg.sender);
graphIDs[counter.current()] = graphID;
}
| 16,291,231 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
contract Auction is Ownable, Pausable, VRFConsumerBase {
using Counters for Counters.Counter;
uint256 public immutable minimumUnitPrice;
uint256 public immutable minimumBidIncrement;
uint256 public immutable unitPriceStepSize;
uint256 public immutable minimumQuantity;
uint256 public immutable maximumQuantity;
uint256 public immutable numberOfAuctions;
uint256 public immutable itemsPerAuction;
address payable public immutable beneficiaryAddress;
uint256 public lastRandomNumber;
// Auction ends in last 3hrs when this random number is observed
uint256 constant auctionLengthInHours = 72;
// The target number for the random end's random number generator
uint256 constant randomEnd = 3;
// block timestamp of when auction starts
uint256 public auctionStart;
AuctionStatus private _auctionStatus;
Counters.Counter private _bidIndex;
// Chainlink configuration.
bytes32 internal keyHash;
uint256 internal fee;
event AuctionStarted();
event AuctionEnded();
event BidPlaced(
bytes32 indexed bidHash,
uint256 indexed auctionIndex,
address indexed bidder,
uint256 bidIndex,
uint256 unitPrice,
uint256 quantity,
uint256 balance
);
event WinnerSelected(
uint256 indexed auctionIndex,
address indexed bidder,
uint256 unitPrice,
uint256 quantity
);
event BidderRefunded(
uint256 indexed auctionIndex,
address indexed bidder,
uint256 refundAmount
);
struct Bid {
uint256 unitPrice;
uint256 quantity;
uint256 balance;
}
struct AuctionStatus {
bool started;
bool ended;
}
// keccak256(auctionIndex, bidder address) => current bid
mapping(bytes32 => Bid) private _bids;
// auctionID => remainingItemsPerAuction
mapping(uint256 => uint256) private _remainingItemsPerAuction;
// Beneficiary address cannot be changed after deployment.
constructor(
address payable _beneficiaryAddress,
uint256 _minimumUnitPrice,
uint256 _minimumBidIncrement,
uint256 _unitPriceStepSize,
uint256 _maximumQuantity,
uint256 _numberOfAuctions,
uint256 _itemsPerAuction,
address vrfCoordinator_,
address link_,
bytes32 keyHash_,
uint256 fee_
) VRFConsumerBase(vrfCoordinator_, link_) {
beneficiaryAddress = _beneficiaryAddress;
minimumUnitPrice = _minimumUnitPrice;
minimumBidIncrement = _minimumBidIncrement;
unitPriceStepSize = _unitPriceStepSize;
minimumQuantity = 1;
maximumQuantity = _maximumQuantity;
numberOfAuctions = _numberOfAuctions;
itemsPerAuction = _itemsPerAuction;
keyHash = keyHash_;
fee = fee_;
// Set up the _remainingItemsPerAuction tracker.
for (uint256 i = 0; i < _numberOfAuctions; i++) {
_remainingItemsPerAuction[i] = _itemsPerAuction;
}
pause();
}
modifier whenAuctionActive() {
require(!_auctionStatus.ended, "Auction has already ended");
require(_auctionStatus.started, "Auction hasn't started yet");
_;
}
modifier whenPreAuction() {
require(!_auctionStatus.ended, "Auction has already ended");
require(!_auctionStatus.started, "Auction has already started");
_;
}
modifier whenAuctionEnded() {
require(_auctionStatus.ended, "Auction hasn't ended yet");
require(_auctionStatus.started, "Auction hasn't started yet");
_;
}
function auctionStatus() public view returns (AuctionStatus memory) {
return _auctionStatus;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function startAuction() external onlyOwner whenPreAuction {
_auctionStatus.started = true;
auctionStart = block.timestamp;
if (paused()) {
unpause();
}
emit AuctionStarted();
}
function endAuction() external onlyOwner whenAuctionActive {
require(
block.timestamp >= (auctionStart + auctionLengthInHours * 60 * 60),
"Auction can't be stopped until due"
);
_endAuction();
}
function _endAuction() internal whenAuctionActive {
_auctionStatus.ended = true;
emit AuctionEnded();
}
// Requests randomness.
function getRandomNumber() internal returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK");
return requestRandomness(keyHash, fee);
}
// Callback function used by VRF Coordinator.
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
override
{
lastRandomNumber = randomness;
if (randomness % 20 == randomEnd) {
_endAuction();
}
}
function attemptEndAuction() external onlyOwner whenAuctionActive {
getRandomNumber();
}
function numberOfBidsPlaced() external view returns (uint256) {
return _bidIndex.current();
}
function getBid(uint256 auctionIndex, address bidder)
external
view
returns (Bid memory)
{
return _bids[_bidHash(auctionIndex, bidder)];
}
function getRemainingItemsForAuction(uint256 auctionIndex)
external
view
returns (uint256)
{
require(auctionIndex < numberOfAuctions, "Invalid auctionIndex");
return _remainingItemsPerAuction[auctionIndex];
}
function _bidHash(uint256 auctionIndex_, address bidder_)
internal
pure
returns (bytes32)
{
return keccak256(abi.encode(auctionIndex_, bidder_));
}
function selectWinners(
uint256 auctionIndex_,
address[] calldata bidders_,
uint256[] calldata quantities_
) external onlyOwner whenPaused whenAuctionEnded {
// Ensure auctionIndex is within valid range.
require(auctionIndex_ < numberOfAuctions, "Invalid auctionIndex");
require(
bidders_.length == quantities_.length,
"bidders length doesn't match quantities length"
);
uint256 tmpRemainingItemsPerAuction = _remainingItemsPerAuction[
auctionIndex_
];
// Iterate over each winning address until we reach the end of the winners list or we deplete _remainingItemsPerAuction for this auctionIndex_.
for (uint256 i = 0; i < bidders_.length; i++) {
address bidder = bidders_[i];
uint256 quantity = quantities_[i];
bytes32 bidHash = _bidHash(auctionIndex_, bidder);
uint256 bidUnitPrice = _bids[bidHash].unitPrice;
uint256 maxAvailableQuantity = _bids[bidHash].quantity;
// Skip bidders whose remaining bid quantity is already 0, or who have function input quantity set to 0.
if (maxAvailableQuantity == 0 || quantity == 0) {
continue;
}
require(
quantity >= maxAvailableQuantity,
"quantity is greater than max quantity"
);
if (tmpRemainingItemsPerAuction == quantity) {
// STOP: _remainingItemsPerAuction has been depleted, and the quantity for this bid made us hit 0 exactly.
_bids[bidHash].quantity = 0;
emit WinnerSelected(auctionIndex_, bidder, bidUnitPrice, quantity);
_remainingItemsPerAuction[auctionIndex_] = 0;
return;
} else if (tmpRemainingItemsPerAuction < quantity) {
// STOP: _remainingItemsPerAuction has been depleted, and the quantity for this bid made us go negative (quantity too high to give the bidder all they asked for)
emit WinnerSelected(
auctionIndex_,
bidder,
bidUnitPrice,
tmpRemainingItemsPerAuction
);
// Don't set unitPrice to 0 here as there is still at least 1 quantity remaining.
// Must set _remainingItemsPerAuction to 0 AFTER this.
_bids[bidHash].quantity -= tmpRemainingItemsPerAuction;
_remainingItemsPerAuction[auctionIndex_] = 0;
return;
} else {
// CONTINUE: _remainingItemsPerAuction hasn't been depleted yet...
_bids[bidHash].quantity = 0;
emit WinnerSelected(auctionIndex_, bidder, bidUnitPrice, quantity);
tmpRemainingItemsPerAuction -= quantity;
}
}
// If reached this point, _remainingItemsPerAuction hasn't been depleted but we've run out of bidders to select as winners. Set the final storage value.
_remainingItemsPerAuction[auctionIndex_] = tmpRemainingItemsPerAuction;
}
// Refunds losing bidders from the contract's balance.
function partiallyRefundBidders(
uint256 auctionIndex_,
address payable[] calldata bidders_,
uint256[] calldata amounts_
) external onlyOwner whenPaused whenAuctionEnded {
require(
bidders_.length == amounts_.length,
"bidders length doesn't match amounts length"
);
for (uint256 i = 0; i < bidders_.length; i++) {
address payable bidder = bidders_[i];
uint256 refundAmount = amounts_[i];
bytes32 bidHash = _bidHash(auctionIndex_, bidder);
uint256 refundMaximum = _bids[bidHash].balance;
require(
refundAmount <= refundMaximum,
"Refund amount is greater than balance"
);
// Skip bidders who aren't entitled to a refund.
if (refundAmount == 0 || refundMaximum == 0) {
continue;
}
_bids[bidHash].balance -= refundAmount;
(bool success, ) = bidder.call{value: refundAmount}("");
require(success, "Transfer failed.");
emit BidderRefunded(auctionIndex_, bidder, refundAmount);
}
}
// When a bidder places a bid or updates their existing bid, they will use this function.
// - total value can never be lowered
// - unit price can never be lowered
// - quantity can be raised or lowered, but only if unit price is raised to meet or exceed previous total price
function placeBid(
uint256 auctionIndex,
uint256 quantity,
uint256 unitPrice
) external payable whenNotPaused whenAuctionActive {
// If the bidder is increasing their bid, the amount being added must be greater than or equal to the minimum bid increment.
if (msg.value > 0 && msg.value < minimumBidIncrement) {
revert("Bid lower than minimum bid increment.");
}
// Ensure auctionIndex is within valid range.
require(auctionIndex < numberOfAuctions, "Invalid auctionIndex");
// Cache initial bid values.
bytes32 bidHash = _bidHash(auctionIndex, msg.sender);
uint256 initialUnitPrice = _bids[bidHash].unitPrice;
uint256 initialQuantity = _bids[bidHash].quantity;
uint256 initialBalance = _bids[bidHash].balance;
// Cache final bid values.
uint256 finalUnitPrice = unitPrice;
uint256 finalQuantity = quantity;
uint256 finalBalance = initialBalance + msg.value;
// Don't allow bids with a unit price scale smaller than unitPriceStepSize.
// For example, allow 1.01 or 111.01 but don't allow 1.011.
require(
finalUnitPrice % unitPriceStepSize == 0,
"Unit price step too small"
);
// Reject bids that don't have a quantity within the valid range.
require(finalQuantity >= minimumQuantity, "Quantity too low");
require(finalQuantity <= maximumQuantity, "Quantity too high");
// Total value can never be lowered.
require(finalBalance >= initialBalance, "Total value can't be lowered");
// Unit price can never be lowered.
// Quantity can be raised or lowered, but it can only be lowered if the unit price is raised to meet or exceed the initial total value. Ensuring the the unit price is never lowered takes care of this.
require(finalUnitPrice >= initialUnitPrice, "Unit price can't be lowered");
// Ensure the new finalBalance equals quantity * the unit price that was given in this txn exactly. This is important to prevent rounding errors later when returning ether.
require(
finalQuantity * finalUnitPrice == finalBalance,
"Quantity * Unit Price != Total Value"
);
// Unit price must be greater than or equal to the minimumUnitPrice.
require(finalUnitPrice >= minimumUnitPrice, "Bid unit price too low");
// Something must be changing from the initial bid for this new bid to be valid.
if (
initialUnitPrice == finalUnitPrice && initialQuantity == finalQuantity
) {
revert("This bid doesn't change anything");
}
// Update the bidder's bid.
_bids[bidHash].unitPrice = finalUnitPrice;
_bids[bidHash].quantity = finalQuantity;
_bids[bidHash].balance = finalBalance;
emit BidPlaced(
bidHash,
auctionIndex,
msg.sender,
_bidIndex.current(),
finalUnitPrice,
finalQuantity,
_bids[bidHash].balance
);
// Increment after emitting the BidPlaced event because counter is 0-indexed.
_bidIndex.increment();
}
function withdrawContractBalance() external onlyOwner {
(bool success, ) = beneficiaryAddress.call{value: address(this).balance}(
""
);
require(success, "Transfer failed");
}
// Handles receiving ether to the contract.
// Reject all direct payments to the contract except from beneficiary and owner.
// Bids must be placed using the placeBid function.
receive() external payable {
require(msg.value > 0, "No ether was sent");
require(
msg.sender == beneficiaryAddress || msg.sender == owner(),
"Only owner or beneficiary can fund contract"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(
bytes32 requestId,
uint256 randomness
)
internal
virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 constant private USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee
)
internal
returns (
bytes32 requestId
)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(
address _vrfCoordinator,
address _link
) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(
bytes32 requestId,
uint256 randomness
)
external
{
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(
address owner,
address spender
)
external
view
returns (
uint256 remaining
);
function approve(
address spender,
uint256 value
)
external
returns (
bool success
);
function balanceOf(
address owner
)
external
view
returns (
uint256 balance
);
function decimals()
external
view
returns (
uint8 decimalPlaces
);
function decreaseApproval(
address spender,
uint256 addedValue
)
external
returns (
bool success
);
function increaseApproval(
address spender,
uint256 subtractedValue
) external;
function name()
external
view
returns (
string memory tokenName
);
function symbol()
external
view
returns (
string memory tokenSymbol
);
function totalSupply()
external
view
returns (
uint256 totalTokensIssued
);
function transfer(
address to,
uint256 value
)
external
returns (
bool success
);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
)
external
returns (
bool success
);
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (
bool success
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
)
internal
pure
returns (
uint256
)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash,
uint256 _vRFInputSeed
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
} | Refunds losing bidders from the contract's balance. Skip bidders who aren't entitled to a refund. | function partiallyRefundBidders(
uint256 auctionIndex_,
address payable[] calldata bidders_,
uint256[] calldata amounts_
) external onlyOwner whenPaused whenAuctionEnded {
require(
bidders_.length == amounts_.length,
"bidders length doesn't match amounts length"
);
for (uint256 i = 0; i < bidders_.length; i++) {
address payable bidder = bidders_[i];
uint256 refundAmount = amounts_[i];
bytes32 bidHash = _bidHash(auctionIndex_, bidder);
uint256 refundMaximum = _bids[bidHash].balance;
require(
refundAmount <= refundMaximum,
"Refund amount is greater than balance"
);
if (refundAmount == 0 || refundMaximum == 0) {
continue;
}
_bids[bidHash].balance -= refundAmount;
require(success, "Transfer failed.");
emit BidderRefunded(auctionIndex_, bidder, refundAmount);
}
}
| 1,436,805 |
// SPDX-License-Identifier: MIT
// dev: @brougkr
/**@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,.................................#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%............................................../@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@........................................................%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@,[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@......................................................................#@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@.............,,***[email protected]@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@..............,******...........................................................*@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@#.................,***,[email protected]@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@%........................................................................................,@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@.......,**,.................................................................................#@@@@@@@@@@@@@
@@@@@@@@@@@@*................................[email protected]@@@@@@@@@@@
@@@@@@@@@@@...................................[email protected]@@@@@@@@@@
@@@@@@@@@@..................................................................................................../@@@@@@@@@
@@@@@@@@@........,............................................................................................./@@@@@@@@
@@@@@@@@........,,..............................................................................................#@@@@@@@
@@@@@@@........,,.................................[email protected]@@@@@@
@@@@@@(........**..,*****,.........................[email protected]@@@@@
@@@@@@........,*,..,****,,........................................................................................&@@@@@
@@@@@%........***,................................................................................................,@@@@@
@@@@@,........**,*..................................[email protected]@@@@
@@@@@........,****..................................[email protected]@@@@
@@@@@........,**,**.................................[email protected]@@@@
@@@@@.........*****, ................,*******....[email protected]@@@@
@@@@@*........**,***. ..............********,..Moonopoly [email protected]@@@@
@@@@@&......... ,**. ...............******.........**........................................................,@@@@@
@@@@@@..... *. ...............................,,[email protected]@@@@@
@@@@@@%... .*,...........................[email protected]@@@@@
@@@@@@@.... ,***........... ......[email protected]@@@@@@
@@@@@@@@.... .******,......... ............... ..................................................&@@@@@@@
@@@@@@@@@.........,,,,,,,,,,,......... .....,,,,,..........................................................%@@@@@@@@
@@@@@@@@@@..........**********,..................,,...........................................................&@@@@@@@@@
@@@@@@@@@@@..........***....,***,...............................................,**[email protected]@@@@@@@@@@
@@@@@@@@@@@@%..........*....****,**,..........................................,*****,......................,@@@@@@@@@@@@
@@@@@@@@@@@@@@...........*******,*****,.........,***,.......,,.................,,**,[email protected]@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@...........*****,,,*******.....******.....,****.........................................(@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@...........,.......*********,..,,.................................................../@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@.................**************,.......................................,,.......&@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@#.............,***,***,***,***,**,..........................,,,***,........,@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@*..............,******,.,******......**,*******************,[email protected]@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@&................. .*************,*************,............*@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#.......................,,,,****,,,,,..................*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(............................................,@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*...............................%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&&%%&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@**/
pragma solidity 0.8.11;
import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
contract MoonopolyV1 is ERC1155Upgradeable, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable
{
// Initialization
string public constant name = "Moonopoly";
string public constant symbol = "MOON";
string public _BASE_URI;
// Variables
uint256 public _CARDS_MINTED;
uint256 public _MAX_CARDS;
uint256 public _MAX_CARDS_PURCHASE;
uint256 public _AIRDROP_AMOUNT;
uint256 public _CARD_PRICE;
uint256 public _UNIQUE_CARDS;
uint256 public _MINIMUM_CARD_INDEX;
uint256 private _randomSeed;
// Sale State
bool public _SALE_ACTIVE;
bool public _AIRDROP_ACTIVE;
bool public _ALLOW_MULTIPLE_PURCHASES;
// Mappings
mapping (uint256 => uint256) public _CARD_ID_ALLOCATION;
mapping (address => bool) public minted;
mapping (address => uint256) public airdrop;
// Events
event MoonopolyAirdropClaimed(address indexed recipient, uint256 indexed amt);
event MoonopolyPublicMint(address indexed recipient, uint256 indexed amt);
event AddAirdropRecipients(address[] wallets);
/**
* @dev Proxy Initializer
*/
function initialize() public initializer
{
__Context_init_unchained(); // Init Context
__ERC1155_init_unchained("https://ipfs.io/ipfs/QmUQBkrxxk9dm78zhzNR41FmHPYrXKUB1QCAJ4ewtRPX7s/{id}.json"); // Init ERC1155
__Ownable_init_unchained(); // Init Ownable
__Pausable_init_unchained(); // Init Pausable
transferOwnership(0x366DA24FD360C5789A5bEb2bE0e72a0FF3BD853C);
_BASE_URI = "https://ipfs.io/ipfs/QmUQBkrxxk9dm78zhzNR41FmHPYrXKUB1QCAJ4ewtRPX7s/";
_CARDS_MINTED = 1;
_MAX_CARDS = 5555;
_MAX_CARDS_PURCHASE = 5;
_AIRDROP_AMOUNT = 3;
_CARD_PRICE = 0.03 ether;
_UNIQUE_CARDS = 33;
_MINIMUM_CARD_INDEX = 1;
_randomSeed = 0x00;
_SALE_ACTIVE = false;
_AIRDROP_ACTIVE = true;
_ALLOW_MULTIPLE_PURCHASES = true;
_CARD_ID_ALLOCATION[1] = 1; // Lagos Full Miner
_CARD_ID_ALLOCATION[2] = 3; // Lagos 4 Node
_CARD_ID_ALLOCATION[3] = 5; // Lagos 3 Node
_CARD_ID_ALLOCATION[4] = 7; // Lagos 2 Node
_CARD_ID_ALLOCATION[5] = 9; // Lagos 1 Node
_CARD_ID_ALLOCATION[6] = 40; // Miami
_CARD_ID_ALLOCATION[7] = 40; // NYC
_CARD_ID_ALLOCATION[8] = 60; // Beijing
_CARD_ID_ALLOCATION[9] = 60; // Shanghai
_CARD_ID_ALLOCATION[10] = 60; // Hong Kong
_CARD_ID_ALLOCATION[11] = 90; // Mumbai
_CARD_ID_ALLOCATION[12] = 90; // New Delhi
_CARD_ID_ALLOCATION[13] = 90; // Kolkata
_CARD_ID_ALLOCATION[14] = 100; // Zurich
_CARD_ID_ALLOCATION[15] = 100; // Geneva
_CARD_ID_ALLOCATION[16] = 100; // Basel
_CARD_ID_ALLOCATION[17] = 150; // Lima
_CARD_ID_ALLOCATION[18] = 150; // Cusko
_CARD_ID_ALLOCATION[19] = 150; // Arequipa
_CARD_ID_ALLOCATION[20] = 250; // Istanbul
_CARD_ID_ALLOCATION[21] = 250; // Ankara
_CARD_ID_ALLOCATION[22] = 250; // Izmir
_CARD_ID_ALLOCATION[23] = 300; // Davao
_CARD_ID_ALLOCATION[24] = 300; // Manila
_CARD_ID_ALLOCATION[25] = 300; // Bohol
_CARD_ID_ALLOCATION[26] = 400; // Saigon
_CARD_ID_ALLOCATION[27] = 400; // Hanoi
_CARD_ID_ALLOCATION[28] = 200; // Coinbase
_CARD_ID_ALLOCATION[29] = 200; // Binance
_CARD_ID_ALLOCATION[30] = 200; // Gemini
_CARD_ID_ALLOCATION[31] = 200; // Kraken
_CARD_ID_ALLOCATION[32] = 500; // Solar
_CARD_ID_ALLOCATION[33] = 500; // Wind
}
/*---------------------*
* PUBLIC FUNCTIONS *
*----------------------*/
/**
* @dev Moonopoly Public Mint
*/
function MoonopolyMint(uint256 numberOfTokens) public payable nonReentrant
{
require(_SALE_ACTIVE, "Public Sale Must Be Active To Mint Cards");
require(numberOfTokens <= _MAX_CARDS_PURCHASE, "Can Only Mint 5 Cards At A Time");
require(_CARDS_MINTED + numberOfTokens <= _MAX_CARDS, "Purchase Would Exceed Max Supply Of Cards");
require(_CARD_PRICE * numberOfTokens == msg.value, "Ether Value Sent Is Not Correct.");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
minted[msg.sender] = true;
for(uint256 i = 0; i < numberOfTokens; i++)
{
uint256 cardID = _drawCard(numberOfTokens);
_CARD_ID_ALLOCATION[cardID] -= 1;
_CARDS_MINTED += 1;
_mint(msg.sender, cardID, 1, "");
}
emit MoonopolyPublicMint(msg.sender, numberOfTokens);
}
/**
* @dev Moonopoly Airdrop
*/
function MoonopolyAirdrop() public nonReentrant
{
require(_AIRDROP_ACTIVE, "Airdrop is not active");
uint256 amt = airdrop[msg.sender];
require(amt > 0, "Sender wallet is not on airdrop Access List");
airdrop[msg.sender] = 0;
for(uint256 i = 0; i < amt; i++)
{
uint256 cardID = _drawCard(amt);
_CARD_ID_ALLOCATION[cardID] -= 1;
_CARDS_MINTED += 1;
_mint(msg.sender, cardID, 1, "");
}
emit MoonopolyAirdropClaimed(msg.sender, amt);
}
/*---------------------*
* PRIVATE FUNCTIONS *
*----------------------*/
/**
* @dev Draws Pseudorandom Card From Available Stack
*/
function _drawCard(uint256 salt) private returns (uint256)
{
for (uint256 i = 1; i < 4; i++)
{
uint256 value = _pseudoRandom(i + _CARDS_MINTED + salt);
if (_canMint(value))
{
_randomSeed = value;
return value;
}
}
// If Pseudorandom Card Is Not Valid After 3 Tries, Draw From Top Of The Stack
return _drawAvailableCard();
}
/*---------------------*
* VIEW FUNCTIONS *
*----------------------*/
/**
* @dev Returns Total Supply
*/
function totalSupply() external view returns (uint256) { return(_CARDS_MINTED); }
/**
* @dev Returns URI for decoding storage of tokenIDs
*/
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, StringsUpgradeable.toString(tokenId), ".json"))); }
/**
* @dev Returns Result Of Card ID Has Sufficient Allocation
*/
function _canMint(uint256 cardID) private view returns (bool) { return (_CARD_ID_ALLOCATION[cardID] > 0); }
/**
* @dev Returns Pseudorandom Number
*/
function _pseudoRandom(uint256 salt) private view returns (uint256)
{
uint256 pseudoRandom =
uint256(
keccak256(
abi.encodePacked(
salt,
block.timestamp,
blockhash(block.difficulty - 1),
block.number,
_randomSeed,
'MOONOPOLY',
'WEN MOON?',
msg.sender
)
)
) % _UNIQUE_CARDS+_MINIMUM_CARD_INDEX;
return pseudoRandom;
}
/**
* @dev Decrements Through Available Card Stack
*/
function _drawAvailableCard() private view returns (uint256)
{
for(uint256 i = _UNIQUE_CARDS; i > _MINIMUM_CARD_INDEX; i--)
{
if(_canMint(i))
{
return i;
}
}
revert("Insufficient Card Amount"); // Insufficient Allocation Of CardIDs To Mint
}
/**
* @dev Conforms to ERC-1155 Standard
*/
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
/*---------------------*
* ADMIN FUNCTIONS *
*----------------------*/
/**
* @dev Batch Transfers Tokens
*/
function __batchTransfer(address[] calldata recipients, uint256[] calldata tokenIDs, uint256[] calldata amounts) external onlyOwner
{
for(uint256 i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
/**
* @dev Modify Airdrop Recipients On Airdrop Access List
*/
function __modifyAirdropRecipients(address[] calldata recipients) external onlyOwner
{
for(uint256 i = 0; i < recipients.length; i++)
{
airdrop[recipients[i]] = _AIRDROP_AMOUNT;
}
emit AddAirdropRecipients(recipients);
}
/**
* @dev Modify Airdrop Recipients On Airdrop Access List With Amounts
*/
function __modifyAirdropRecipientsAmt(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner
{
require(recipients.length == amounts.length, "Invalid Data Formatting");
for(uint256 i = 0; i < recipients.length; i++)
{
airdrop[recipients[i]] = amounts[i];
}
emit AddAirdropRecipients(recipients);
}
/**
* @dev Modifies Card Allocations For Future Expansions
*/
function __modifyCardAllocations(uint256[] calldata cardIDs, uint256[] calldata amounts) external onlyOwner
{
require(cardIDs.length == amounts.length, "Invalid Data Formatting");
for(uint256 i = 0; i < cardIDs.length; i++)
{
_CARD_ID_ALLOCATION[cardIDs[i]] = amounts[i];
}
}
/**
* @dev ADMIN: Mints Expansion Cards For Future Community Airdrops Outside Of The Core Collection :)
*/
function __mintExpansionCards(address[] calldata addresses, uint256[] calldata cardIDs, uint256[] calldata amounts) external onlyOwner
{
require(addresses.length == cardIDs.length && cardIDs.length == amounts.length, "Invalid Data Formatting");
_CARDS_MINTED += amounts.length;
for(uint256 i = 0; i < addresses.length; i++)
{
_mint(addresses[i], cardIDs[i], amounts[i], "");
}
}
/**
* @dev ADMIN: Reserves Cards For Marketing & Core Team
*/
function __reserveCards(uint256 amt, address account) external onlyOwner
{
require(_CARDS_MINTED + amt <= _MAX_CARDS, "Overflow");
for(uint256 i = 0; i < amt; i++)
{
uint256 cardID = _drawCard(amt);
_CARD_ID_ALLOCATION[cardID] -= 1;
_CARDS_MINTED += 1;
_mint(account, cardID, 1, "");
}
}
/**
* @dev ADMIN: Sets Base URI For .json Hosting
*/
function __setBaseURI(string memory BASE_URI) external onlyOwner { _BASE_URI = BASE_URI; }
/**
* @dev ADMIN: Sets Max Cards For future Card Expansion Packs
*/
function __setMaxCards(uint256 MAX_CARDS) external onlyOwner { _MAX_CARDS = MAX_CARDS; }
/**
* @dev ADMIN: Sets Unique Card Index For Future Card Expansion Packs
*/
function __setUniqueCards(uint256 uniqueCards) external onlyOwner { _UNIQUE_CARDS = uniqueCards; }
/**
* @dev ADMIN: Sets Minimum Card Index
*/
function __setCardIndex(uint256 MINIMUM_CARD_INDEX) external onlyOwner { _MINIMUM_CARD_INDEX = MINIMUM_CARD_INDEX; }
/**
* @dev ADMIN: Sets Max Cards Purchasable By Wallet
*/
function __setMaxCardsPurchase(uint256 MAX_CARDS_PURCHASE) external onlyOwner { _MAX_CARDS_PURCHASE = MAX_CARDS_PURCHASE; }
/**
* @dev ADMIN: Sets Future Card Price
*/
function __setCardPrice(uint256 CARD_PRICE) external onlyOwner { _CARD_PRICE = CARD_PRICE; }
/**
* @dev ADMIN: Flips Allowing Multiple Purchases For Future Card Expansion Packs
*/
function __flip_allowMultiplePurchases() external onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
/**
* @dev ADMIN: Flips Sale State
*/
function __flip_saleState() external onlyOwner { _SALE_ACTIVE = !_SALE_ACTIVE; }
/**
* @dev ADMIN: Flips Airdrop State
*/
function __flip_airdropState() external onlyOwner { _AIRDROP_ACTIVE = !_AIRDROP_ACTIVE; }
/**
* @dev ADMIN: Withdraws Ether from Contract
*/
function __withdraw() external onlyOwner { payable(msg.sender).transfer(address(this).balance); }
/**
* @dev ADMIN: Pauses Contract
*/
function __pause() external onlyOwner { _pause(); }
/**
* @dev ADMIN: Unpauses Contract
*/
function __unpause() external onlyOwner { _unpause(); }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC1155Upgradeable.sol";
import "./IERC1155ReceiverUpgradeable.sol";
import "./extensions/IERC1155MetadataURIUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable {
using AddressUpgradeable for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
function __ERC1155_init(string memory uri_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal initializer {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155Upgradeable.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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;
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");
(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");
(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");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | Initialization Variables Sale State Mappings Events | {
string public constant name = "Moonopoly";
string public constant symbol = "MOON";
string public _BASE_URI;
uint256 public _CARDS_MINTED;
uint256 public _MAX_CARDS;
uint256 public _MAX_CARDS_PURCHASE;
uint256 public _AIRDROP_AMOUNT;
uint256 public _CARD_PRICE;
uint256 public _UNIQUE_CARDS;
uint256 public _MINIMUM_CARD_INDEX;
uint256 private _randomSeed;
bool public _SALE_ACTIVE;
bool public _AIRDROP_ACTIVE;
bool public _ALLOW_MULTIPLE_PURCHASES;
mapping (uint256 => uint256) public _CARD_ID_ALLOCATION;
mapping (address => bool) public minted;
mapping (address => uint256) public airdrop;
event MoonopolyAirdropClaimed(address indexed recipient, uint256 indexed amt);
event MoonopolyPublicMint(address indexed recipient, uint256 indexed amt);
event AddAirdropRecipients(address[] wallets);
function initialize() public initializer
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
{
transferOwnership(0x366DA24FD360C5789A5bEb2bE0e72a0FF3BD853C);
_CARDS_MINTED = 1;
_MAX_CARDS = 5555;
_MAX_CARDS_PURCHASE = 5;
_AIRDROP_AMOUNT = 3;
_CARD_PRICE = 0.03 ether;
_UNIQUE_CARDS = 33;
_MINIMUM_CARD_INDEX = 1;
_randomSeed = 0x00;
_SALE_ACTIVE = false;
_AIRDROP_ACTIVE = true;
_ALLOW_MULTIPLE_PURCHASES = true;
}
function MoonopolyMint(uint256 numberOfTokens) public payable nonReentrant
{
require(_SALE_ACTIVE, "Public Sale Must Be Active To Mint Cards");
require(numberOfTokens <= _MAX_CARDS_PURCHASE, "Can Only Mint 5 Cards At A Time");
require(_CARDS_MINTED + numberOfTokens <= _MAX_CARDS, "Purchase Would Exceed Max Supply Of Cards");
require(_CARD_PRICE * numberOfTokens == msg.value, "Ether Value Sent Is Not Correct.");
minted[msg.sender] = true;
for(uint256 i = 0; i < numberOfTokens; i++)
{
uint256 cardID = _drawCard(numberOfTokens);
_CARD_ID_ALLOCATION[cardID] -= 1;
_CARDS_MINTED += 1;
_mint(msg.sender, cardID, 1, "");
}
emit MoonopolyPublicMint(msg.sender, numberOfTokens);
}
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!minted[msg.sender], "Address Has Already Minted"); }
function MoonopolyMint(uint256 numberOfTokens) public payable nonReentrant
{
require(_SALE_ACTIVE, "Public Sale Must Be Active To Mint Cards");
require(numberOfTokens <= _MAX_CARDS_PURCHASE, "Can Only Mint 5 Cards At A Time");
require(_CARDS_MINTED + numberOfTokens <= _MAX_CARDS, "Purchase Would Exceed Max Supply Of Cards");
require(_CARD_PRICE * numberOfTokens == msg.value, "Ether Value Sent Is Not Correct.");
minted[msg.sender] = true;
for(uint256 i = 0; i < numberOfTokens; i++)
{
uint256 cardID = _drawCard(numberOfTokens);
_CARD_ID_ALLOCATION[cardID] -= 1;
_CARDS_MINTED += 1;
_mint(msg.sender, cardID, 1, "");
}
emit MoonopolyPublicMint(msg.sender, numberOfTokens);
}
function MoonopolyAirdrop() public nonReentrant
{
require(_AIRDROP_ACTIVE, "Airdrop is not active");
uint256 amt = airdrop[msg.sender];
require(amt > 0, "Sender wallet is not on airdrop Access List");
airdrop[msg.sender] = 0;
for(uint256 i = 0; i < amt; i++)
{
uint256 cardID = _drawCard(amt);
_CARD_ID_ALLOCATION[cardID] -= 1;
_CARDS_MINTED += 1;
_mint(msg.sender, cardID, 1, "");
}
emit MoonopolyAirdropClaimed(msg.sender, amt);
}
function MoonopolyAirdrop() public nonReentrant
{
require(_AIRDROP_ACTIVE, "Airdrop is not active");
uint256 amt = airdrop[msg.sender];
require(amt > 0, "Sender wallet is not on airdrop Access List");
airdrop[msg.sender] = 0;
for(uint256 i = 0; i < amt; i++)
{
uint256 cardID = _drawCard(amt);
_CARD_ID_ALLOCATION[cardID] -= 1;
_CARDS_MINTED += 1;
_mint(msg.sender, cardID, 1, "");
}
emit MoonopolyAirdropClaimed(msg.sender, amt);
}
function _drawCard(uint256 salt) private returns (uint256)
{
for (uint256 i = 1; i < 4; i++)
{
uint256 value = _pseudoRandom(i + _CARDS_MINTED + salt);
if (_canMint(value))
{
_randomSeed = value;
return value;
}
}
}
function _drawCard(uint256 salt) private returns (uint256)
{
for (uint256 i = 1; i < 4; i++)
{
uint256 value = _pseudoRandom(i + _CARDS_MINTED + salt);
if (_canMint(value))
{
_randomSeed = value;
return value;
}
}
}
function _drawCard(uint256 salt) private returns (uint256)
{
for (uint256 i = 1; i < 4; i++)
{
uint256 value = _pseudoRandom(i + _CARDS_MINTED + salt);
if (_canMint(value))
{
_randomSeed = value;
return value;
}
}
}
return _drawAvailableCard();
function totalSupply() external view returns (uint256) { return(_CARDS_MINTED); }
function uri(uint256 tokenId) override public view returns (string memory) { return(string(abi.encodePacked(_BASE_URI, StringsUpgradeable.toString(tokenId), ".json"))); }
function _canMint(uint256 cardID) private view returns (bool) { return (_CARD_ID_ALLOCATION[cardID] > 0); }
function _pseudoRandom(uint256 salt) private view returns (uint256)
{
uint256 pseudoRandom =
uint256(
keccak256(
abi.encodePacked(
salt,
block.timestamp,
blockhash(block.difficulty - 1),
block.number,
_randomSeed,
'MOONOPOLY',
'WEN MOON?',
msg.sender
)
)
) % _UNIQUE_CARDS+_MINIMUM_CARD_INDEX;
return pseudoRandom;
}
function _drawAvailableCard() private view returns (uint256)
{
for(uint256 i = _UNIQUE_CARDS; i > _MINIMUM_CARD_INDEX; i--)
{
if(_canMint(i))
{
return i;
}
}
}
function _drawAvailableCard() private view returns (uint256)
{
for(uint256 i = _UNIQUE_CARDS; i > _MINIMUM_CARD_INDEX; i--)
{
if(_canMint(i))
{
return i;
}
}
}
function _drawAvailableCard() private view returns (uint256)
{
for(uint256 i = _UNIQUE_CARDS; i > _MINIMUM_CARD_INDEX; i--)
{
if(_canMint(i))
{
return i;
}
}
}
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal override
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
function __batchTransfer(address[] calldata recipients, uint256[] calldata tokenIDs, uint256[] calldata amounts) external onlyOwner
{
for(uint256 i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
function __batchTransfer(address[] calldata recipients, uint256[] calldata tokenIDs, uint256[] calldata amounts) external onlyOwner
{
for(uint256 i=0; i < recipients.length; i++)
{
_safeTransferFrom(msg.sender, recipients[i], tokenIDs[i], amounts[i], "");
}
}
function __modifyAirdropRecipients(address[] calldata recipients) external onlyOwner
{
for(uint256 i = 0; i < recipients.length; i++)
{
airdrop[recipients[i]] = _AIRDROP_AMOUNT;
}
emit AddAirdropRecipients(recipients);
}
function __modifyAirdropRecipients(address[] calldata recipients) external onlyOwner
{
for(uint256 i = 0; i < recipients.length; i++)
{
airdrop[recipients[i]] = _AIRDROP_AMOUNT;
}
emit AddAirdropRecipients(recipients);
}
function __modifyAirdropRecipientsAmt(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner
{
require(recipients.length == amounts.length, "Invalid Data Formatting");
for(uint256 i = 0; i < recipients.length; i++)
{
airdrop[recipients[i]] = amounts[i];
}
emit AddAirdropRecipients(recipients);
}
function __modifyAirdropRecipientsAmt(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner
{
require(recipients.length == amounts.length, "Invalid Data Formatting");
for(uint256 i = 0; i < recipients.length; i++)
{
airdrop[recipients[i]] = amounts[i];
}
emit AddAirdropRecipients(recipients);
}
function __modifyCardAllocations(uint256[] calldata cardIDs, uint256[] calldata amounts) external onlyOwner
{
require(cardIDs.length == amounts.length, "Invalid Data Formatting");
for(uint256 i = 0; i < cardIDs.length; i++)
{
_CARD_ID_ALLOCATION[cardIDs[i]] = amounts[i];
}
}
function __modifyCardAllocations(uint256[] calldata cardIDs, uint256[] calldata amounts) external onlyOwner
{
require(cardIDs.length == amounts.length, "Invalid Data Formatting");
for(uint256 i = 0; i < cardIDs.length; i++)
{
_CARD_ID_ALLOCATION[cardIDs[i]] = amounts[i];
}
}
function __mintExpansionCards(address[] calldata addresses, uint256[] calldata cardIDs, uint256[] calldata amounts) external onlyOwner
{
require(addresses.length == cardIDs.length && cardIDs.length == amounts.length, "Invalid Data Formatting");
_CARDS_MINTED += amounts.length;
for(uint256 i = 0; i < addresses.length; i++)
{
_mint(addresses[i], cardIDs[i], amounts[i], "");
}
}
function __mintExpansionCards(address[] calldata addresses, uint256[] calldata cardIDs, uint256[] calldata amounts) external onlyOwner
{
require(addresses.length == cardIDs.length && cardIDs.length == amounts.length, "Invalid Data Formatting");
_CARDS_MINTED += amounts.length;
for(uint256 i = 0; i < addresses.length; i++)
{
_mint(addresses[i], cardIDs[i], amounts[i], "");
}
}
function __reserveCards(uint256 amt, address account) external onlyOwner
{
require(_CARDS_MINTED + amt <= _MAX_CARDS, "Overflow");
for(uint256 i = 0; i < amt; i++)
{
uint256 cardID = _drawCard(amt);
_CARD_ID_ALLOCATION[cardID] -= 1;
_CARDS_MINTED += 1;
_mint(account, cardID, 1, "");
}
}
function __reserveCards(uint256 amt, address account) external onlyOwner
{
require(_CARDS_MINTED + amt <= _MAX_CARDS, "Overflow");
for(uint256 i = 0; i < amt; i++)
{
uint256 cardID = _drawCard(amt);
_CARD_ID_ALLOCATION[cardID] -= 1;
_CARDS_MINTED += 1;
_mint(account, cardID, 1, "");
}
}
function __setBaseURI(string memory BASE_URI) external onlyOwner { _BASE_URI = BASE_URI; }
function __setMaxCards(uint256 MAX_CARDS) external onlyOwner { _MAX_CARDS = MAX_CARDS; }
function __setUniqueCards(uint256 uniqueCards) external onlyOwner { _UNIQUE_CARDS = uniqueCards; }
function __setCardIndex(uint256 MINIMUM_CARD_INDEX) external onlyOwner { _MINIMUM_CARD_INDEX = MINIMUM_CARD_INDEX; }
function __setMaxCardsPurchase(uint256 MAX_CARDS_PURCHASE) external onlyOwner { _MAX_CARDS_PURCHASE = MAX_CARDS_PURCHASE; }
function __setCardPrice(uint256 CARD_PRICE) external onlyOwner { _CARD_PRICE = CARD_PRICE; }
function __flip_allowMultiplePurchases() external onlyOwner { _ALLOW_MULTIPLE_PURCHASES = !_ALLOW_MULTIPLE_PURCHASES; }
function __flip_saleState() external onlyOwner { _SALE_ACTIVE = !_SALE_ACTIVE; }
function __flip_airdropState() external onlyOwner { _AIRDROP_ACTIVE = !_AIRDROP_ACTIVE; }
function __withdraw() external onlyOwner { payable(msg.sender).transfer(address(this).balance); }
function __pause() external onlyOwner { _pause(); }
function __unpause() external onlyOwner { _unpause(); }
}
| 129,937 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
import "./Ownable.sol";
import "./IXToken.sol";
import "./IERC721.sol";
import "./ERC721Holder.sol";
import "./IXStore.sol";
import "./Initializable.sol";
import "./SafeERC20.sol";
contract SNFTX is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IXStore public store;
function initialize(address storeAddress) public initializer {
initOwnable();
store = IXStore(storeAddress);
}
// modifier가 아니라 그냥 함수로 구현함
function onlyPrivileged(uint256 vaultId) internal view {
require(msg.sender == store.manager(vaultId),
"Not manager");
}
function _getPseudoRand(uint256 modulus)
internal
returns (uint256)
{
store.setRandNonce(store.randNonce().add(1));
return
uint256(
keccak256(
abi.encodePacked(
now, msg.sender, store.randNonce()))
) %
modulus;
}
function _receiveEthToVault(
uint256 vaultId,
uint256 amountRequested,
uint256 amountSent
) internal {
require(amountSent >= amountRequested, "Value too low");
store.setEthBalance(
vaultId,
store.ethBalance(vaultId).add(amountRequested)
);
// 잔돈 거슬러줌.
if (amountSent > amountRequested) {
msg.sender.transfer(amountSent.sub(amountRequested));
}
}
function _payEthFromVault(
uint256 vaultId,
uint256 amount,
address payable to
) internal virtual {
uint256 ethBalance = store.ethBalance(vaultId);
uint256 amountToSend = ethBalance < amount ? ethBalance : amount;
if (amountToSend > 0) {
store.setEthBalance(vaultId, ethBalance.sub(amountToSend));
to.transfer(amountToSend);
}
}
function _calcFee(
uint256 amount,
uint256 ethBase,
uint256 ethStep
) internal pure returns (uint256) {
if (amount == 0) {
return 0;
} else {
uint256 n = amount;
uint256 nSub1 = amount >= 1 ? n.sub(1) : 0;
return ethBase.add(ethStep.mul(nSub1));
}
}
function createVault(
address _xTokenAddress,
address _assetAddress
) public returns (uint256) {
IXToken xToken = IXToken(_xTokenAddress);
require(xToken.owner() == address(this), "Wrong owner");
uint256 vaultId = store.addNewVault();
store.setXTokenAddress(vaultId, _xTokenAddress);
store.setXToken(vaultId);
store.setNftAddress(vaultId, _assetAddress);
store.setNft(vaultId);
store.setManager(vaultId, msg.sender);
return vaultId;
}
function requestMint(uint256 vaultId, uint256[] memory nftIds)
public
payable
{
uint256 amount = nftIds.length;
(uint256 ethBase, uint256 ethStep)
= store.mintFees(vaultId);
uint256 ethFee = _calcFee(
amount,
ethBase,
ethStep
);
_receiveEthToVault(vaultId, ethFee, msg.value);
for (uint256 i = 0; i < nftIds.length; i = i.add(1)) {
require(
store.nft(vaultId).ownerOf(nftIds[i])
!= address(this),
"Already owner"
);
// store.nft(vaultId)는 ERC721 contract 객체다.
store.nft(vaultId).safeTransferFrom(
msg.sender,
address(this),
nftIds[i]
);
require(
store.nft(vaultId).ownerOf(nftIds[i])
== address(this),
"Not received"
);
store.setRequester(vaultId, nftIds[i], msg.sender);
}
}
// 위에 거 반대로 해서 취소하는 기능
function revokeMintRequests(
uint256 vaultId,
uint256[] memory nftIds)
public
{
uint256 amount = nftIds.length;
(uint256 ethBase, uint256 ethStep)
= store.mintFees(vaultId);
uint256 ethFee = _calcFee(
amount,
ethBase,
ethStep
);
_payEthFromVault(vaultId, ethFee, msg.sender);
for (uint256 i = 0; i < nftIds.length; i = i.add(1)) {
require(
store.requester(vaultId, nftIds[i])
== msg.sender,
"Not requester"
);
store.setRequester(vaultId, nftIds[i], address(0));
store.nft(vaultId).safeTransferFrom(
address(this),
msg.sender,
nftIds[i]
);
}
}
function setIsEligible(
uint256 vaultId,
uint256[] memory nftIds,
bool _boolean
) public {
onlyPrivileged(vaultId);
for (uint256 i = 0; i < nftIds.length; i = i.add(1)) {
store.setIsEligible(vaultId, nftIds[i], _boolean);
}
}
function isEligible(uint256 vaultId, uint256 nftId)
public
view
returns (bool)
{
return store.isEligible(vaultId, nftId);
}
function approveMintRequest(
uint256 vaultId,
uint256[] memory nftIds
) public {
// modifier 대신 이렇게 함수 호출로 쓸 수도 있음.
onlyPrivileged(vaultId);
for (uint256 i = 0; i < nftIds.length; i = i.add(1)) {
address requester = store.requester(
vaultId, nftIds[i]);
require(requester != address(0), "No request");
require(
store.nft(vaultId).ownerOf(nftIds[i])
== address(this),
"Not owner"
);
store.setRequester(vaultId, nftIds[i], address(0));
store.setIsEligible(vaultId, nftIds[i], true);
store.holdingsAdd(vaultId, nftIds[i]);
// wei 단위 때문에 이렇게 10**18을 곱해줘야 한다.
// 일단 이렇게 찍어만 놓고, requester에게 나중에 준다.
store.xToken(vaultId).mint(requester, 10**18);
}
}
function _mint(uint256 vaultId, uint256[] memory nftIds)
internal
{
for (uint256 i = 0; i < nftIds.length; i = i.add(1)) {
uint256 nftId = nftIds[i];
require(isEligible(vaultId, nftId), "Not eligible");
require(
store.nft(vaultId).ownerOf(nftId)
!= address(this),
"Already owner"
);
// 1)NFT를 vault에 옮기고
store.nft(vaultId).safeTransferFrom(
msg.sender,
address(this),
nftId
);
require(
store.nft(vaultId).ownerOf(nftId)
== address(this),
"Not received"
);
store.holdingsAdd(vaultId, nftId);
}
uint256 amount = nftIds.length.mul(10**18);
// 2)vault token 찍어준다.
store.xToken(vaultId).mint(msg.sender, amount);
}
function mint(uint256 vaultId, uint256[] memory nftIds)
public payable
{
uint256 amount = nftIds.length;
(uint256 ethBase, uint256 ethStep)
= store.mintFees(vaultId);
uint256 ethFee = _calcFee(
amount,
ethBase,
ethStep
);
_receiveEthToVault(vaultId, ethFee, msg.value);
_mint(vaultId, nftIds, false);
}
function _redeem(uint256 vaultId, uint256 numNFTs) internal {
for (uint256 i = 0; i < numNFTs; i = i.add(1)) {
// 새 array를 만들어줌
uint256[] memory nftIds = new uint256[](1);
uint256 rand = _getPseudoRand(
store.holdingsLength(vaultId));
nftIds[0] = store.holdingsAt(vaultId, rand);
_redeemHelper(vaultId, nftIds);
}
}
function _redeemHelper(
uint256 vaultId,
uint256[] memory nftIds
) internal {
store.xToken(vaultId).burnFrom(
msg.sender,
nftIds.length.mul(10**18)
);
for (uint256 i = 0; i < nftIds.length; i = i.add(1)) {
uint256 nftId = nftIds[i];
require(
store.holdingsContains(vaultId, nftId) ||
store.reservesContains(vaultId, nftId),
"NFT not in vault"
);
store.holdingsRemove(vaultId, nftId);
store.nft(vaultId).safeTransferFrom(
address(this),
msg.sender,
nftId
);
}
}
function redeem(uint256 vaultId, uint256 amount)
public payable
{
(uint256 ethBase, uint256 ethStep)
= store.burnFees(vaultId);
uint256 ethFee = _calcFee(
amount,
ethBase,
ethStep
);
_receiveEthToVault(vaultId, ethFee, msg.value);
_redeem(vaultId, amount, false);
}
function setManager(uint256 vaultId, address newManager)
public virtual {
onlyPrivileged(vaultId);
store.setManager(vaultId, newManager);
}
function setMintFees(
uint256 vaultId,
uint256 _ethBase,
uint256 _ethStep
)
public
virtual
{
onlyPrivileged(vaultId);
store.setMintFees(vaultId, _ethBase, _ethStep);
}
function setBurnFees(
uint256 vaultId,
uint256 _ethBase,
uint256 _ethStep
)
public
virtual
{
onlyPrivileged(vaultId);
store.setBurnFees(vaultId, _ethBase, _ethStep);
}
}
| modifier 대신 이렇게 함수 호출로 쓸 수도 있음. wei 단위 때문에 이렇게 1018을 곱해줘야 한다. 일단 이렇게 찍어만 놓고, requester에게 나중에 준다. | function approveMintRequest(
uint256 vaultId,
uint256[] memory nftIds
) public {
onlyPrivileged(vaultId);
for (uint256 i = 0; i < nftIds.length; i = i.add(1)) {
address requester = store.requester(
vaultId, nftIds[i]);
require(requester != address(0), "No request");
require(
store.nft(vaultId).ownerOf(nftIds[i])
== address(this),
"Not owner"
);
store.setRequester(vaultId, nftIds[i], address(0));
store.setIsEligible(vaultId, nftIds[i], true);
store.holdingsAdd(vaultId, nftIds[i]);
store.xToken(vaultId).mint(requester, 10**18);
}
}
| 1,805,948 |
./full_match/5/0xcc65Ea1d651ee8ACA6B8a0ba140221032aB73380/sources/lotto.sol | this updates the placeholder winning info for the current nonce and sets it to... the winning info | function _logWinningPlayer(
address account,
uint256 winnings
) internal virtual {
_winningHistory.push(
);
}
| 7,084,981 |
./full_match/137/0x335fF3edFb787e24fd6F3eB6c5E6e53003017cdD/sources/contracts/notlarvalads.sol | Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length./ | function toHexString(uint256 value, uint256 length) internal pure returns(string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
| 4,735,313 |
./partial_match/1/0xdB7B2616210Bd0068D914eEB7E31aFD2Da517444/sources/SmartToken.sol | executes the ERC20 token's `transfer` function and reverts upon failure the main purpose of this function is to prevent a non standard ERC20 token from failing silently _token ERC20 token address _to target address _value transfer amount/ | function safeTransfer(IERC20Token _token, address _to, uint256 _value) public {
execute(_token, abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value));
}
| 4,155,108 |
/**
* @title ArbitrableDeposit
* @author Luke Hartman - <[email protected]>
* Bug Bounties: This code hasn't undertaken a bug bounty program yet.
*/
pragma solidity ^0.4.15;
import "./Arbitrable.sol";
/** @title Arbitrable Deposit
* This is a a contract which allow for an owner deposit. Anyone besides the owner can seek arbitration/file a claim as a claimant.
* To develop a contract inheriting from this one, you need to:
* - Redefine RULING_OPTIONS to explain the consequences of the possible rulings.
* - Redefine executeRuling while still calling super.executeRuling to implement the results of the arbitration.
*/
contract ArbitrableDeposit is Arbitrable {
address public owner;
address public claimant;
uint public timeout; // Time in seconds a party can take before being considered unresponding and lose the dispute.
uint public ownerFee; // Total fees paid by the owner.
uint public claimantFee; // Total fees paid by the claimant.
uint public lastInteraction; // Last interaction for the dispute procedure.
uint public disputeID;
uint public amount; // Total amount deposited by owner.
uint public claimAmount; // Claim amount a claimant proposes.
uint public claimRate; // Rate of a claim the claimant must deposit as an integer.
uint internal claimResponseAmount; // Amount which the Owner responds to the claimant's asking claim.
uint public claimDepositAmount; // Total amount a claimant must deposit.
enum Status {NoDispute, WaitingOwner, WaitingClaimant, DisputeCreated, Resolved}
Status public status;
uint8 constant AMOUNT_OF_CHOICES = 2;
uint8 constant OWNER_WINS = 1;
uint8 constant CLAIMANT_WINS = 2;
string constant RULING_OPTIONS = "Owner wins;Claimant wins"; // A plain English of what rulings do. Need to be redefined by the child class.
modifier onlyOwner{ require(msg.sender==address(owner)); _; }
modifier onlyNotOwner{ require(msg.sender!=address(owner)); _;}
modifier onlyClaimant{ require(msg.sender==address(claimant)); _;}
enum Party {Owner, Claimant}
/** @dev Indicate that a party has to pay a fee or would otherwise be considered as loosing.
* @param _party The party who has to pay.
*/
event HasToPayFee(Party _party);
/** @dev Constructor. Choose the arbitrator
* @param _arbitrator The arbitrator of the contract.
* @param _hashContract Keccak256 hash of the plain text contract.
* @param _timeout Time after which a party automatically loose a dispute.
* @param _arbitratorExtraData Extra data for the arbitrator.
*/
constructor(Arbitrator _arbitrator, bytes32 _hashContract, uint _timeout, bytes _arbitratorExtraData, uint _claimRate) Arbitrable(_arbitrator, _arbitratorExtraData, _hashContract) public payable {
timeout = _timeout;
claimRate = _claimRate;
status = Status.NoDispute;
amount += msg.value;
owner = msg.sender;
address(this).transfer(amount);
}
/** @dev Owner deposit to contract. To be called when the owner makes a deposit.
*/
function deposit(uint _amount) public onlyOwner {
amount += _amount;
address(this).transfer(_amount);
}
/** @dev File a claim against owner. To be called when someone makes a claim.
* @param _claimAmount The proposed claim amount by the claimant.
*/
function makeClaim(uint _claimAmount) public onlyNotOwner {
require(_claimAmount >= 0 && _claimAmount <= amount);
claimant = msg.sender;
claimAmount = _claimAmount;
claimDepositAmount = (_claimAmount * claimRate)/100;
address(this).transfer(claimDepositAmount);
status = Status.WaitingOwner;
}
/** @dev Owner response to claimant. To be called when the owner initates a
* a response.
* @param _responseAmount The counter-offer amount the Owner proposes to a claimant.
*/
function claimResponse(uint _responseAmount) public onlyOwner {
require(_responseAmount >= 0 && _responseAmount <= claimDepositAmount);
claimResponseAmount = _responseAmount;
if (_responseAmount == claimDepositAmount) {
claimant.transfer(_responseAmount);
claimAmount = 0;
amount = 0;
status = Status.Resolved;
} else {
payArbitrationFeeByOwner();
}
}
/** @dev Pay the arbitration fee to raise a dispute. To be called by the owner. UNTRUSTED.
* Note that the arbitrator can have createDispute throw, which will make this function throw and therefore lead to a party being timed-out.
* This is not a vulnerability as the arbitrator can rule in favor of one party anyway.
*/
function payArbitrationFeeByOwner() public payable onlyOwner{
uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
ownerFee += msg.value;
require(ownerFee == arbitrationCost); // Require that the total pay at least the arbitration cost.
require(status<Status.DisputeCreated); // Make sure a dispute has not been created yet.
lastInteraction = now;
if (claimantFee < arbitrationCost) { // The claimant still has to pay.
// This can also happens if he has paid, but arbitrationCost has increased.
status = Status.WaitingClaimant;
emit HasToPayFee(Party.Claimant);
} else { // The claimant has also paid the fee. We create the dispute
raiseDispute(arbitrationCost);
}
}
/** @dev Pay the arbitration fee to raise a dispute. To be called by the claimant. UNTRUSTED.
* Note that this function mirror payArbitrationFeeByOwner.
*/
function payArbitrationFeeByClaimant() public payable onlyClaimant {
uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
claimantFee += msg.value;
require(claimantFee == arbitrationCost); // Require that the total pay at least the arbitration cost.
require(status<Status.DisputeCreated); // Make sure a dispute has not been created yet.
lastInteraction = now;
if (ownerFee < arbitrationCost) { // The owner still has to pay. This can also happens if he has paid, but arbitrationCost has increased.
status = Status.WaitingOwner;
emit HasToPayFee(Party.Claimant);
} else { // The owner has also paid the fee. We create the dispute
raiseDispute(arbitrationCost);
}
}
/** @dev Create a dispute. UNTRUSTED.
* @param _arbitrationCost Amount to pay the arbitrator.
*/
function raiseDispute(uint _arbitrationCost) internal {
status = Status.DisputeCreated;
disputeID = arbitrator.createDispute.value(_arbitrationCost)(AMOUNT_OF_CHOICES,arbitratorExtraData);
emit Dispute(arbitrator,disputeID,RULING_OPTIONS);
}
/** @dev Reimburse owner if claimant fails to pay the fee.
*/
function timeOutByOwner() public onlyOwner {
require(status==Status.WaitingClaimant);
require(now >= lastInteraction + timeout);
executeRuling(disputeID,OWNER_WINS);
}
/** @dev Pay claimant if owner fails to pay the fee.
*/
function timeOutByClaimant() public onlyClaimant {
require(status==Status.WaitingOwner);
require(now >= lastInteraction+timeout);
executeRuling(disputeID,CLAIMANT_WINS);
}
/** @dev Execute a ruling of a dispute. Pays parties respective amounts based on ruling.
* This needs to be extended by contract inheriting from it.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling Ruling given by the arbitrator. 1 : Allow owner deposit. 2 : Pay claimant.
*/
function executeRuling(uint _disputeID, uint _ruling) internal {
require(_disputeID==disputeID);
require(_ruling<=AMOUNT_OF_CHOICES);
if (_ruling==OWNER_WINS) {
owner.transfer(amount + claimAmount);
claimant.transfer(claimResponseAmount);
} else if (_ruling==CLAIMANT_WINS)
claimant.transfer(amount);
amount = 0;
}
}
| File a claim against owner. To be called when someone makes a claim. _claimAmount The proposed claim amount by the claimant./ | function makeClaim(uint _claimAmount) public onlyNotOwner {
require(_claimAmount >= 0 && _claimAmount <= amount);
claimant = msg.sender;
claimAmount = _claimAmount;
claimDepositAmount = (_claimAmount * claimRate)/100;
address(this).transfer(claimDepositAmount);
status = Status.WaitingOwner;
}
| 13,093,190 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "./MockERC721.sol";
/**
* @dev N of M Multisig Contract
* - M of N is fixed at the deploy moment
* - The access controlled contract is instantiated at the deploy moment
* the controlled extend `Ownable`, so that controlled only via this multisig
* - the length of signers CANNOT be changed once they are set
*
* Inspired by BitGo's WalletSimple.sol
* https://github.com/BitGo/eth-multisig-v2/blob/master/contracts/WalletSimple.sol
*/
contract Multisig is Context {
using Address for address;
using ECDSA for bytes32;
/* the addresses allowed to sign */
address[] public signers;
/* required singner number */
uint8 public threshold;
/* the minimum threshold */
uint8 public MIN_THRESHOLD = 2;
/* the adress of access controlled contract */
address public controlled;
// Mapping to keep track of all hashes (message or transaction) that have been approved by ANY owners
mapping(address => mapping(bytes32 => uint256)) public approvedHashes;
event Called(address caller, bytes data, bytes returndata);
event SignerReplaced(address indexed oldSinger, address indexed newSinger);
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlySigner() {
(bool ok, ) = isSigner(_msgSender());
if (!ok) {
revert("unauthorized msg sender");
}
_;
}
constructor(address[] memory _signers, uint8 _threshold) {
require(_threshold >= MIN_THRESHOLD, "threshold is too low");
require(
_signers.length >= _threshold,
"signers length must be bigger than threshold"
);
threshold = _threshold;
signers = _signers;
controlled = address(new MockERC721());
}
function version() public view virtual returns (string memory) {
return "1";
}
/**
* @dev Determine if an address is a signer on this wallet
* @param signer address to check
* returns
* - boolean indicating whether address is signer or not,
* - the index of target address
*/
function isSigner(address signer) public view returns (bool, uint256) {
// Iterate through all signers on the wallet and
for (uint256 i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return (true, i);
}
}
return (false, 0);
}
/**
* @dev verify singer signatures
* @param hash The hash of calldata
* @param signatures The signatures
*/
function _verifySigs(bytes32 hash, bytes[] memory signatures) internal {
for (uint256 i = 0; i < signatures.length; i++) {
address recoverd = hash.recover(signatures[i]);
(bool ok, ) = isSigner(recoverd);
if (!ok) {
revert("recoverd address is not signer");
}
if (recoverd == _msgSender()) {
revert("msg.sender should not be signer");
}
if (approvedHashes[recoverd][hash] >= 1) {
revert("already approved signature");
}
approvedHashes[recoverd][hash] = 1;
}
}
/**
* @dev call controlled contract without value
* @param signatures required more than threshold signatures
* @param data the calldata
*/
function callControlled(bytes[] memory signatures, bytes calldata data)
public
payable
virtual
onlySigner
returns (bytes memory)
{
require(signatures.length + 1 >= threshold, "insufficient signatures");
_verifySigs(ECDSA.toEthSignedMessageHash(keccak256(data)), signatures);
bytes memory returndata = controlled.functionCall(
data,
"faild to call controlled"
);
emit Called(_msgSender(), data, returndata);
return returndata;
}
/**
* @dev replace signer, only authorized by signer
* @param newSinger the new signer address
*/
function replaceSinger(address newSinger) public {
(bool ok, uint256 i) = isSigner(_msgSender());
if (!ok) {
revert("unauthorized msg sender");
}
signers[i] = newSinger;
emit SignerReplaced(_msgSender(), newSinger);
}
}
| Determine if an address is a signer on this wallet signer address to check returns - boolean indicating whether address is signer or not, - the index of target address/ Iterate through all signers on the wallet and | function isSigner(address signer) public view returns (bool, uint256) {
for (uint256 i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return (true, i);
}
}
return (false, 0);
}
| 13,033,024 |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "./StateUtils.sol";
import "./interfaces/IGetterUtils.sol";
/// @title Contract that implements getters
contract GetterUtils is StateUtils, IGetterUtils {
/// @param api3TokenAddress API3 token contract address
constructor(address api3TokenAddress)
StateUtils(api3TokenAddress)
{}
/// @notice Called to get the voting power of a user at a specific block
/// @dev This method is used to implement the MiniMe interface for the
/// Api3Voting app
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Voting power of the user at the block
function balanceOfAt(
address userAddress,
uint256 _block
)
public
view
override
returns(uint256)
{
// Users that delegate have no voting power
if (userDelegateAt(userAddress, _block) != address(0))
{
return 0;
}
uint256 userSharesThen = userSharesAt(userAddress, _block);
uint256 delegatedToUserThen = userReceivedDelegationAt(userAddress, _block);
return userSharesThen + delegatedToUserThen;
}
/// @notice Called to get the current voting power of a user
/// @dev This method is used to implement the MiniMe interface for the
/// Api3Voting app
/// @param userAddress User address
/// @return Current voting power of the user
function balanceOf(address userAddress)
public
view
override
returns(uint256)
{
return balanceOfAt(userAddress, block.number);
}
/// @notice Called to get the total voting power one block ago
/// @dev This method is used to implement the MiniMe interface for the
/// Api3Voting app
/// @return Total voting power one block ago
function totalSupplyOneBlockAgo()
public
view
override
returns(uint256)
{
return totalSharesOneBlockAgo();
}
/// @notice Called to get the current total voting power
/// @dev This method is used to implement the MiniMe interface for the
/// Aragon Voting app
/// @return Current total voting power
function totalSupply()
public
view
override
returns(uint256)
{
return totalShares();
}
/// @notice Called to get the pool shares of a user at a specific block
/// @dev Starts from the most recent value in `user.shares` and searches
/// backwards one element at a time
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Pool shares of the user at the block
function userSharesAt(
address userAddress,
uint256 _block
)
public
view
override
returns(uint256)
{
return getValueAt(users[userAddress].shares, _block, 0);
}
/// @notice Called to get the current pool shares of a user
/// @param userAddress User address
/// @return Current pool shares of the user
function userShares(address userAddress)
public
view
override
returns(uint256)
{
return userSharesAt(userAddress, block.number);
}
/// @notice Called to get the pool shares of a user at a specific block
/// using binary search
/// @dev From
/// https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431
/// This method is not used by the current iteration of the DAO/pool and is
/// implemented for future external contracts to use to get the user shares
/// at an arbitrary block.
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Pool shares of the user at the block
function userSharesAtWithBinarySearch(
address userAddress,
uint256 _block
)
external
view
override
returns(uint256)
{
Checkpoint[] storage checkpoints = users[userAddress].shares;
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length -1].fromBlock)
return checkpoints[checkpoints.length - 1].value;
if (_block < checkpoints[0].fromBlock)
return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
/// @notice Called to get the current staked tokens of the user
/// @param userAddress User address
/// @return Current staked tokens of the user
function userStake(address userAddress)
public
view
override
returns(uint256)
{
return userShares(userAddress) * totalStake / totalShares();
}
/// @notice Called to get the voting power delegated to a user at a
/// specific block
/// @dev Starts from the most recent value in `user.delegatedTo` and
/// searches backwards one element at a time. If `_block` is within
/// `EPOCH_LENGTH`, this call is guaranteed to find the value among
/// the last `MAX_INTERACTION_FREQUENCY` elements, which is why it only
/// searches through them.
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Voting power delegated to the user at the block
function userReceivedDelegationAt(
address userAddress,
uint256 _block
)
public
view
override
returns(uint256)
{
Checkpoint[] storage delegatedTo = users[userAddress].delegatedTo;
uint256 minimumCheckpointIndex = delegatedTo.length > MAX_INTERACTION_FREQUENCY
? delegatedTo.length - MAX_INTERACTION_FREQUENCY
: 0;
return getValueAt(delegatedTo, _block, minimumCheckpointIndex);
}
/// @notice Called to get the current voting power delegated to a user
/// @param userAddress User address
/// @return Current voting power delegated to the user
function userReceivedDelegation(address userAddress)
public
view
override
returns(uint256)
{
return userReceivedDelegationAt(userAddress, block.number);
}
/// @notice Called to get the delegate of the user at a specific block
/// @dev Starts from the most recent value in `user.delegates` and
/// searches backwards one element at a time. If `_block` is within
/// `EPOCH_LENGTH`, this call is guaranteed to find the value among
/// the last 2 elements because a user cannot update delegate more
/// frequently than once an `EPOCH_LENGTH`.
/// @param userAddress User address
/// @param _block Block number
/// @return Delegate of the user at the specific block
function userDelegateAt(
address userAddress,
uint256 _block
)
public
view
override
returns(address)
{
AddressCheckpoint[] storage delegates = users[userAddress].delegates;
for (uint256 i = delegates.length; i > 0; i--)
{
if (delegates[i - 1].fromBlock <= _block)
{
return delegates[i - 1]._address;
}
}
return address(0);
}
/// @notice Called to get the current delegate of the user
/// @param userAddress User address
/// @return Current delegate of the user
function userDelegate(address userAddress)
public
view
override
returns(address)
{
return userDelegateAt(userAddress, block.number);
}
/// @notice Called to get the current locked tokens of the user
/// @param userAddress User address
/// @return locked Current locked tokens of the user
function getUserLocked(address userAddress)
public
view
override
returns(uint256 locked)
{
Checkpoint[] storage _userShares = users[userAddress].shares;
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
uint256 oldestLockedEpoch = currentEpoch - REWARD_VESTING_PERIOD > genesisEpoch
? currentEpoch - REWARD_VESTING_PERIOD + 1
: genesisEpoch + 1;
if (_userShares.length == 0)
{
return 0;
}
uint256 indUserShares = _userShares.length - 1;
for (
uint256 indEpoch = currentEpoch;
indEpoch >= oldestLockedEpoch;
indEpoch--
)
{
Reward storage lockedReward = epochIndexToReward[indEpoch];
if (lockedReward.atBlock != 0)
{
for (; indUserShares >= 0; indUserShares--)
{
Checkpoint storage userShare = _userShares[indUserShares];
if (userShare.fromBlock <= lockedReward.atBlock)
{
locked += lockedReward.amount * userShare.value / lockedReward.totalSharesThen;
break;
}
}
}
}
}
/// @notice Called to get the value of a checkpoint array at a specific
/// block
/// @param checkpoints Checkpoints array
/// @param _block Block number for which the query is being made
/// @return Value of the checkpoint array at the block
function getValueAt(
Checkpoint[] storage checkpoints,
uint256 _block,
uint256 minimumCheckpointIndex
)
internal
view
returns(uint256)
{
uint256 i = checkpoints.length;
for (; i > minimumCheckpointIndex; i--)
{
if (checkpoints[i - 1].fromBlock <= _block)
{
return checkpoints[i - 1].value;
}
}
// Revert if the value being searched for comes before
// `minimumCheckpointIndex`
require(i == 0, ERROR_VALUE);
return 0;
}
}
| Called to get the current delegate of the user userAddress User address return Current delegate of the user | function userDelegate(address userAddress)
public
view
override
returns(address)
{
return userDelegateAt(userAddress, block.number);
}
| 12,851,186 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
/**
* @title ERC-1155 Inventory, additional minting interface
* @dev See https://eips.ethereum.org/EIPS/eip-1155
*/
interface IERC1155InventoryMintable {
/**
* Safely mints some token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if `id` is not a token.
* @dev Reverts if `id` represents a non-fungible token and `value` is not 1.
* @dev Reverts if `id` represents a non-fungible token which has already been minted.
* @dev Reverts if `id` represents a fungible token and `value` is 0.
* @dev Reverts if `id` represents a fungible token and there is an overflow of supply.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155Received} fails or is refused.
* @dev Emits an {IERC1155-TransferSingle} event.
* @param to Address of the new token owner.
* @param id Identifier of the token to mint.
* @param value Amount of token to mint.
* @param data Optional data to send along to a receiver contract.
*/
function safeMint(
address to,
uint256 id,
uint256 value,
bytes calldata data
) external;
/**
* Safely mints a batch of tokens.
* @dev Reverts if `ids` and `values` have different lengths.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if one of `ids` is not a token.
* @dev Reverts if one of `ids` represents a non-fungible token and its paired value is not 1.
* @dev Reverts if one of `ids` represents a non-fungible token which has already been minted.
* @dev Reverts if one of `ids` represents a fungible token and its paired value is 0.
* @dev Reverts if one of `ids` represents a fungible token and there is an overflow of supply.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused.
* @dev Emits an {IERC1155-TransferBatch} event.
* @param to Address of the new tokens owner.
* @param ids Identifiers of the tokens to mint.
* @param values Amounts of tokens to mint.
* @param data Optional data to send along to a receiver contract.
*/
function safeBatchMint(
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
}
| ERC-1155 Inventory, additional minting interface/ | interface IERC1155InventoryMintable {
function safeMint(
address to,
uint256 id,
uint256 value,
bytes calldata data
) external;
function safeBatchMint(
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
}
| 7,306,927 |
// SPDX-License-Identifier:UNLICENSED
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IERC20.sol";
import "@chainlink/contracts/src/v0.7/Chainlink.sol";
import "@chainlink/contracts/src/v0.7/ChainlinkClient.sol";
//import "./BiscuitManager.sol";
contract ChainlinkBroker is ChainlinkClient {
using Chainlink for Chainlink.Request;
address administrator;
uint256 multiplier = 10 ** 18;
address oracle;
bytes32 jobId;
uint256 fee;
uint256 count;
string missionName;
// BiscuitManager spaceBiscuits;
IERC20 LINK;
mapping(bytes32=>string) requestIdStringByRequestIdBytes32;
mapping(string=>bytes32) requestIdBytes32ByRequestIdString;
mapping(string=>string) missionNameByRequestId;
string [] allRequestIds;
string [] allMissionNames;
bytes32 [] allReqIds;
constructor(address _administrator,
address _oracleAddress,
address _linkAddress,
uint256 _fee ) {
setPublicChainlinkToken();
oracle = _oracleAddress;
jobId = "29fa9aa13bf1468788b7cc4a500a45b8";
fee = _fee ;
administrator = _administrator;
LINK = IERC20(_linkAddress);
LINK.approve(_oracleAddress, fee);
}
function requestMissionData() public returns (bytes32 _requestId) {
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
request.add("get", "https://api.spacexdata.com/v2/launches");
request.add("path", "-1.mission_name");
//request.addInt("times", multiplier);
bytes32 reqIdb = sendChainlinkRequestTo(oracle, request, fee);
allReqIds.push(reqIdb);
string memory reqId = bytes32ToString(reqIdb);
allRequestIds.push(reqId);
return reqIdb;
}
function postImageData() external returns (bytes32 _requestId) {
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.notifyPosted.selector);
request.add("get", "https://blockstarlogic.com/spacebiscuitsweb_0_0_2");
request.add("path", "fulfilled");
//request.addInt("times", multiplier);
bytes32 reqIdb = sendChainlinkRequestTo(oracle, request, fee);
allReqIds.push(reqIdb);
string memory reqId = bytes32ToString(reqIdb);
allRequestIds.push(reqId);
return reqIdb;
}
function getFulfilledRequestCount() external view returns (uint256 _fulfilledRequestCount) {
return count;
}
function getMissionName(string memory _requestId) external view returns (string memory _missionName ){
return missionNameByRequestId[_requestId];
}
function getJobId() external view returns (bytes32 _jobId){
return jobId;
}
function getAllRawRequestIds() external view returns (bytes32 [] memory _requestIds) {
return allReqIds;
}
function getAllRequestIds() external view returns (string [] memory _requestIds) {
return allRequestIds;
}
function getAllMissionNames() external view returns (string [] memory _missionNames) {
return allMissionNames;
}
function fulfill(bytes32 _requestId, string memory _missionName) public recordChainlinkFulfillment(_requestId){
string memory reqId = requestIdStringByRequestIdBytes32[_requestId];
allMissionNames.push(_missionName);
missionNameByRequestId[reqId] = _missionName;
//spacebiscuits.createNewBiscuit();
count++;
}
function notifyPosted(bytes32 _requestId, string memory _responseStatus) public recordChainlinkFulfillment(_requestId){
string memory reqId = requestIdStringByRequestIdBytes32[_requestId];
count++;
}
function stringToBytes32(string memory source) public pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function creditLink(uint256 _link) external returns (uint256 _balance) {
LINK.transferFrom(msg.sender, address(this), _link*multiplier);
return this.getLINKBalance();
}
function getLINKBalance() external view returns (uint256 _balance) {
return LINK.balanceOf(address(this));
}
function withdrawLINK() external returns (bool _done) {
LINK.transfer(msg.sender, this.getLINKBalance());
return true;
}
function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
uint8 i = 0;
while(i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
function setBiscuitManager(address _biscuitManager) external returns (bool _set) {
require(msg.sender == administrator, "administrator only");
//spacebiscuits = _biscuitManager(_biscuitManager);
}
}
| spacebiscuits = _biscuitManager(_biscuitManager); | function setBiscuitManager(address _biscuitManager) external returns (bool _set) {
require(msg.sender == administrator, "administrator only");
}
| 1,040,495 |
./full_match/44787/0x2e87b88dA8e1A6FB3399b1CEE168AC638E7D30Eb/sources/contracts/StarFarm.sol | require(NFTOwner[_tokenId] == _msgSender(), "error NFT user");require(userNFTs[_msgSender()].length > 0, "star token user"); | function testenterStakingNFT(uint256 _tokenId) public returns(uint256,address) {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.amount.mul(_selfGain).div(100));
return (_nftAmountGain,NFTOwner[_tokenId]);
}
| 13,257,702 |
./partial_match/1/0xB8C60a5C9d73C0406FF279C65E31496a40F0dc5a/sources/contracts/FlashStrategyLido.sol | Lido: 1 wei corner case stETH balance calculation includes integer division, and there is a common case when the whole stETH balance can't be transferred from the account, while leaving the last 1 wei on the sender's account. Same thing can actually happen at any transfer or deposit transaction. ref: https:docs.lido.fi/guides/steth-integration-guide/ Register how much we are depositing | function depositPrincipal(uint256 _tokenAmount) external override onlyAuthorised returns (uint256) {
principalBalance = principalBalance + _tokenAmount - 1;
return _tokenAmount - 1;
}
| 16,125,591 |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// EMG - A mapping to have the authorized contracts that can call the Data contract.
mapping(address => uint256) authorizedCallers;
// EMG - Initial funding for the insurance is 10 ether
uint private constant INITIAL_FUNDING = 10 ether;
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
// EMG - data structure for the airlines
struct Airline {
address airline;
bool isRegistered;
uint256 fundsProvided;
}
mapping(address => Airline) private airlines;
// EMG - array to store the registered airlines
address[] private registeredAirlines = new address[](0);
struct Flight {
bool isRegistered;
uint8 statusCode;
// EMG - These are the passengers of the flight that have bought an insurance
address[] passengers;
}
mapping(bytes32 => Flight) private flights;
// EMG - data structure for the insurances
struct Insurance {
bool isRegistered;
bool hasBeenPaid;
uint256 amountBought;
uint256 amountPaid;
}
// EMG - mapping from passenger-flight to insurance
mapping(bytes32 => Insurance) private insurances;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
// EMG - The first airline is registered as part of the initial deployment of the contract
airlines[msg.sender] = Airline({
airline: msg.sender,
isRegistered: true,
fundsProvided: 0
});
registeredAirlines.push(msg.sender);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
// EMG - A modifier to make sure the caller is authorized to call functions that require that
modifier isCallerAuthorized()
{
require(authorizedCallers[msg.sender] == 1, "Caller is not authorized");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
// EMG - A function to authorize a contract to call the Data contract, and another one to deauthorize
function authorizeCaller(address dataContract) external requireContractOwner {
authorizedCallers[dataContract] = 1;
}
function deauthorizeCaller(address dataContract) external requireContractOwner {
delete authorizedCallers[dataContract];
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
isCallerAuthorized()
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner()
{
operational = mode;
}
function getDataContractOwner
(
)
external
view
isCallerAuthorized()
returns(address)
{
return contractOwner;
}
// EMG - This is a helper function that can be used for such purposes as testing modifiers
function setTestingMode
(
)
public
view
requireIsOperational()
{
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
// EMG - This function returns the number of airlines currently registered
function numberOfRegisteredAirlines
(
)
external
view
isCallerAuthorized()
returns(uint256)
{
return registeredAirlines.length;
}
// EMG - This function returns whether an airline is registered
function airlineIsRegistered
(
address airline
)
external
view
isCallerAuthorized()
returns(bool)
{
return airlines[airline].isRegistered;
}
// EMG - This function returns whether an airline is funded (i.e., whether it has already provided the contract
// with 10 ether or more
function airlineIsFunded
(
address airline
)
external
view
isCallerAuthorized()
returns(bool)
{
return (airlines[airline].fundsProvided >= INITIAL_FUNDING);
}
// EMG - This function returns whether a flight is registered
function flightIsRegistered
(
address airline,
string flightNumber,
uint256 timestamp
)
external
view
isCallerAuthorized()
returns(bool)
{
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
return (flights[flightKey].isRegistered);
}
// EMG - This function returns whether an insurance is registered
function insuranceIsRegistered
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
view
isCallerAuthorized()
returns(bool)
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
return (insurances[insuranceKey].isRegistered);
}
// EMG - This function returns whether an insurance has been paid
function insuranceHasBeenPaid
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
view
isCallerAuthorized()
returns(bool)
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
return (insurances[insuranceKey].hasBeenPaid);
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address airline
)
external
// EMG - Can only be called from FlightSuretyApp contract
isCallerAuthorized()
{
airlines[airline] = Airline({
airline: airline,
isRegistered: true,
fundsProvided: 0
});
registeredAirlines.push(airline);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
// EMG - A registered airline can provide as many funds as it wants. However, it is not going to be
// considered funded until the amount provided is greater than or equal to 10 ether
function fund
(
address airline
)
public
payable
isCallerAuthorized()
{
require(airlines[airline].isRegistered, "Airline is not registered");
airlines[airline].fundsProvided = airlines[airline].fundsProvided.add(msg.value);
}
function registerFlight
(
address airline,
string flightNumber,
uint256 timestamp
)
external
isCallerAuthorized()
{
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
// EMG - STATUS_CODE_UNKNOWN = 0
flights[flightKey] = Flight({
isRegistered: true,
statusCode: 0,
passengers: new address[](0)
});
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
payable
isCallerAuthorized()
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
insurances[insuranceKey] = Insurance({
isRegistered: true,
hasBeenPaid: false,
amountBought: msg.value,
amountPaid: 0
});
// The insured passenger is included within the list of insured passengers of the flight
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
flights[flightKey].passengers.push(passenger);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus
(
address airline,
string flightNumber,
uint256 timestamp
)
external
isCallerAuthorized()
{
creditInsurees(airline, flightNumber, timestamp);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
address airline,
string memory flightNumber,
uint256 timestamp
)
internal
{
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
for(uint c = 0; c < flights[flightKey].passengers.length; c++) {
bytes32 insuranceKey = getInsuranceKey(flights[flightKey].passengers[c], airline,
flightNumber, timestamp);
// The passenger is credited 1.5X the amount they paid
insurances[insuranceKey].amountPaid = insurances[insuranceKey].amountBought.mul(3).div(2);
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
isCallerAuthorized()
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
insurances[insuranceKey].hasBeenPaid = true;
passenger.transfer(insurances[insuranceKey].amountPaid);
}
function getFlightKey
(
address airline,
string memory flightNumber,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flightNumber, timestamp));
}
// EMG - Calculation of the key of the insurances mapping
function getInsuranceKey
(
address passenger,
address airline,
string memory flightNumber,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(passenger, airline, flightNumber, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
// EMG - Even though it is not the intended procedure to provide funds to the Data contract,
// it is possible to call the fallback function in the Data Contract. This will cause the fund
// function to be executed
function()
external
payable
{
fund(msg.sender);
}
}
| EMG - This function returns whether an airline is registered | function airlineIsRegistered
(
address airline
)
external
view
isCallerAuthorized()
returns(bool)
{
return airlines[airline].isRegistered;
}
| 13,019,184 |
./full_match/1/0xe5BB8654F698c5f021dA21146219f6a998F2aA99/sources/contracts/v3/tokens/ERC721LA.sol | Returns the index of the batch for a given token. If the token was not bought in a batch tokenId == tokenIdBatchHead/ | function _getBatchHead(uint256 tokenId)
internal
view
returns (uint256 tokenIdBatchHead)
{
ERC721State.ERC721LAState storage state = ERC721State
._getERC721LAState();
(uint256 editionId, ) = parseEditionFromTokenId(tokenId);
tokenIdBatchHead = state._batchHead.scanForward(
tokenId,
editionId * state._edition_max_tokens
);
}
| 3,137,236 |
./full_match/1/0x788f328843a185B1B484e72ADEFbAB6c8AEE95af/sources/WrappedERC721.sol | See {IERC721Enumerable-totalSupply}./ | function totalSupply() public view virtual override returns (uint256) {
return wrappedContract.totalSupply();
}
| 2,962,684 |
./full_match/1/0x0EBB2B76FBdcc3a636b652fd3769154b5C196249/sources/contracts2/CSPLGuildPoolV2.sol | ギルドトークンごとの引き出し可能な量 全体の総和×割合-これまで引き出した量 | function getGuildStockWithdrawableBalance(uint256 _guildTokenId) public view returns (uint256) {
guildAsset.isValidGuildStock(_guildTokenId);
uint16 _guildType = guildAsset.getGuildType(_guildTokenId);
(uint256 shareRate, uint256 decimal) = guildAsset.getShareRateWithDecimal(_guildTokenId);
uint256 maxAmount = guildTypeToTotalAmount[_guildType] * shareRate / decimal;
return maxAmount - guildStockToWithdrawnAmount[_guildTokenId];
}
| 8,294,344 |
./full_match/5/0xA18817e452d5b5913A28fB1a9d1257aF98b79059/sources/contracts/messaging/WatcherClient.sol | ============ Watcher fns ============ | function pause() external onlyWatcher whenNotPaused {
_pause();
}
| 1,923,829 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../interfaces/ILendingPoolAaveCompatible.sol';
import './LendingPool.sol';
/// @dev LendingPoolCompatible is a wrapper for backward compatibility with AAVE due to modified referral field format.
contract LendingPoolCompatible is LendingPool, ILendingPoolAaveCompatible {
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referral
) external override {
super.deposit(asset, amount, onBehalfOf, uint256(referral));
}
function borrow(
address,
uint256,
uint256,
uint16,
address
) external override {
_delegate(_extension);
}
function flashLoan(
address,
address[] calldata,
uint256[] calldata,
uint256[] calldata,
address,
bytes calldata,
uint16
) external override {
_delegate(_extension);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
/// @dev ILendingPoolAaveCompatible uses uint16 referral for full backward compatibility with AAVE
interface ILendingPoolAaveCompatible {
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referral
) external;
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referral,
address onBehalfOf
) external;
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referral
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../dependencies/openzeppelin/contracts/IERC20.sol';
import '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import '../../dependencies/openzeppelin/contracts/Address.sol';
import '../../access/interfaces/IMarketAccessController.sol';
import '../../access/AccessHelper.sol';
import '../../interfaces/IDepositToken.sol';
import '../../interfaces/IVariableDebtToken.sol';
import '../../interfaces/ILendingPool.sol';
import '../../interfaces/ILendingPoolForTokens.sol';
import '../../flashloan/interfaces/IFlashLoanReceiver.sol';
import '../../interfaces/IStableDebtToken.sol';
import '../../tools/upgradeability/Delegator.sol';
import '../../tools/Errors.sol';
import '../../tools/math/WadRayMath.sol';
import '../libraries/helpers/Helpers.sol';
import '../libraries/logic/GenericLogic.sol';
import '../libraries/logic/ValidationLogic.sol';
import '../libraries/logic/ReserveLogic.sol';
import '../libraries/types/DataTypes.sol';
import './LendingPoolBase.sol';
/**
* @title LendingPool contract
* @dev Main point of interaction with a protocol's market
* - Users can:
* # Deposit
* # Withdraw
* # Borrow
* # Repay
* # Swap their loans between variable and stable rate
* # Enable/disable their deposits as collateral rebalance stable rate borrow positions
* # Liquidate positions
* # Execute Flash Loans
**/
contract LendingPool is LendingPoolBase, ILendingPool, Delegator, ILendingPoolForTokens {
using SafeERC20 for IERC20;
using WadRayMath for uint256;
using AccessHelper for IMarketAccessController;
using ReserveLogic for DataTypes.ReserveData;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
uint256 private constant POOL_REVISION = 0x1;
function getRevision() internal pure virtual override returns (uint256) {
return POOL_REVISION;
}
function initialize(IMarketAccessController provider) public initializer(POOL_REVISION) {
_addressesProvider = provider;
_maxStableRateBorrowSizePct = 25 * PercentageMath.PCT;
_flashLoanPremiumPct = 9 * PercentageMath.BP;
}
// solhint-disable-next-line payable-fallback
fallback() external {
// all IManagedLendingPool etc functions should be delegated to the extension
_delegate(_extension);
}
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint256 referral
) public override whenNotPaused noReentryOrFlashloanFeature(FEATURE_FLASHLOAN_DEPOSIT) {
DataTypes.ReserveData storage reserve = _reserves[asset];
ValidationLogic.validateDeposit(reserve, amount);
address depositToken = reserve.depositTokenAddress;
uint256 liquidityIndex = reserve.updateStateForDeposit(asset);
reserve.updateInterestRates(asset, depositToken, amount, 0);
IERC20(asset).safeTransferFrom(msg.sender, depositToken, amount);
bool isFirstDeposit = IDepositToken(depositToken).mint(onBehalfOf, amount, liquidityIndex, false);
if (isFirstDeposit) {
_usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id);
emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf);
}
emit Deposit(asset, msg.sender, onBehalfOf, amount, referral);
}
function withdraw(
address asset,
uint256 amountToWithdraw,
address to
) external override whenNotPaused noReentryOrFlashloanFeature(FEATURE_FLASHLOAN_WITHDRAW) returns (uint256) {
DataTypes.ReserveData storage reserve = _reserves[asset];
address depositToken = reserve.depositTokenAddress;
uint256 liquidityIndex = reserve.updateStateForDeposit(asset);
uint256 userBalance = IDepositToken(depositToken).scaledBalanceOf(msg.sender);
userBalance = userBalance.rayMul(liquidityIndex);
if (amountToWithdraw == type(uint256).max) {
amountToWithdraw = userBalance;
}
ValidationLogic.validateWithdraw(
asset,
amountToWithdraw,
userBalance,
_reserves,
_usersConfig[msg.sender],
_reservesList,
_addressesProvider.getPriceOracle()
);
reserve.updateInterestRates(asset, depositToken, 0, amountToWithdraw);
if (amountToWithdraw == userBalance) {
_usersConfig[msg.sender].unsetUsingAsCollateral(reserve.id);
emit ReserveUsedAsCollateralDisabled(asset, msg.sender);
}
IDepositToken(depositToken).burn(msg.sender, to, amountToWithdraw, liquidityIndex);
emit Withdraw(asset, msg.sender, to, amountToWithdraw);
return amountToWithdraw;
}
function borrow(
address,
uint256,
uint256,
uint256,
address
) external override {
// for compatibility with ILendingPool
_delegate(_extension);
}
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external override whenNotPaused noReentryOrFlashloanFeature(FEATURE_FLASHLOAN_REPAY) returns (uint256) {
DataTypes.ReserveData storage reserve = _reserves[asset];
(uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve);
DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode);
ValidationLogic.validateRepay(reserve, amount, interestRateMode, onBehalfOf, stableDebt, variableDebt);
uint256 paybackAmount = interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt;
if (amount < paybackAmount) {
paybackAmount = amount;
}
reserve.updateState(asset);
if (interestRateMode == DataTypes.InterestRateMode.STABLE) {
IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount);
} else {
IVariableDebtToken(reserve.variableDebtTokenAddress).burn(onBehalfOf, paybackAmount, reserve.variableBorrowIndex);
}
address depositToken = reserve.depositTokenAddress;
reserve.updateInterestRates(asset, depositToken, paybackAmount, 0);
if (stableDebt + variableDebt <= paybackAmount) {
_usersConfig[onBehalfOf].unsetBorrowing(reserve.id);
}
IERC20(asset).safeTransferFrom(msg.sender, depositToken, paybackAmount);
emit Repay(asset, onBehalfOf, msg.sender, paybackAmount);
return paybackAmount;
}
function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused noReentryOrFlashloan {
DataTypes.ReserveData storage reserve = _reserves[asset];
(uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve);
DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode);
ValidationLogic.validateSwapRateMode(reserve, _usersConfig[msg.sender], stableDebt, variableDebt, interestRateMode);
reserve.updateState(asset);
if (interestRateMode == DataTypes.InterestRateMode.STABLE) {
IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt);
IVariableDebtToken(reserve.variableDebtTokenAddress).mint(
msg.sender,
msg.sender,
stableDebt,
reserve.variableBorrowIndex
);
} else {
IVariableDebtToken(reserve.variableDebtTokenAddress).burn(msg.sender, variableDebt, reserve.variableBorrowIndex);
IStableDebtToken(reserve.stableDebtTokenAddress).mint(
msg.sender,
msg.sender,
variableDebt,
reserve.currentStableBorrowRate
);
}
reserve.updateInterestRates(asset, reserve.depositTokenAddress, 0, 0);
emit Swap(asset, msg.sender, rateMode);
}
function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused noReentryOrFlashloan {
DataTypes.ReserveData storage reserve = _reserves[asset];
IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress);
uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user);
address depositToken = reserve.depositTokenAddress;
ValidationLogic.validateRebalanceStableBorrowRate(reserve, asset, stableDebtToken, depositToken);
reserve.updateState(asset);
IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt);
IStableDebtToken(address(stableDebtToken)).mint(user, user, stableDebt, reserve.currentStableBorrowRate);
reserve.updateInterestRates(asset, depositToken, 0, 0);
emit RebalanceStableBorrowRate(asset, user);
}
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
ValidationLogic.validateSetUseReserveAsCollateral(
reserve,
asset,
useAsCollateral,
_reserves,
_usersConfig[msg.sender],
_reservesList,
_addressesProvider.getPriceOracle()
);
if (useAsCollateral) {
_usersConfig[msg.sender].setUsingAsCollateral(reserve.id);
emit ReserveUsedAsCollateralEnabled(asset, msg.sender);
} else {
_usersConfig[msg.sender].unsetUsingAsCollateral(reserve.id);
emit ReserveUsedAsCollateralDisabled(asset, msg.sender);
}
}
function liquidationCall(
address,
address,
address,
uint256,
bool
) external override {
// for compatibility with ILendingPool
_delegate(_extension);
}
function flashLoan(
address,
address[] calldata,
uint256[] calldata,
uint256[] calldata,
address,
bytes calldata,
uint256
) external override {
// for compatibility with ILendingPool
_delegate(_extension);
}
function getReserveData(address asset)
external
view
override(ILendingPool, ILendingPoolForTokens)
returns (DataTypes.ReserveData memory)
{
return _reserves[asset];
}
function getUserAccountData(address user)
external
view
override
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
)
{
(totalCollateralETH, totalDebtETH, ltv, currentLiquidationThreshold, healthFactor) = GenericLogic
.calculateUserAccountData(
user,
_reserves,
_usersConfig[user],
_reservesList,
_addressesProvider.getPriceOracle()
);
availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH(totalCollateralETH, totalDebtETH, ltv);
}
function getConfiguration(address asset)
external
view
override(ILendingPool, ILendingPoolForTokens)
returns (DataTypes.ReserveConfigurationMap memory)
{
return _reserves[asset].configuration;
}
function getUserConfiguration(address user) external view override returns (DataTypes.UserConfigurationMap memory) {
return _usersConfig[user];
}
function getReserveNormalizedIncome(address asset)
external
view
virtual
override(ILendingPool, ILendingPoolForTokens)
returns (uint256)
{
return _reserves[asset].getNormalizedIncome(asset);
}
function getReserveNormalizedVariableDebt(address asset)
external
view
override(ILendingPool, ILendingPoolForTokens)
returns (uint256)
{
return _reserves[asset].getNormalizedDebt();
}
function getReservesList() external view override(ILendingPool, ILendingPoolForTokens) returns (address[] memory) {
address[] memory _activeReserves = new address[](_reservesCount);
for (uint256 i = 0; i < _reservesCount; i++) {
_activeReserves[i] = _reservesList[i];
}
return _activeReserves;
}
function getAccessController() external view override returns (IMarketAccessController) {
return _addressesProvider;
}
/// @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate
// solhint-disable-next-line func-name-mixedcase
function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) {
return _maxStableRateBorrowSizePct;
}
/// @dev Returns the fee of flash loans - backward compatible
// solhint-disable-next-line func-name-mixedcase
function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) {
return _flashLoanPremiumPct;
}
function getFlashloanPremiumPct() public view override returns (uint16) {
return _flashLoanPremiumPct;
}
function getAddressesProvider() external view override returns (address) {
return address(_addressesProvider);
}
/// @dev Returns the address of the LendingPoolExtension
function getLendingPoolExtension() external view returns (address) {
return _extension;
}
/// @dev Updates the address of the LendingPoolExtension
function setLendingPoolExtension(address extension) external onlyConfiguratorOrAdmin {
require(Address.isContract(extension), Errors.VL_CONTRACT_REQUIRED);
_extension = extension;
emit LendingPoolExtensionUpdated(extension);
}
function finalizeTransfer(
address asset,
address from,
address to,
bool lastBalanceFrom,
bool firstBalanceTo
) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
require(msg.sender == reserve.depositTokenAddress, Errors.LP_CALLER_MUST_BE_DEPOSIT_TOKEN);
DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from];
ValidationLogic.validateTransfer(
asset,
from,
_reserves,
fromConfig,
_reservesList,
_addressesProvider.getPriceOracle()
);
if (from != to) {
if (lastBalanceFrom) {
fromConfig.unsetUsingAsCollateral(reserve.id);
emit ReserveUsedAsCollateralDisabled(asset, from);
}
if (firstBalanceTo) {
DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to];
toConfig.setUsingAsCollateral(reserve.id);
emit ReserveUsedAsCollateralEnabled(asset, to);
}
}
}
function setReservePaused(address asset, bool paused) external override {
DataTypes.ReserveData storage reserve = _reserves[asset];
if (msg.sender != reserve.depositTokenAddress) {
_onlyEmergencyAdmin();
require(reserve.depositTokenAddress != address(0), Errors.VL_UNKNOWN_RESERVE);
}
DataTypes.ReserveConfigurationMap memory config = reserve.configuration;
config.setFrozen(paused);
reserve.configuration = config;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
/**
* @dev Interface of the ERC20 standard as defined in the EIP excluding events to avoid linearization issues.
*/
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.
*/
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
*/
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.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import './IERC20.sol';
import './Address.sol';
/**
* @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 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));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
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 callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), 'SafeERC20: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, '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');
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// solhint-disable no-inline-assembly, avoid-low-level-calls
/**
* @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;
assembly {
size := extcodesize(account)
}
return size > 0;
}
bytes32 private constant accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
function isExternallyOwned(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
uint256 size;
assembly {
codehash := extcodehash(account)
size := extcodesize(account)
}
return codehash == accountHash && 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}.
*/
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.
*
* 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');
(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');
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, 'Address: low-level delegate call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), 'Address: delegate call to non-contract');
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IAccessController.sol';
/// @dev Main registry of addresses part of or connected to the protocol, including permissioned roles. Also acts a proxy factory.
interface IMarketAccessController is IAccessController {
function getMarketId() external view returns (string memory);
function getLendingPool() external view returns (address);
function getPriceOracle() external view returns (address);
function getLendingRateOracle() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './interfaces/IRemoteAccessBitmask.sol';
/// @dev Helper/wrapper around IRemoteAccessBitmask
library AccessHelper {
function getAcl(IRemoteAccessBitmask remote, address subject) internal view returns (uint256) {
return remote.queryAccessControlMask(subject, ~uint256(0));
}
function queryAcl(
IRemoteAccessBitmask remote,
address subject,
uint256 filterMask
) internal view returns (uint256) {
return remote.queryAccessControlMask(subject, filterMask);
}
function hasAnyOf(
IRemoteAccessBitmask remote,
address subject,
uint256 flags
) internal view returns (bool) {
uint256 found = queryAcl(remote, subject, flags);
return found & flags != 0;
}
function hasAny(IRemoteAccessBitmask remote, address subject) internal view returns (bool) {
return remote.queryAccessControlMask(subject, 0) != 0;
}
function hasNone(IRemoteAccessBitmask remote, address subject) internal view returns (bool) {
return remote.queryAccessControlMask(subject, 0) == 0;
}
function requireAnyOf(
IRemoteAccessBitmask remote,
address subject,
uint256 flags,
string memory text
) internal view {
require(hasAnyOf(remote, subject, flags), text);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../dependencies/openzeppelin/contracts/IERC20.sol';
import './IScaledBalanceToken.sol';
import './IPoolToken.sol';
interface IDepositToken is IERC20, IPoolToken, IScaledBalanceToken {
/**
* @dev Emitted on mint
* @param account The receiver of minted tokens
* @param value The amount minted
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed account, uint256 value, uint256 index);
/**
* @dev Mints `amount` depositTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @param repayOverdraft Enables to use this amount cover an overdraft
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index,
bool repayOverdraft
) external returns (bool);
/**
* @dev Emitted on burn
* @param account The owner of tokens burned
* @param target The receiver of the underlying
* @param value The amount burned
* @param index The new liquidity index of the reserve
**/
event Burn(address indexed account, address indexed target, uint256 value, uint256 index);
/**
* @dev Emitted on transfer
* @param from The sender
* @param to The recipient
* @param value The amount transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);
/**
* @dev Burns depositTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the depositTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints depositTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers depositTokens in the event of a borrow being liquidated, in case the liquidators reclaims the depositToken
* @param from The address getting liquidated, current owner of the depositTokens
* @param to The recipient
* @param value The amount of tokens getting transferred
* @param index The liquidity index of the reserve
* @param transferUnderlying is true when the underlying should be, otherwise the depositToken
* @return true when transferUnderlying is false and the recipient had zero balance
**/
function transferOnLiquidation(
address from,
address to,
uint256 value,
uint256 index,
bool transferUnderlying
) external returns (bool);
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the underlying
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);
function collateralBalanceOf(address) external view returns (uint256);
/**
* @dev Emitted on use of overdraft (by liquidation)
* @param account The receiver of overdraft (user with shortage)
* @param value The amount received
* @param index The liquidity index of the reserve
**/
event OverdraftApplied(address indexed account, uint256 value, uint256 index);
/**
* @dev Emitted on return of overdraft allowance when it was fully or partially used
* @param provider The provider of overdraft
* @param recipient The receiver of overdraft
* @param overdraft The amount overdraft that was covered by the provider
* @param index The liquidity index of the reserve
**/
event OverdraftCovered(address indexed provider, address indexed recipient, uint256 overdraft, uint256 index);
event SubBalanceProvided(address indexed provider, address indexed recipient, uint256 amount, uint256 index);
event SubBalanceReturned(address indexed provider, address indexed recipient, uint256 amount, uint256 index);
event SubBalanceLocked(address indexed provider, uint256 amount, uint256 index);
event SubBalanceUnlocked(address indexed provider, uint256 amount, uint256 index);
function updateTreasury() external;
function addSubBalanceOperator(address addr) external;
function addStakeOperator(address addr) external;
function removeSubBalanceOperator(address addr) external;
function provideSubBalance(
address provider,
address recipient,
uint256 scaledAmount
) external;
function returnSubBalance(
address provider,
address recipient,
uint256 scaledAmount,
bool preferOverdraft
) external returns (uint256 coveredOverdraft);
function lockSubBalance(address provider, uint256 scaledAmount) external;
function unlockSubBalance(
address provider,
uint256 scaledAmount,
address transferTo
) external;
function replaceSubBalance(
address prevProvider,
address recipient,
uint256 prevScaledAmount,
address newProvider,
uint256 newScaledAmount
) external returns (uint256 coveredOverdraftByPrevProvider);
function transferLockedBalance(
address from,
address to,
uint256 scaledAmount
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IScaledBalanceToken.sol';
import '../dependencies/openzeppelin/contracts/IERC20.sol';
import './IPoolToken.sol';
/// @dev Defines the basic interface for a variable debt token.
interface IVariableDebtToken is IPoolToken, IScaledBalanceToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param onBehalfOf The address of the user on which behalf minting has been performed
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);
/// @dev Mints debt token to the `onBehalfOf` address. Returns `true` when balance of the `onBehalfOf` was 0
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/// @dev Burns user variable debt
function burn(
address user,
uint256 amount,
uint256 index
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../protocol/libraries/types/DataTypes.sol';
import './ILendingPoolEvents.sol';
interface ILendingPool is ILendingPoolEvents {
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying depositTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the depositTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of depositTokens
* is a different wallet
* @param referral Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint256 referral
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent depositTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole depositToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referral Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint256 referral,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external returns (uint256);
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveDeposit `true` if the liquidators wants to receive the collateral depositTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveDeposit
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referral Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint256 referral
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function getReservesList() external view returns (address[] memory);
function getAddressesProvider() external view returns (address);
function getFlashloanPremiumPct() external view returns (uint16);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../access/interfaces/IMarketAccessController.sol';
import '../protocol/libraries/types/DataTypes.sol';
interface ILendingPoolForTokens {
/**
* @dev Validates and finalizes an depositToken transfer
* - Only callable by the overlying depositToken of the `asset`
* @param asset The address of the underlying asset of the depositToken
* @param from The user from which the depositToken are transferred
* @param to The user receiving the depositToken
* @param lastBalanceFrom True when from's balance was non-zero and became zero
* @param firstBalanceTo True when to's balance was zero and became non-zero
*/
function finalizeTransfer(
address asset,
address from,
address to,
bool lastBalanceFrom,
bool firstBalanceTo
) external;
function getAccessController() external view returns (IMarketAccessController);
function getReserveNormalizedIncome(address asset) external view returns (uint256);
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function getReservesList() external view returns (address[] memory);
function setReservePaused(address asset, bool paused) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../interfaces/IFlashLoanAddressProvider.sol';
import '../../interfaces/ILendingPool.sol';
// solhint-disable func-name-mixedcase
/**
* @title IFlashLoanReceiver interface
* @notice Interface for the Aave fee IFlashLoanReceiver.
* @author Aave
* @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract
**/
interface IFlashLoanReceiver {
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool);
function ADDRESS_PROVIDER() external view returns (IFlashLoanAddressProvider);
function LENDING_POOL() external view returns (ILendingPool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IBalanceHook.sol';
import '../dependencies/openzeppelin/contracts/IERC20.sol';
import './IPoolToken.sol';
/// @dev Defines the interface for the stable debt token
interface IStableDebtToken is IPoolToken {
/**
* @dev Emitted when new stable debt is minted
* @param user The address of the user who triggered the minting
* @param onBehalfOf The recipient of stable debt tokens
* @param amount The amount minted
* @param currentBalance The current balance of the user
* @param balanceIncrease The increase in balance since the last action of the user
* @param newRate The rate of the debt after the minting
* @param avgStableRate The new average stable rate after the minting
* @param newTotalSupply The new total supply of the stable debt token after the action
**/
event Mint(
address indexed user,
address indexed onBehalfOf,
uint256 amount,
uint256 currentBalance,
uint256 balanceIncrease,
uint256 newRate,
uint256 avgStableRate,
uint256 newTotalSupply
);
/**
* @dev Emitted when new stable debt is burned
* @param user The address of the user
* @param amount The amount being burned
* @param currentBalance The current balance of the user
* @param balanceIncrease The the increase in balance since the last action of the user
* @param avgStableRate The new average stable rate after the burning
* @param newTotalSupply The new total supply of the stable debt token after the action
**/
event Burn(
address indexed user,
uint256 amount,
uint256 currentBalance,
uint256 balanceIncrease,
uint256 avgStableRate,
uint256 newTotalSupply
);
/**
* @dev Mints debt token to the `onBehalfOf` address.
* - The resulting rate is the weighted average between the rate of the new debt
* and the rate of the previous debt
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt tokens to mint
* @param rate The rate of the debt being minted
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 rate
) external returns (bool);
/**
* @dev Burns debt of `user`
* - The resulting rate is the weighted average between the rate of the new debt
* and the rate of the previous debt
* @param user The address of the user getting his debt burned
* @param amount The amount of debt tokens getting burned
**/
function burn(address user, uint256 amount) external;
/// @dev Returns the average rate of all the stable rate loans
function getAverageStableRate() external view returns (uint256);
/// @dev Returns the stable rate of the user debt
function getUserStableRate(address user) external view returns (uint256);
/// @dev Returns the timestamp of the last update of the user
function getUserLastUpdated(address user) external view returns (uint40);
/// @dev Returns the principal, the total supply and the average stable rate
function getSupplyData()
external
view
returns (
uint256,
uint256,
uint256,
uint40
);
/// @dev Returns the timestamp of the last update of the total supply
function getTotalSupplyLastUpdated() external view returns (uint40);
/// @dev Returns the total supply and the average stable rate
function getTotalSupplyAndAvgRate() external view returns (uint256, uint256);
/// @dev Returns the principal debt balance of the user
function principalBalanceOf(address user) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
/// @dev Provides delegation of calls with proper forwarding of return values and bubbling of failures. Based on OpenZeppelin Proxy.
abstract contract Delegator {
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
require(implementation != address(0));
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
/**
* @title Errors library
* @notice Defines the error messages emitted by the different contracts
* @dev Error messages prefix glossary:
* - VL = ValidationLogic
* - MATH = Math libraries
* - CT = Common errors between tokens (DepositToken, VariableDebtToken and StableDebtToken)
* - AT = DepositToken
* - SDT = StableDebtToken
* - VDT = VariableDebtToken
* - LP = LendingPool
* - LPAPR = AddressesProviderRegistry
* - LPC = LendingPoolConfiguration
* - RL = ReserveLogic
* - LPCM = LendingPoolExtension
* - ST = Stake
*/
library Errors {
//contract specific errors
string public constant VL_INVALID_AMOUNT = '1'; // Amount must be greater than 0
string public constant VL_NO_ACTIVE_RESERVE = '2'; // Action requires an active reserve
string public constant VL_RESERVE_FROZEN = '3'; // Action cannot be performed because the reserve is frozen
string public constant VL_UNKNOWN_RESERVE = '4'; // Action requires an active reserve
string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // User cannot withdraw more than the available balance (above min limit)
string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // Transfer cannot be allowed.
string public constant VL_BORROWING_NOT_ENABLED = '7'; // Borrowing is not enabled
string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // Invalid interest rate mode selected
string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // The collateral balance is 0
string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // Health factor is lesser than the liquidation threshold
string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // There is not enough collateral to cover a new borrow
string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled
string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed
string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // The requested amount is exceeds max size of a stable loan
string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // to repay a debt, user needs to specify a correct debt type (variable or stable)
string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // To repay on behalf of an user an explicit amount to repay is needed
string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // User does not have a stable rate loan in progress on this reserve
string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // User does not have a variable rate loan in progress on this reserve
string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // The collateral balance needs to be greater than 0
string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // User deposit is already being used as collateral
string public constant VL_RESERVE_MUST_BE_COLLATERAL = '21'; // This reserve must be enabled as collateral
string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // Interest rate rebalance conditions were not met
string public constant AT_OVERDRAFT_DISABLED = '23'; // User doesn't accept allocation of overdraft
string public constant VL_INVALID_SUB_BALANCE_ARGS = '24';
string public constant AT_INVALID_SLASH_DESTINATION = '25';
string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // The caller of the function is not the lending pool configurator
string public constant LENDING_POOL_REQUIRED = '28'; // The caller of this function must be a lending pool
string public constant CALLER_NOT_LENDING_POOL = '29'; // The caller of this function must be a lending pool
string public constant AT_SUB_BALANCE_RESTIRCTED_FUNCTION = '30'; // The caller of this function must be a lending pool or a sub-balance operator
string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // Reserve has already been initialized
string public constant CALLER_NOT_POOL_ADMIN = '33'; // The caller must be the pool admin
string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // The liquidity of the reserve needs to be 0
string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // Provider is not registered
string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // Health factor is not below the threshold
string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // The collateral chosen cannot be liquidated
string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // User did not borrow the specified currency
string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // There isn't enough liquidity available to liquidate
string public constant MATH_MULTIPLICATION_OVERFLOW = '48';
string public constant MATH_ADDITION_OVERFLOW = '49';
string public constant MATH_DIVISION_BY_ZERO = '50';
string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128
string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128
string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128
string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128
string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128
string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint
string public constant CALLER_NOT_STAKE_ADMIN = '57';
string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn
string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small
string public constant CALLER_NOT_LIQUIDITY_CONTROLLER = '60';
string public constant CALLER_NOT_REF_ADMIN = '61';
string public constant VL_INSUFFICIENT_REWARD_AVAILABLE = '62';
string public constant LP_CALLER_MUST_BE_DEPOSIT_TOKEN = '63';
string public constant LP_IS_PAUSED = '64'; // Pool is paused
string public constant LP_NO_MORE_RESERVES_ALLOWED = '65';
string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66';
string public constant RC_INVALID_LTV = '67';
string public constant RC_INVALID_LIQ_THRESHOLD = '68';
string public constant RC_INVALID_LIQ_BONUS = '69';
string public constant RC_INVALID_DECIMALS = '70';
string public constant RC_INVALID_RESERVE_FACTOR = '71';
string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72';
string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73';
string public constant VL_TREASURY_REQUIRED = '74';
string public constant LPC_INVALID_CONFIGURATION = '75'; // Invalid risk parameters for the reserve
string public constant CALLER_NOT_EMERGENCY_ADMIN = '76'; // The caller must be the emergency admin
string public constant UL_INVALID_INDEX = '77';
string public constant VL_CONTRACT_REQUIRED = '78';
string public constant SDT_STABLE_DEBT_OVERFLOW = '79';
string public constant SDT_BURN_EXCEEDS_BALANCE = '80';
string public constant CALLER_NOT_REWARD_CONFIG_ADMIN = '81'; // The caller of this function must be a reward admin
string public constant LP_INVALID_PERCENTAGE = '82'; // Percentage can't be more than 100%
string public constant LP_IS_NOT_TRUSTED_FLASHLOAN = '83';
string public constant CALLER_NOT_SWEEP_ADMIN = '84';
string public constant LP_TOO_MANY_NESTED_CALLS = '85';
string public constant LP_RESTRICTED_FEATURE = '86';
string public constant LP_TOO_MANY_FLASHLOAN_CALLS = '87';
string public constant RW_BASELINE_EXCEEDED = '88';
string public constant CALLER_NOT_REWARD_RATE_ADMIN = '89';
string public constant CALLER_NOT_REWARD_CONTROLLER = '90';
string public constant RW_REWARD_PAUSED = '91';
string public constant CALLER_NOT_TEAM_MANAGER = '92';
string public constant STK_REDEEM_PAUSED = '93';
string public constant STK_INSUFFICIENT_COOLDOWN = '94';
string public constant STK_UNSTAKE_WINDOW_FINISHED = '95';
string public constant STK_INVALID_BALANCE_ON_COOLDOWN = '96';
string public constant STK_EXCESSIVE_SLASH_PCT = '97';
string public constant STK_WRONG_COOLDOWN_OR_UNSTAKE = '98';
string public constant STK_PAUSED = '99';
string public constant TXT_OWNABLE_CALLER_NOT_OWNER = 'Ownable: caller is not the owner';
string public constant TXT_CALLER_NOT_PROXY_OWNER = 'ProxyOwner: caller is not the owner';
string public constant TXT_ACCESS_RESTRICTED = 'RESTRICTED';
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../Errors.sol';
/// @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
library WadRayMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/// @return One ray, 1e27
function ray() internal pure returns (uint256) {
return RAY;
}
/// @return One wad, 1e18
function wad() internal pure returns (uint256) {
return WAD;
}
/// @return Half ray, 1e27/2
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/// @return Half ray, 1e18/2
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/// @dev Multiplies two wad, rounding half up to the nearest wad
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfWAD) / WAD;
}
/// @dev Divides two wad, rounding half up to the nearest wad
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * WAD + halfB) / b;
}
/// @dev Multiplies two ray, rounding half up to the nearest ray
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfRAY) / RAY;
}
/// @dev Divides two ray, rounding half up to the nearest ray
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * RAY + halfB) / b;
}
/// @dev Casts ray down to wad
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / WAD_RAY_RATIO;
}
/// @dev Converts wad up to ray
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import '../types/DataTypes.sol';
library Helpers {
/// @dev Fetches the user current stable and variable debt balances
function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve)
internal
view
returns (uint256, uint256)
{
return (
IERC20(reserve.stableDebtTokenAddress).balanceOf(user),
IERC20(reserve.variableDebtTokenAddress).balanceOf(user)
);
}
function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve)
internal
view
returns (uint256, uint256)
{
return (
IERC20(reserve.stableDebtTokenAddress).balanceOf(user),
IERC20(reserve.variableDebtTokenAddress).balanceOf(user)
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import './ReserveLogic.sol';
import '../configuration/ReserveConfiguration.sol';
import '../configuration/UserConfiguration.sol';
import '../../../tools/math/WadRayMath.sol';
import '../../../tools/math/PercentageMath.sol';
import '../../../interfaces/IPriceOracleGetter.sol';
import '../types/DataTypes.sol';
/// @title Implements protocol-level logic to calculate and validate the state of a user
library GenericLogic {
using ReserveLogic for DataTypes.ReserveData;
using WadRayMath for uint256;
using PercentageMath for uint256;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether;
struct BalanceDecreaseAllowedLocalVars {
uint256 decimals;
uint256 liquidationThreshold;
uint256 totalCollateralInETH;
uint256 totalDebtInETH;
uint256 avgLiquidationThreshold;
uint256 amountToDecreaseInETH;
uint256 collateralBalanceAfterDecrease;
uint256 liquidationThresholdAfterDecrease;
uint256 healthFactorAfterDecrease;
bool reserveUsageAsCollateralEnabled;
}
/**
* @dev Checks if a specific balance decrease is allowed
* (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD)
* @param asset The address of the underlying asset of the reserve
* @param user The address of the user
* @param amount The amount to decrease
* @param reservesData The data of all the reserves
* @param userConfig The user configuration
* @param reserves The list of all the active reserves
* @param oracle The address of the oracle contract
* @return true if the decrease of the balance is allowed
**/
function balanceDecreaseAllowed(
address asset,
address user,
uint256 amount,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap memory userConfig,
mapping(uint256 => address) storage reserves,
address oracle
) internal view returns (bool) {
if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) {
return true;
}
BalanceDecreaseAllowedLocalVars memory vars;
(, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset].configuration.getParams();
if (vars.liquidationThreshold == 0) {
return true;
}
(vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(
user,
reservesData,
userConfig,
reserves,
oracle
);
if (vars.totalDebtInETH == 0) {
return true;
}
vars.amountToDecreaseInETH = (IPriceOracleGetter(oracle).getAssetPrice(asset) * amount) / (10**vars.decimals);
vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH - vars.amountToDecreaseInETH;
//if there is a borrow, there can't be 0 collateral
if (vars.collateralBalanceAfterDecrease == 0) {
return false;
}
vars.liquidationThresholdAfterDecrease =
((vars.totalCollateralInETH * vars.avgLiquidationThreshold) -
(vars.amountToDecreaseInETH * vars.liquidationThreshold)) /
vars.collateralBalanceAfterDecrease;
uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances(
vars.collateralBalanceAfterDecrease,
vars.totalDebtInETH,
vars.liquidationThresholdAfterDecrease
);
return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
struct CalculateUserAccountDataVars {
uint256 i;
uint256 reserveUnitPrice;
uint256 tokenUnit;
uint256 compoundedLiquidityBalance;
uint256 compoundedBorrowBalance;
uint256 decimals;
uint256 ltv;
uint256 liquidationThreshold;
uint256 healthFactor;
uint256 totalCollateralInETH;
uint256 totalDebtInETH;
uint256 avgLtv;
uint256 avgLiquidationThreshold;
uint256 reservesLength;
bool healthFactorBelowThreshold;
address currentReserveAddress;
bool usageAsCollateralEnabled;
bool userUsesReserveAsCollateral;
}
/**
* @dev Calculates the user data across the reserves.
* this includes the total liquidity/collateral/borrow balances in ETH,
* the average Loan To Value, the average Liquidation Ratio, and the Health factor.
* @param user The address of the user
* @param reservesData Data of all the reserves
* @param userConfig The configuration of the user
* @param reserves The list of the available reserves
* @param oracle The price oracle address
* @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF
**/
function calculateUserAccountData(
address user,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap memory userConfig,
mapping(uint256 => address) storage reserves,
address oracle
)
internal
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
if (userConfig.isEmpty()) {
return (0, 0, 0, 0, ~uint256(0));
}
CalculateUserAccountDataVars memory vars;
for (
uint256 scanData = userConfig.data;
scanData > 0;
(vars.i, scanData) = (vars.i + 1, scanData >> UserConfiguration.SHIFT_STEP)
) {
if (scanData & UserConfiguration.ANY_MASK == 0) {
continue;
}
vars.currentReserveAddress = reserves[vars.i];
DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];
(vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve.configuration.getParams();
vars.tokenUnit = 10**vars.decimals;
vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress);
if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) {
vars.compoundedLiquidityBalance = IDepositToken(currentReserve.depositTokenAddress).collateralBalanceOf(user);
uint256 liquidityBalanceETH = (vars.reserveUnitPrice * vars.compoundedLiquidityBalance) / vars.tokenUnit;
vars.totalCollateralInETH += liquidityBalanceETH;
vars.avgLtv += liquidityBalanceETH * vars.ltv;
vars.avgLiquidationThreshold += liquidityBalanceETH * vars.liquidationThreshold;
}
if (userConfig.isBorrowing(vars.i)) {
vars.compoundedBorrowBalance =
IERC20(currentReserve.stableDebtTokenAddress).balanceOf(user) +
IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user);
vars.totalDebtInETH += (vars.reserveUnitPrice * vars.compoundedBorrowBalance) / vars.tokenUnit;
}
}
if (vars.totalCollateralInETH > 0) {
vars.avgLtv /= vars.totalCollateralInETH;
vars.avgLiquidationThreshold /= vars.totalCollateralInETH;
} else {
(vars.avgLtv, vars.avgLiquidationThreshold) = (0, 0);
}
vars.healthFactor = calculateHealthFactorFromBalances(
vars.totalCollateralInETH,
vars.totalDebtInETH,
vars.avgLiquidationThreshold
);
return (
vars.totalCollateralInETH,
vars.totalDebtInETH,
vars.avgLtv,
vars.avgLiquidationThreshold,
vars.healthFactor
);
}
/**
* @dev Calculates the health factor from the corresponding balances
* @param totalCollateralInETH The total collateral in ETH
* @param totalDebtInETH The total debt in ETH
* @param liquidationThreshold The avg liquidation threshold
* @return The health factor calculated from the balances provided
**/
function calculateHealthFactorFromBalances(
uint256 totalCollateralInETH,
uint256 totalDebtInETH,
uint256 liquidationThreshold
) internal pure returns (uint256) {
if (totalDebtInETH == 0) return ~uint256(0);
return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH);
}
/**
* @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the
* average Loan To Value
* @param totalCollateralInETH The total collateral in ETH
* @param totalDebtInETH The total borrow balance
* @param ltv The average loan to value
* @return the amount available to borrow in ETH for the user
**/
function calculateAvailableBorrowsETH(
uint256 totalCollateralInETH,
uint256 totalDebtInETH,
uint256 ltv
) internal pure returns (uint256) {
uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv);
if (availableBorrowsETH < totalDebtInETH) {
return 0;
}
availableBorrowsETH = availableBorrowsETH - totalDebtInETH;
return availableBorrowsETH;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import './ReserveLogic.sol';
import './GenericLogic.sol';
import '../../../tools/math/WadRayMath.sol';
import '../../../tools/math/PercentageMath.sol';
import '../../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import '../configuration/ReserveConfiguration.sol';
import '../configuration/UserConfiguration.sol';
import '../../../tools/Errors.sol';
import '../helpers/Helpers.sol';
import '../../../interfaces/IReserveRateStrategy.sol';
import '../types/DataTypes.sol';
/**
* @title ReserveLogic library
* @author Aave
* @notice Implements functions to validate the different actions of the protocol
*/
library ValidationLogic {
using ReserveLogic for DataTypes.ReserveData;
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20 for IERC20;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000;
uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95%
/**
* @dev Validates a deposit action
* @param reserve The reserve object on which the user is depositing
* @param amount The amount to be deposited
*/
function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) internal view {
(bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags();
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!isFrozen, Errors.VL_RESERVE_FROZEN);
}
/**
* @dev Validates a withdraw action
* @param reserveAddress The address of the reserve
* @param amount The amount to be withdrawn
* @param userBalance The balance of the user
* @param reservesData The reserves state
* @param userConfig The user configuration
* @param reserves The addresses of the reserves
* @param oracle The price oracle
*/
function validateWithdraw(
address reserveAddress,
uint256 amount,
uint256 userBalance,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
address oracle
) internal view {
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE);
(bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(
GenericLogic.balanceDecreaseAllowed(
reserveAddress,
msg.sender,
amount,
reservesData,
userConfig,
reserves,
oracle
),
Errors.VL_TRANSFER_NOT_ALLOWED
);
}
struct ValidateBorrowLocalVars {
uint256 currentLtv;
uint256 currentLiquidationThreshold;
uint256 amountOfCollateralNeededETH;
uint256 userCollateralBalanceETH;
uint256 userBorrowBalanceETH;
uint256 availableLiquidity;
uint256 healthFactor;
bool isActive;
bool isFrozen;
bool borrowingEnabled;
bool stableRateBorrowingEnabled;
}
/**
* @dev Validates a borrow action
* @param asset The address of the asset to borrow
* @param reserve The reserve state from which the user is borrowing
* @param userAddress The address of the user
* @param amount The amount to be borrowed
* @param amountInETH The amount to be borrowed, in ETH
* @param interestRateMode The interest rate mode at which the user is borrowing
* @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage
* @param reservesData The state of all the reserves
* @param userConfig The state of the user for the specific reserve
* @param reserves The addresses of all the active reserves
* @param oracle The price oracle
*/
function validateBorrow(
address asset,
DataTypes.ReserveData storage reserve,
address userAddress,
uint256 amount,
uint256 amountInETH,
uint256 interestRateMode,
uint256 maxStableLoanPercent,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
address oracle
) internal view {
ValidateBorrowLocalVars memory vars;
(vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve
.configuration
.getFlags();
require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN);
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED);
//validate interest rate mode
require(
uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode ||
uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode,
Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED
);
(
vars.userCollateralBalanceETH,
vars.userBorrowBalanceETH,
vars.currentLtv,
vars.currentLiquidationThreshold,
vars.healthFactor
) = GenericLogic.calculateUserAccountData(userAddress, reservesData, userConfig, reserves, oracle);
require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0);
require(
vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,
Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD
);
//add the current already borrowed amount to the amount requested to calculate the total collateral needed.
vars.amountOfCollateralNeededETH = (vars.userBorrowBalanceETH + amountInETH).percentDiv(vars.currentLtv); //LTV is calculated in percentage
require(
vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH,
Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW
);
/**
* Following conditions need to be met if the user is borrowing at a stable rate:
* 1. Reserve must be enabled for stable rate borrowing
* 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency
* they are borrowing, to prevent abuses.
* 3. Users will be able to borrow only a portion of the total available liquidity
**/
if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) {
//check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve
require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED);
require(
!userConfig.isUsingAsCollateral(reserve.id) ||
reserve.configuration.getLtv() == 0 ||
amount > IDepositToken(reserve.depositTokenAddress).collateralBalanceOf(userAddress),
Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY
);
vars.availableLiquidity = IERC20(asset).balanceOf(reserve.depositTokenAddress);
//calculate the max available loan size in stable rate mode as a percentage of the
//available liquidity
uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent);
require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE);
}
}
/**
* @dev Validates a repay action
* @param reserve The reserve state from which the user is repaying
* @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)
* @param onBehalfOf The address of the user msg.sender is repaying for
* @param stableDebt The borrow balance of the user
* @param variableDebt The borrow balance of the user
*/
function validateRepay(
DataTypes.ReserveData storage reserve,
uint256 amountSent,
DataTypes.InterestRateMode rateMode,
address onBehalfOf,
uint256 stableDebt,
uint256 variableDebt
) internal view {
bool isActive = reserve.configuration.getActive();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(amountSent > 0, Errors.VL_INVALID_AMOUNT);
require(
(stableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE) ||
(variableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE),
Errors.VL_NO_DEBT_OF_SELECTED_TYPE
);
require(amountSent != ~uint256(0) || msg.sender == onBehalfOf, Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF);
}
/**
* @dev Validates a swap of borrow rate mode.
* @param reserve The reserve state on which the user is swapping the rate
* @param userConfig The user reserves configuration
* @param stableDebt The stable debt of the user
* @param variableDebt The variable debt of the user
* @param currentRateMode The rate mode of the borrow
*/
function validateSwapRateMode(
DataTypes.ReserveData storage reserve,
DataTypes.UserConfigurationMap storage userConfig,
uint256 stableDebt,
uint256 variableDebt,
DataTypes.InterestRateMode currentRateMode
) internal view {
(bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!isFrozen, Errors.VL_RESERVE_FROZEN);
if (currentRateMode == DataTypes.InterestRateMode.STABLE) {
require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE);
} else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) {
require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE);
/**
* user wants to swap to stable, before swapping we need to ensure that
* 1. stable borrow rate is enabled on the reserve
* 2. user is not trying to abuse the reserve by depositing
* more collateral than he is borrowing, artificially lowering
* the interest rate, borrowing at variable, and switching to stable
**/
require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED);
require(
!userConfig.isUsingAsCollateral(reserve.id) ||
reserve.configuration.getLtv() == 0 ||
(stableDebt + variableDebt) > IDepositToken(reserve.depositTokenAddress).collateralBalanceOf(msg.sender),
Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY
);
} else {
revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED);
}
}
/**
* @dev Validates a stable borrow rate rebalance action
* @param reserve The reserve state on which the user is getting rebalanced
* @param reserveAddress The address of the reserve
* @param stableDebtToken The stable debt token instance
* @param depositTokenAddress The address of the depositToken contract
*/
function validateRebalanceStableBorrowRate(
DataTypes.ReserveData storage reserve,
address reserveAddress,
IERC20 stableDebtToken,
address depositTokenAddress
) internal view {
(bool isActive, , , ) = reserve.configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
uint256 usageRatio = stableDebtToken.totalSupply() + IERC20(reserve.variableDebtTokenAddress).totalSupply(); /* totalDebt */
if (usageRatio != 0) {
uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(depositTokenAddress);
usageRatio = usageRatio.wadToRay().wadDiv(
availableLiquidity +
/* totalDebt */
usageRatio
);
}
//if the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage,
//then we allow rebalancing of the stable rate positions.
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 maxVariableBorrowRate = IReserveRateStrategy(reserve.strategy).getMaxVariableBorrowRate();
require(
usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD &&
currentLiquidityRate <= maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD),
Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET
);
}
/**
* @dev Validates the action of setting an asset as collateral
* @param reserve The state of the reserve that the user is enabling or disabling as collateral
* @param reserveAddress The address of the reserve
* @param reservesData The data of all the reserves
* @param userConfig The state of the user for the specific reserve
* @param reserves The addresses of all the active reserves
* @param oracle The price oracle
*/
function validateSetUseReserveAsCollateral(
DataTypes.ReserveData storage reserve,
address reserveAddress,
bool useAsCollateral,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
address oracle
) internal view {
uint256 underlyingBalance = IDepositToken(reserve.depositTokenAddress).collateralBalanceOf(msg.sender);
require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0);
if (!useAsCollateral) {
require(!reserve.configuration.isExternalStrategy(), Errors.VL_RESERVE_MUST_BE_COLLATERAL);
require(
GenericLogic.balanceDecreaseAllowed(
reserveAddress,
msg.sender,
underlyingBalance,
reservesData,
userConfig,
reserves,
oracle
),
Errors.VL_DEPOSIT_ALREADY_IN_USE
);
} else {
require(reserve.configuration.getLtv() > 0, Errors.VL_RESERVE_MUST_BE_COLLATERAL);
}
}
/**
* @dev Validates a flashloan action
* @param assets The assets being flashborrowed
* @param amounts The amounts for each asset being borrowed
**/
function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure {
require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS);
}
/**
* @dev Validates the liquidation action
* @param collateralReserve The reserve data of the collateral
* @param principalReserve The reserve data of the principal
* @param userConfig The user configuration
* @param userHealthFactor The user's health factor
* @param userStableDebt Total stable debt balance of the user
* @param userVariableDebt Total variable debt balance of the user
**/
function validateLiquidationCall(
DataTypes.ReserveData storage collateralReserve,
DataTypes.ReserveData storage principalReserve,
DataTypes.UserConfigurationMap storage userConfig,
uint256 userHealthFactor,
uint256 userStableDebt,
uint256 userVariableDebt
) internal view {
require(
collateralReserve.configuration.getActive() && principalReserve.configuration.getActive(),
Errors.VL_NO_ACTIVE_RESERVE
);
require(
userHealthFactor < GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,
Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD
);
//if collateral isn't enabled as collateral by user, it cannot be liquidated
require(
collateralReserve.configuration.getLiquidationThreshold() > 0 &&
userConfig.isUsingAsCollateral(collateralReserve.id),
Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED
);
require(userStableDebt != 0 || userVariableDebt != 0, Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER);
}
/**
* @dev Validates an depositToken transfer
* @param from The user from which the depositTokens are being transferred
* @param reservesData The state of all the reserves
* @param userConfig The state of the user for the specific reserve
* @param reserves The addresses of all the active reserves
* @param oracle The price oracle
*/
function validateTransfer(
address asset,
address from,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
address oracle
) internal view {
if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) {
return;
}
(, , , , uint256 healthFactor) = GenericLogic.calculateUserAccountData(
from,
reservesData,
userConfig,
reserves,
oracle
);
require(healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_TRANSFER_NOT_ALLOWED);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import '../../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import '../../../interfaces/IDepositToken.sol';
import '../../../interfaces/IStableDebtToken.sol';
import '../../../interfaces/IVariableDebtToken.sol';
import '../../../interfaces/IReserveRateStrategy.sol';
import '../../../interfaces/IReserveDelegatedStrategy.sol';
import '../configuration/ReserveConfiguration.sol';
import '../../../tools/math/InterestMath.sol';
import '../../../tools/math/WadRayMath.sol';
import '../../../tools/math/PercentageMath.sol';
import '../../../tools/Errors.sol';
import '../types/DataTypes.sol';
/**
* @title ReserveLogic library
* @notice Implements the logic to update the reserves state
*/
library ReserveLogic {
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant externalPastLimit = 10 minutes;
/**
* @dev Emitted when the state of a reserve is updated
* @param asset The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed asset,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
using ReserveLogic for DataTypes.ReserveData;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
/**
* @dev Returns the ongoing normalized income for the reserve
* A value of 1e27 means there is no income. As time passes, the income is accrued
* A value of 2*1e27 means for each unit of asset one unit of income has been accrued
* @param reserve The reserve object
* @return the normalized income. expressed in ray
**/
function getNormalizedIncome(DataTypes.ReserveData storage reserve, address asset) internal view returns (uint256) {
uint40 timestamp = reserve.lastUpdateTimestamp;
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.liquidityIndex;
}
if (reserve.configuration.isExternalStrategy()) {
return IReserveDelegatedStrategy(reserve.strategy).getDelegatedDepositIndex(asset);
}
return InterestMath.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(reserve.liquidityIndex);
}
/**
* @dev Returns the ongoing normalized variable debt for the reserve
* A value of 1e27 means there is no debt. As time passes, the income is accrued
* A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated
* @param reserve The reserve object
* @return The normalized variable debt. expressed in ray
**/
function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) {
uint40 timestamp = reserve.lastUpdateTimestamp;
if (timestamp == uint40(block.timestamp) || reserve.configuration.isExternalStrategy()) {
//if the index was updated in the same block or is external, no need to perform any calculation
return reserve.variableBorrowIndex;
}
uint256 cumulated = InterestMath.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(
reserve.variableBorrowIndex
);
return cumulated;
}
/**
* @dev Updates the liquidity cumulative index and the variable borrow index.
* @param reserve the reserve object
**/
function updateStateForDeposit(DataTypes.ReserveData storage reserve, address asset) internal returns (uint256) {
if (reserve.configuration.isExternalStrategy()) {
return _updateExternalIndexes(reserve, asset);
}
return _updateState(reserve);
}
/**
* @dev Updates the liquidity cumulative index and the variable borrow index.
* @param reserve the reserve object
**/
function updateState(DataTypes.ReserveData storage reserve, address asset) internal {
if (reserve.configuration.isExternalStrategy()) {
if (reserve.lastUpdateTimestamp < uint40(block.timestamp)) {
_updateExternalIndexes(reserve, asset);
}
} else {
_updateState(reserve);
}
}
/**
* @dev Updates the liquidity cumulative index and the variable borrow index.
* @param reserve the reserve object
**/
function _updateState(DataTypes.ReserveData storage reserve) private returns (uint256) {
uint256 scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply();
uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;
uint256 previousLiquidityIndex = reserve.liquidityIndex;
uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;
(uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes(
reserve,
scaledVariableDebt,
previousLiquidityIndex,
previousVariableBorrowIndex,
lastUpdatedTimestamp
);
_mintToTreasury(
reserve,
scaledVariableDebt,
previousVariableBorrowIndex,
newLiquidityIndex,
newVariableBorrowIndex,
lastUpdatedTimestamp
);
return newLiquidityIndex;
}
/**
* @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate
* the flashloan fee to the reserve, and spread it between all the depositors
* @param reserve The reserve object
* @param totalLiquidity The total liquidity available in the reserve
* @param amount The amount to accomulate
**/
function cumulateToLiquidityIndex(
DataTypes.ReserveData storage reserve,
uint256 totalLiquidity,
uint256 amount
) internal {
uint256 result = WadRayMath.RAY + amount.wadToRay().wadDiv(totalLiquidity);
result = result.rayMul(reserve.liquidityIndex);
require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);
reserve.liquidityIndex = uint128(result);
}
/**
* @dev Initializes a reserve
**/
function init(DataTypes.ReserveData storage reserve, DataTypes.InitReserveData calldata data) internal {
require(reserve.depositTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);
reserve.liquidityIndex = uint128(WadRayMath.RAY);
reserve.variableBorrowIndex = uint128(WadRayMath.RAY);
reserve.depositTokenAddress = data.depositTokenAddress;
reserve.stableDebtTokenAddress = data.stableDebtAddress;
reserve.variableDebtTokenAddress = data.variableDebtAddress;
reserve.strategy = data.strategy;
{
DataTypes.ReserveConfigurationMap memory cfg = reserve.configuration;
cfg.setExternalStrategy(data.externalStrategy);
reserve.configuration = cfg;
}
}
struct UpdateInterestRatesLocalVars {
uint256 availableLiquidity;
uint256 totalStableDebt;
uint256 newLiquidityRate;
uint256 newStableRate;
uint256 newVariableRate;
uint256 avgStableRate;
uint256 totalVariableDebt;
}
/**
* @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate
* @param reserve The address of the reserve to be updated
* @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay)
* @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)
**/
function updateInterestRates(
DataTypes.ReserveData storage reserve,
address reserveAddress,
address depositToken,
uint256 liquidityAdded,
uint256 liquidityTaken
) internal {
if (!reserve.configuration.isExternalStrategy()) {
_updateInterestRates(reserve, reserveAddress, depositToken, liquidityAdded, liquidityTaken);
}
// // There is no need to be exactly at external's asset rate when we don't send or receive funds
// else if (reserve.lastUpdateTimestamp < uint40(block.timestamp) || liquidityAdded != 0 || liquidityTaken != 0) {
// _updateExternalRates(reserve, reserveAddress);
// }
}
function _updateInterestRates(
DataTypes.ReserveData storage reserve,
address reserveAddress,
address depositToken,
uint256 liquidityAdded,
uint256 liquidityTaken
) private {
UpdateInterestRatesLocalVars memory vars;
(vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(reserve.stableDebtTokenAddress)
.getTotalSupplyAndAvgRate();
//calculates the total variable debt locally using the scaled total supply instead
//of totalSupply(), as it's noticeably cheaper. Also, the index has been
//updated by the previous updateState() call
vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply().rayMul(
reserve.variableBorrowIndex
);
(vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate) = IReserveRateStrategy(reserve.strategy)
.calculateInterestRates(
reserveAddress,
depositToken,
liquidityAdded,
liquidityTaken,
vars.totalStableDebt,
vars.totalVariableDebt,
vars.avgStableRate,
reserve.configuration.getReserveFactor()
);
require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW);
require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW);
require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW);
reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);
reserve.currentStableBorrowRate = uint128(vars.newStableRate);
reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);
emit ReserveDataUpdated(
reserveAddress,
vars.newLiquidityRate,
vars.newStableRate,
vars.newVariableRate,
reserve.liquidityIndex,
reserve.variableBorrowIndex
);
}
struct MintToTreasuryLocalVars {
uint256 currentStableDebt;
uint256 principalStableDebt;
uint256 previousStableDebt;
uint256 currentVariableDebt;
uint256 previousVariableDebt;
uint256 avgStableRate;
uint256 cumulatedStableInterest;
uint256 totalDebtAccrued;
uint256 amountToMint;
uint256 reserveFactor;
uint40 stableSupplyUpdatedTimestamp;
}
/**
* @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the
* specific asset.
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The current scaled total variable debt
* @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest
* @param newLiquidityIndex The new liquidity index
* @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest
**/
function _mintToTreasury(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 previousVariableBorrowIndex,
uint256 newLiquidityIndex,
uint256 newVariableBorrowIndex,
uint40 timestamp
) private {
MintToTreasuryLocalVars memory vars;
vars.reserveFactor = reserve.configuration.getReserveFactor();
if (vars.reserveFactor == 0) {
return;
}
//fetching the principal, total stable debt and the avg stable rate
(
vars.principalStableDebt,
vars.currentStableDebt,
vars.avgStableRate,
vars.stableSupplyUpdatedTimestamp
) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData();
//calculate the last principal variable debt
vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex);
//calculate the new total supply after accumulation of the index
vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex);
//calculate the stable debt until the last timestamp update
vars.cumulatedStableInterest = InterestMath.calculateCompoundedInterest(
vars.avgStableRate,
vars.stableSupplyUpdatedTimestamp,
timestamp
);
vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest);
//debt accrued is the sum of the current debt minus the sum of the debt at the last update
vars.totalDebtAccrued =
(vars.currentVariableDebt + vars.currentStableDebt) -
(vars.previousVariableDebt + vars.previousStableDebt);
vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor);
if (vars.amountToMint != 0) {
IDepositToken(reserve.depositTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex);
}
}
/**
* @dev Updates the reserve indexes and the timestamp of the update
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The scaled variable debt
* @param liquidityIndex The last stored liquidity index
* @param variableBorrowIndex The last stored variable borrow index
**/
function _updateIndexes(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 timestamp
) private returns (uint256, uint256) {
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 newLiquidityIndex = liquidityIndex;
uint256 newVariableBorrowIndex = variableBorrowIndex;
//only cumulating if there is any income being produced
if (currentLiquidityRate > 0) {
uint256 cumulatedLiquidityInterest = InterestMath.calculateLinearInterest(currentLiquidityRate, timestamp);
newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex);
require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);
reserve.liquidityIndex = uint128(newLiquidityIndex);
//as the liquidity rate might come only from stable rate loans, we need to ensure
//that there is actual variable debt before accumulating
if (scaledVariableDebt != 0) {
uint256 cumulatedVariableBorrowInterest = InterestMath.calculateCompoundedInterest(
reserve.currentVariableBorrowRate,
timestamp
);
newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex);
require(newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW);
reserve.variableBorrowIndex = uint128(newVariableBorrowIndex);
}
}
reserve.lastUpdateTimestamp = uint40(block.timestamp);
return (newLiquidityIndex, newVariableBorrowIndex);
}
function _updateExternalIndexes(DataTypes.ReserveData storage reserve, address asset) private returns (uint256) {
IReserveDelegatedStrategy.DelegatedState memory state = IReserveDelegatedStrategy(reserve.strategy)
.getDelegatedState(asset, reserve.lastUpdateTimestamp);
require(state.lastUpdateTimestamp <= block.timestamp);
if (state.lastUpdateTimestamp == reserve.lastUpdateTimestamp) {
if (state.liquidityIndex == reserve.liquidityIndex) {
return state.liquidityIndex;
}
} else {
require(state.lastUpdateTimestamp > reserve.lastUpdateTimestamp);
reserve.lastUpdateTimestamp = state.lastUpdateTimestamp;
}
reserve.variableBorrowIndex = state.variableBorrowIndex;
reserve.currentLiquidityRate = state.liquidityRate;
reserve.currentVariableBorrowRate = state.variableBorrowRate;
reserve.currentStableBorrowRate = state.stableBorrowRate;
reserve.liquidityIndex = state.liquidityIndex;
return state.liquidityIndex;
}
// function _updateExternalRates(DataTypes.ReserveData storage reserve, address asset) private {
// // nothing to do - all was updated inside _updateExternalIndexes
// }
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
library DataTypes {
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address depositTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the reserve strategy
address strategy;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
//bit 80: strategy is external
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
struct InitReserveData {
address asset;
address depositTokenAddress;
address stableDebtAddress;
address variableDebtAddress;
address strategy;
bool externalStrategy;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../access/interfaces/IMarketAccessController.sol';
import '../../access/AccessHelper.sol';
import '../../access/AccessFlags.sol';
import '../../interfaces/IEmergencyAccess.sol';
import '../../tools/Errors.sol';
import './LendingPoolStorage.sol';
abstract contract LendingPoolBase is IEmergencyAccess, LendingPoolStorage {
using AccessHelper for IMarketAccessController;
function _whenNotPaused() private view {
require(!_paused, Errors.LP_IS_PAUSED);
}
modifier whenNotPaused() {
_whenNotPaused();
_;
}
function _onlyLendingPoolConfigurator() private view {
_addressesProvider.requireAnyOf(
msg.sender,
AccessFlags.LENDING_POOL_CONFIGURATOR,
Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR
);
}
modifier onlyLendingPoolConfigurator() {
// This trick makes generated code smaller when modifier is applied multiple times.
_onlyLendingPoolConfigurator();
_;
}
function _onlyConfiguratorOrAdmin() private view {
_addressesProvider.requireAnyOf(
msg.sender,
AccessFlags.POOL_ADMIN | AccessFlags.LENDING_POOL_CONFIGURATOR,
Errors.CALLER_NOT_POOL_ADMIN
);
}
modifier onlyConfiguratorOrAdmin() {
_onlyConfiguratorOrAdmin();
_;
}
function _notNestedCall() private view {
require(_nestedCalls == 0, Errors.LP_TOO_MANY_NESTED_CALLS);
}
modifier noReentry() {
_notNestedCall();
_nestedCalls++;
_;
_nestedCalls--;
}
function _noReentryOrFlashloan() private view {
_notNestedCall();
require(_flashloanCalls == 0, Errors.LP_TOO_MANY_FLASHLOAN_CALLS);
}
modifier noReentryOrFlashloan() {
_noReentryOrFlashloan();
_nestedCalls++;
_;
_nestedCalls--;
}
function _noReentryOrFlashloanFeature(uint16 featureFlag) private view {
_notNestedCall();
require(featureFlag & _disabledFeatures == 0 || _flashloanCalls == 0, Errors.LP_TOO_MANY_FLASHLOAN_CALLS);
}
modifier noReentryOrFlashloanFeature(uint16 featureFlag) {
_noReentryOrFlashloanFeature(featureFlag);
_nestedCalls++;
_;
_nestedCalls--;
}
function _onlyEmergencyAdmin() internal view {
_addressesProvider.requireAnyOf(msg.sender, AccessFlags.EMERGENCY_ADMIN, Errors.CALLER_NOT_EMERGENCY_ADMIN);
}
function setPaused(bool val) external override {
_onlyEmergencyAdmin();
_paused = val;
emit EmergencyPaused(msg.sender, val);
}
function isPaused() external view override returns (bool) {
return _paused;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IRemoteAccessBitmask.sol';
import '../../tools/upgradeability/IProxy.sol';
/// @dev Main registry of permissions and addresses
interface IAccessController is IRemoteAccessBitmask {
function getAddress(uint256 id) external view returns (address);
function createProxy(
address admin,
address impl,
bytes calldata params
) external returns (IProxy);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IRemoteAccessBitmask {
/**
* @dev Returns access flags granted to the given address and limited by the filterMask. filterMask == 0 has a special meaning.
* @param addr an to get access perfmissions for
* @param filterMask limits a subset of flags to be checked.
* NB! When filterMask == 0 then zero is returned no flags granted, or an unspecified non-zero value otherwise.
* @return Access flags currently granted
*/
function queryAccessControlMask(address addr, uint256 filterMask) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IProxy {
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
function getScaleIndex() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IDerivedToken.sol';
// solhint-disable func-name-mixedcase
interface IPoolToken is IDerivedToken {
function POOL() external view returns (address);
function updatePool() external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
// solhint-disable func-name-mixedcase
interface IDerivedToken {
/**
* @dev Returns the address of the underlying asset of this token (E.g. WETH for agWETH)
**/
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../access/interfaces/IMarketAccessController.sol';
import '../protocol/libraries/types/DataTypes.sol';
interface ILendingPoolEvents {
/// @dev Emitted on deposit()
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 indexed referral
);
/// @dev Emitted on withdraw()
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/// @dev Emitted on borrow() and flashLoan() when debt needs to be opened
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint256 indexed referral
);
/// @dev Emitted on repay()
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/// @dev Emitted on swapBorrowRateMode()
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/// @dev Emitted on setUserUseReserveAsCollateral()
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/// @dev Emitted on setUserUseReserveAsCollateral()
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/// @dev Emitted on rebalanceStableBorrowRate()
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
/// @dev Emitted on flashLoan()
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint256 referral
);
/// @dev Emitted when a borrower is liquidated.
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveDeposit
);
/// @dev Emitted when the state of a reserve is updated.
event ReserveDataUpdated(
address indexed underlying,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
event LendingPoolExtensionUpdated(address extension);
event DisabledFeaturesUpdated(uint16 disabledFeatures);
event FlashLoanPremiumUpdated(uint16 premium);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IPoolAddressProvider.sol';
interface IFlashLoanAddressProvider is IPoolAddressProvider {}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IPriceOracleProvider.sol';
interface IPoolAddressProvider is IPriceOracleProvider {
function getLendingPool() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IPriceOracleProvider {
function getPriceOracle() external view returns (address);
function getLendingRateOracle() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IBalanceHook {
function handleBalanceUpdate(
address token,
address holder,
uint256 oldBalance,
uint256 newBalance,
uint256 providerSupply
) external;
function handleScaledBalanceUpdate(
address token,
address holder,
uint256 oldBalance,
uint256 newBalance,
uint256 providerSupply,
uint256 scaleRay
) external;
function isScaledBalanceUpdateNeeded() external view returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../../tools/Errors.sol';
import '../types/DataTypes.sol';
/// @dev ReserveConfiguration library, implements the bitmap logic to handle the reserve configuration
library ReserveConfiguration {
uint256 private constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore
uint256 private constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore
uint256 private constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore
uint256 private constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore
uint256 private constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore
uint256 private constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore
uint256 private constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore
uint256 private constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore
uint256 private constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore
uint256 private constant STRATEGY_TYPE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFF; // prettier-ignore
/// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed
uint256 private constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;
uint256 private constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;
uint256 private constant RESERVE_DECIMALS_START_BIT_POSITION = 48;
uint256 private constant RESERVE_FACTOR_START_BIT_POSITION = 64;
uint256 private constant MAX_VALID_LTV = 65535;
uint256 private constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;
uint256 private constant MAX_VALID_LIQUIDATION_BONUS = 65535;
uint256 private constant MAX_VALID_DECIMALS = 255;
uint256 private constant MAX_VALID_RESERVE_FACTOR = 65535;
/// @dev Sets the Loan to Value of the reserve
function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {
require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);
self.data = (self.data & LTV_MASK) | ltv;
}
/// @dev Gets the Loan to Value of the reserve
function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return self.data & ~LTV_MASK;
}
function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure {
require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);
self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);
}
function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;
}
function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure {
require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);
self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);
}
function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;
}
function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure {
require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS);
self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);
}
function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;
}
function getDecimalsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint8) {
return uint8((self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION);
}
function _setFlag(
DataTypes.ReserveConfigurationMap memory self,
uint256 mask,
bool value
) internal pure {
if (value) {
self.data |= ~mask;
} else {
self.data &= mask;
}
}
function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {
_setFlag(self, ACTIVE_MASK, active);
}
function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~ACTIVE_MASK) != 0;
}
function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {
_setFlag(self, FROZEN_MASK, frozen);
}
function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~FROZEN_MASK) != 0;
}
function getFrozenMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {
return (self.data & ~FROZEN_MASK) != 0;
}
function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure {
_setFlag(self, BORROWING_MASK, enabled);
}
function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~BORROWING_MASK) != 0;
}
function setStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure {
_setFlag(self, STABLE_BORROWING_MASK, enabled);
}
function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~STABLE_BORROWING_MASK) != 0;
}
function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure {
require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR);
self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);
}
function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;
}
/// @dev Returns flags: active, frozen, borrowing enabled, stableRateBorrowing enabled
function getFlags(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (
bool,
bool,
bool,
bool
)
{
return _getFlags(self.data);
}
function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self)
internal
pure
returns (
bool active,
bool frozen,
bool borrowEnable,
bool stableBorrowEnable
)
{
return _getFlags(self.data);
}
function _getFlags(uint256 data)
private
pure
returns (
bool,
bool,
bool,
bool
)
{
return (
(data & ~ACTIVE_MASK) != 0,
(data & ~FROZEN_MASK) != 0,
(data & ~BORROWING_MASK) != 0,
(data & ~STABLE_BORROWING_MASK) != 0
);
}
/// @dev Paramters of the reserve: ltv, liquidation threshold, liquidation bonus, the reserve decimals
function getParams(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return _getParams(self.data);
}
/// @dev Paramters of the reserve: ltv, liquidation threshold, liquidation bonus, the reserve decimals
function getParamsMemory(DataTypes.ReserveConfigurationMap memory self)
internal
pure
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return _getParams(self.data);
}
function _getParams(uint256 dataLocal)
private
pure
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return (
dataLocal & ~LTV_MASK,
(dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
(dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
(dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
);
}
function isExternalStrategyMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {
return (self.data & ~STRATEGY_TYPE_MASK) != 0;
}
function isExternalStrategy(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~STRATEGY_TYPE_MASK) != 0;
}
function setExternalStrategy(DataTypes.ReserveConfigurationMap memory self, bool isExternal) internal pure {
_setFlag(self, STRATEGY_TYPE_MASK, isExternal);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../../tools/Errors.sol';
import '../types/DataTypes.sol';
/// @dev Implements the bitmap logic to handle the user configuration
library UserConfiguration {
uint256 private constant ANY_BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555;
uint256 private constant BORROW_BIT_MASK = 1;
uint256 private constant COLLATERAL_BIT_MASK = 2;
uint256 internal constant ANY_MASK = BORROW_BIT_MASK | COLLATERAL_BIT_MASK;
uint256 internal constant SHIFT_STEP = 2;
function setBorrowing(DataTypes.UserConfigurationMap storage self, uint256 reserveIndex) internal {
self.data |= BORROW_BIT_MASK << (reserveIndex << 1);
}
function unsetBorrowing(DataTypes.UserConfigurationMap storage self, uint256 reserveIndex) internal {
self.data &= ~(BORROW_BIT_MASK << (reserveIndex << 1));
}
function setUsingAsCollateral(DataTypes.UserConfigurationMap storage self, uint256 reserveIndex) internal {
self.data |= COLLATERAL_BIT_MASK << (reserveIndex << 1);
}
function unsetUsingAsCollateral(DataTypes.UserConfigurationMap storage self, uint256 reserveIndex) internal {
self.data &= ~(COLLATERAL_BIT_MASK << (reserveIndex << 1));
}
/// @dev Returns true if the user is using the reserve for borrowing
function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) {
return (self.data >> (reserveIndex << 1)) & BORROW_BIT_MASK != 0;
}
/// @dev Returns true if the user is using the reserve as collateral
function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)
internal
pure
returns (bool)
{
return (self.data >> (reserveIndex << 1)) & COLLATERAL_BIT_MASK != 0;
}
/// @dev Returns true if the user is borrowing from any reserve
function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {
return self.data & ANY_BORROWING_MASK != 0;
}
/// @dev Returns true if the user is not using any reserve
function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {
return self.data == 0;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../Errors.sol';
/// @dev Percentages are defined in basis points. The precision is indicated by ONE. Operations are rounded half up.
library PercentageMath {
uint16 public constant BP = 1; // basis point
uint16 public constant PCT = 100 * BP; // basis points per percentage point
uint16 public constant ONE = 100 * PCT; // basis points per 1 (100%)
uint16 public constant HALF_ONE = ONE / 2;
// deprecated
uint256 public constant PERCENTAGE_FACTOR = ONE; //percentage plus two decimals
/**
* @dev Executes a percentage multiplication
* @param value The value of which the percentage needs to be calculated
* @param factor Basis points of the value to be calculated
* @return The percentage of value
**/
function percentMul(uint256 value, uint256 factor) internal pure returns (uint256) {
if (value == 0 || factor == 0) {
return 0;
}
require(value <= (type(uint256).max - HALF_ONE) / factor, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (value * factor + HALF_ONE) / ONE;
}
/**
* @dev Executes a percentage division
* @param value The value of which the percentage needs to be calculated
* @param factor Basis points of the value to be calculated
* @return The value divided the percentage
**/
function percentDiv(uint256 value, uint256 factor) internal pure returns (uint256) {
require(factor != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfFactor = factor >> 1;
require(value <= (type(uint256).max - halfFactor) / ONE, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (value * ONE + halfFactor) / factor;
}
function percentOf(uint256 value, uint256 base) internal pure returns (uint256) {
require(base != 0, Errors.MATH_DIVISION_BY_ZERO);
if (value == 0) {
return 0;
}
require(value <= (type(uint256).max - HALF_ONE) / ONE, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (value * ONE + (base >> 1)) / base;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
enum SourceType {
AggregatorOrStatic,
UniswapV2Pair
}
interface IPriceOracleEvents {
event AssetPriceUpdated(address asset, uint256 price, uint256 timestamp);
event EthPriceUpdated(uint256 price, uint256 timestamp);
event DerivedAssetSourceUpdated(
address indexed asset,
uint256 index,
address indexed underlyingSource,
uint256 underlyingPrice,
uint256 timestamp,
SourceType sourceType
);
}
/// @dev Interface for a price oracle.
interface IPriceOracleGetter is IPriceOracleEvents {
/// @dev returns the asset price in ETH
function getAssetPrice(address asset) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IReserveStrategy.sol';
/// @dev Strategy to control a lending pool reserve
interface IReserveRateStrategy is IReserveStrategy {
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
address reserve,
address depositToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
returns (
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate
);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './IReserveStrategy.sol';
import './IUnderlyingStrategy.sol';
/// @dev Interface to access the interest rate of an external asset
interface IReserveDelegatedStrategy is IReserveStrategy, IUnderlyingStrategy {
/// @dev all indexes and rates are expressed in ray
struct DelegatedState {
uint128 liquidityIndex;
uint128 variableBorrowIndex;
uint128 liquidityRate;
uint128 variableBorrowRate;
uint128 stableBorrowRate;
uint40 lastUpdateTimestamp;
}
function getDelegatedState(address underlyingToken, uint40 lastUpdateTimestamp)
external
returns (DelegatedState memory);
function getDelegatedDepositIndex(address underlyingToken) external view returns (uint256 liquidityIndex);
function getStrategyName() external view returns (string memory);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import './WadRayMath.sol';
library InterestMath {
using WadRayMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant SECONDS_PER_YEAR = 365 days;
uint256 internal constant MILLIS_PER_YEAR = SECONDS_PER_YEAR * 1000;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The annual interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) {
return WadRayMath.RAY + (rate * (block.timestamp - lastUpdateTimestamp)) / SECONDS_PER_YEAR;
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
uint256 exp = currentTimestamp - lastUpdateTimestamp;
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = (exp * expMinusOne * basePowerTwo) / 2;
uint256 thirdTerm = (exp * expMinusOne * expMinusTwo * basePowerThree) / 6;
return WadRayMath.RAY + exp * ratePerSecond + secondTerm + thirdTerm;
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) {
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IReserveStrategy {
function isDelegatedReserve() external view returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IUnderlyingStrategy {
function getUnderlying(address asset) external view returns (address);
function delegatedWithdrawUnderlying(
address asset,
uint256 amount,
address to
) external returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
library AccessFlags {
// roles that can be assigned to multiple addresses - use range [0..15]
uint256 public constant EMERGENCY_ADMIN = 1 << 0;
uint256 public constant POOL_ADMIN = 1 << 1;
uint256 public constant TREASURY_ADMIN = 1 << 2;
uint256 public constant REWARD_CONFIG_ADMIN = 1 << 3;
uint256 public constant REWARD_RATE_ADMIN = 1 << 4;
uint256 public constant STAKE_ADMIN = 1 << 5;
uint256 public constant REFERRAL_ADMIN = 1 << 6;
uint256 public constant LENDING_RATE_ADMIN = 1 << 7;
uint256 public constant SWEEP_ADMIN = 1 << 8;
uint256 public constant ORACLE_ADMIN = 1 << 9;
uint256 public constant ROLES = (uint256(1) << 16) - 1;
// singletons - use range [16..64] - can ONLY be assigned to a single address
uint256 public constant SINGLETONS = ((uint256(1) << 64) - 1) & ~ROLES;
// proxied singletons
uint256 public constant LENDING_POOL = 1 << 16;
uint256 public constant LENDING_POOL_CONFIGURATOR = 1 << 17;
uint256 public constant LIQUIDITY_CONTROLLER = 1 << 18;
uint256 public constant TREASURY = 1 << 19;
uint256 public constant REWARD_TOKEN = 1 << 20;
uint256 public constant REWARD_STAKE_TOKEN = 1 << 21;
uint256 public constant REWARD_CONTROLLER = 1 << 22;
uint256 public constant REWARD_CONFIGURATOR = 1 << 23;
uint256 public constant STAKE_CONFIGURATOR = 1 << 24;
uint256 public constant REFERRAL_REGISTRY = 1 << 25;
uint256 public constant PROXIES = ((uint256(1) << 26) - 1) & ~ROLES;
// non-proxied singletons, numbered down from 31 (as JS has problems with bitmasks over 31 bits)
uint256 public constant WETH_GATEWAY = 1 << 27;
uint256 public constant DATA_HELPER = 1 << 28;
uint256 public constant PRICE_ORACLE = 1 << 29;
uint256 public constant LENDING_RATE_ORACLE = 1 << 30;
// any other roles - use range [64..]
// these roles can be assigned to multiple addresses
uint256 public constant TRUSTED_FLASHLOAN = 1 << 66;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
interface IEmergencyAccess {
function setPaused(bool paused) external;
function isPaused() external view returns (bool);
event EmergencyPaused(address indexed by, bool paused);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
import '../../tools/upgradeability/VersionedInitializable.sol';
import '../../access/interfaces/IMarketAccessController.sol';
import '../libraries/types/DataTypes.sol';
abstract contract LendingPoolStorage is VersionedInitializable {
IMarketAccessController internal _addressesProvider;
address internal _extension;
mapping(address => DataTypes.ReserveData) internal _reserves;
mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig;
// the list of the available reserves, structured as a mapping for gas savings reasons
mapping(uint256 => address) internal _reservesList;
uint16 internal _maxStableRateBorrowSizePct;
uint16 internal _flashLoanPremiumPct;
uint16 internal constant FEATURE_LIQUIDATION = 1 << 0;
uint16 internal constant FEATURE_FLASHLOAN = 1 << 1;
uint16 internal constant FEATURE_FLASHLOAN_DEPOSIT = 1 << 2;
uint16 internal constant FEATURE_FLASHLOAN_WITHDRAW = 1 << 3;
uint16 internal constant FEATURE_FLASHLOAN_BORROW = 1 << 4;
uint16 internal constant FEATURE_FLASHLOAN_REPAY = 1 << 5;
uint16 internal _disabledFeatures;
uint8 internal _reservesCount;
uint8 internal constant _maxNumberOfReserves = 128;
uint8 internal _flashloanCalls;
uint8 internal _nestedCalls;
bool internal _paused;
mapping(address => address[]) internal _indirectUnderlying;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.4;
/**
* @title VersionedInitializable
*
* @dev Helper contract to implement versioned initializer functions. To use it, replace
* the constructor with a function that has the `initializer` or `initializerRunAlways` modifier.
* The revision number should be defined as a private constant, returned by getRevision() and used by initializer() modifier.
*
* ATTN: There is a built-in protection from implementation self-destruct exploits. This protection
* prevents initializers from being called on an implementation inself, but only on proxied contracts.
* To override this protection, call _unsafeResetVersionedInitializers() from a constructor.
*
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an initializable contract, as well
* as extending an initializable contract via inheritance.
*
* ATTN: When used with inheritance, parent initializers with `initializer` modifier are prevented by calling twice,
* but can only be called in child-to-parent sequence.
*
* WARNING: When used with inheritance, parent initializers with `initializerRunAlways` modifier
* are NOT protected from multiple calls by another initializer.
*/
abstract contract VersionedInitializable {
uint256 private constant BLOCK_REVISION = type(uint256).max;
// This revision number is applied to implementations
uint256 private constant IMPL_REVISION = BLOCK_REVISION - 1;
/// @dev Indicates that the contract has been initialized. The default value blocks initializers from being called on an implementation.
uint256 private lastInitializedRevision = IMPL_REVISION;
/// @dev Indicates that the contract is in the process of being initialized.
uint256 private lastInitializingRevision = 0;
/**
* @dev There is a built-in protection from self-destruct of implementation exploits. This protection
* prevents initializers from being called on an implementation inself, but only on proxied contracts.
* Function _unsafeResetVersionedInitializers() can be called from a constructor to disable this protection.
* It must be called before any initializers, otherwise it will fail.
*/
function _unsafeResetVersionedInitializers() internal {
require(isConstructor(), 'only for constructor');
if (lastInitializedRevision == IMPL_REVISION) {
lastInitializedRevision = 0;
} else {
require(lastInitializedRevision == 0, 'can only be called before initializer(s)');
}
}
/// @dev Modifier to use in the initializer function of a contract.
modifier initializer(uint256 localRevision) {
(uint256 topRevision, bool initializing, bool skip) = _preInitializer(localRevision);
if (!skip) {
lastInitializingRevision = localRevision;
_;
lastInitializedRevision = localRevision;
}
if (!initializing) {
lastInitializedRevision = topRevision;
lastInitializingRevision = 0;
}
}
modifier initializerRunAlways(uint256 localRevision) {
(uint256 topRevision, bool initializing, bool skip) = _preInitializer(localRevision);
if (!skip) {
lastInitializingRevision = localRevision;
}
_;
if (!skip) {
lastInitializedRevision = localRevision;
}
if (!initializing) {
lastInitializedRevision = topRevision;
lastInitializingRevision = 0;
}
}
function _preInitializer(uint256 localRevision)
private
returns (
uint256 topRevision,
bool initializing,
bool skip
)
{
topRevision = getRevision();
require(topRevision < IMPL_REVISION, 'invalid contract revision');
require(localRevision > 0, 'incorrect initializer revision');
require(localRevision <= topRevision, 'inconsistent contract revision');
if (lastInitializedRevision < IMPL_REVISION) {
// normal initialization
initializing = lastInitializingRevision > 0 && lastInitializedRevision < topRevision;
require(initializing || isConstructor() || topRevision > lastInitializedRevision, 'already initialized');
} else {
// by default, initialization of implementation is only allowed inside a constructor
require(lastInitializedRevision == IMPL_REVISION && isConstructor(), 'initializer blocked');
// enable normal use of initializers inside a constructor
lastInitializedRevision = 0;
// but make sure to block initializers afterwards
topRevision = BLOCK_REVISION;
initializing = lastInitializingRevision > 0;
}
if (initializing) {
require(lastInitializingRevision > localRevision, 'incorrect order of initializers');
}
if (localRevision <= lastInitializedRevision) {
// prevent calling of parent's initializer when it was called before
if (initializing) {
// Can't set zero yet, as it is not a top-level call, otherwise `initializing` will become false.
// Further calls will fail with the `incorrect order` assertion above.
lastInitializingRevision = 1;
}
return (topRevision, initializing, true);
}
return (topRevision, initializing, false);
}
function isRevisionInitialized(uint256 localRevision) internal view returns (bool) {
return lastInitializedRevision >= localRevision;
}
// solhint-disable-next-line func-name-mixedcase
function REVISION() public pure returns (uint256) {
return getRevision();
}
/**
* @dev returns the revision number (< type(uint256).max - 1) of the contract.
* The number should be defined as a private constant.
**/
function getRevision() internal pure virtual returns (uint256);
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly {
cs := extcodesize(address())
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[4] private ______gap;
}
| Returns the address of the LendingPoolExtension | function getLendingPoolExtension() external view returns (address) {
return _extension;
}
| 5,799,912 |
./full_match/80001/0xf0463Bbede56c6102022E73B9ca298478C4552c3/sources/Vote.sol | Make a new suggestion if you are the member of the DAO | function suggest(string memory _newSuggestion) external isAMember {
_id++;
}
| 5,555,919 |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => uint256) authorizedContracts;
mapping(string => Insurance[]) insurances;
mapping(address => mapping(string => bool)) insurancesByCustomer;
mapping(address => uint256) credit;
address[] private multiCalls = new address[](0);
mapping(address => Airline) airlines;
int256 nAirlines;
struct Airline {
int256 mark;
bool funded;
string name;
address[] confirmations;
bool registered;
}
struct Insurance {
address airline;
uint256 value;
bool paidOut;
address customer;
}
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
address airline,
string name
)
public
{
contractOwner = msg.sender;
airlines[airline] = Airline(1, false, name, new address[](0), true);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier isCallerAuthorized()
{
require(authorizedContracts[msg.sender] == 1, "Caller is not authorized");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function authorizeContract(address c) external requireContractOwner {
authorizedContracts[c] = 1;
}
function deauthorizeContract(address c) external requireContractOwner {
delete authorizedContracts[c];
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
function getAirline(address a) public view returns(int256, bool, string, address[], bool) {
return (airlines[a].mark, airlines[a].registered, airlines[a].name, airlines[a].confirmations, airlines[a].funded);
}
function getNumberOfAirlines() public view returns (int256) {
return nAirlines;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
isCallerAuthorized
{
require(mode != operational, "new mode must be different from existing mode");
require(airlines[tx.origin].funded, "caller must be registered and funded airline");
bool isDuplicate = false;
for (uint c = 0; c < multiCalls.length; c++) {
if (multiCalls[c] == tx.origin) {
isDuplicate = true;
break;
}
}
require(!isDuplicate, "caller has already called this function");
multiCalls.push(tx.origin);
if (multiCalls.length > uint256(nAirlines / 2)) {
operational = mode;
multiCalls = new address[](0);
}
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address a,
string name
)
external
isCallerAuthorized
requireIsOperational
returns(bool success, uint256 votes)
{
if (nAirlines < 4) {
require(airlines[tx.origin].funded, "Only registered airlines can register other airlines");
require(airlines[a].mark == 0, "Airline has already been registered");
airlines[a] = Airline(1, false, name, new address[](0), true);
return (true, 0);
} else {
if (airlines[a].mark == 0) {
airlines[a] = Airline(1, false, name, new address[](0), false);
}
if (airlines[tx.origin].funded) {
bool isDuplicate = false;
for (uint c = 0; c < airlines[a].confirmations.length; c++) {
if (airlines[a].confirmations[c] == tx.origin) {
isDuplicate = true;
break;
}
}
require(!isDuplicate, "confirm register has already been called by this airline");
airlines[a].confirmations.push(tx.origin);
if (airlines[a].confirmations.length >= uint256(nAirlines / 2)) {
airlines[a].registered = true;
}
return (true, airlines[a].confirmations.length);
}
return (true, 0);
}
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
string flight,
address airline
)
external
payable
isCallerAuthorized
requireIsOperational
{
require(msg.value <= 1 ether, "Payment must be lower than 1 ether");
require(airlines[airline].funded, "Airline is not funded");
require(!insurancesByCustomer[tx.origin][flight], "Customer already purchased this insurance");
insurances[flight].push(Insurance(airline, msg.value, false, tx.origin));
insurancesByCustomer[tx.origin][flight] = true;
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
string flight
)
external
isCallerAuthorized
requireIsOperational
{
for (uint c = 0; c < insurances[flight].length; c++) {
if (!insurances[flight][c].paidOut) {
insurances[flight][c].paidOut = true;
uint256 aux = credit[insurances[flight][c].customer];
uint256 add = uint256(aux / 2);
credit[insurances[flight][c].customer] += add;
}
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
)
external
requireIsOperational
{
require(credit[tx.origin] > 0, "No funds to transfer");
uint256 cred = credit[tx.origin];
credit[tx.origin] = 0;
tx.origin.transfer(cred);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
)
public
payable
isCallerAuthorized
requireIsOperational
{
require(airlines[tx.origin].mark == 1, "Airline must be registered");
require(airlines[tx.origin].registered, "Airline registration must be confirmed");
require(msg.value == 10 ether, "Funding value must be 10 ether");
require(!airlines[tx.origin].funded, "Airline is already funded");
airlines[tx.origin].funded = true;
nAirlines = nAirlines + 1;
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
| Transfers eligible payout funds to insuree/ | function pay
(
)
external
requireIsOperational
{
require(credit[tx.origin] > 0, "No funds to transfer");
uint256 cred = credit[tx.origin];
credit[tx.origin] = 0;
tx.origin.transfer(cred);
}
| 996,969 |
./full_match/3/0xED4717a7C5c363Af896F64fA4B67C3E2816111fC/sources/contracts/Web3_payment/ETH/Merchant.sol | Initialize merchant contract Only merchant factory callable/ Transfer ownership to the admin address who becomes owner of the contract | function initialize(
address _merchantFactory,
address _merchantWallet,
address _receiveToken,
address _merchantOwner
) external onlyOwner {
require(!isInitialized, "Already initialized");
require(_merchantFactory != address(0), "Invalid factory");
require(
_merchantWallet != address(0),
"Invalid merchant wallet address"
);
require(_merchantOwner != address(0), "Invalid merchant owner");
require(
MerchantSharedProperty(_merchantFactory).isWhitelistedForRecToken(
_receiveToken
),
"Not whitelisted token"
);
MERCHANT_FACTORY = _merchantFactory;
merchantWallet = _merchantWallet;
receiveToken = _receiveToken;
emit MerchantWalletUpdated(
payable(address(0)),
payable(merchantWallet)
);
transferOwnership(_merchantOwner);
}
| 8,194,760 |
./full_match/100/0x4457a2Fa769325CA41851D4a5Bb403f5F55c87B6/sources/src/ConstantProductSwap.sol | solhint-disable-next-line not-rely-on-time | function getTradeableOrder() public view override returns (GPv2Order.Data memory) {
(uint256 my0, uint256 my1) = getReserves();
uint256 myK = my0.mul(my1);
(uint256 reserve0, uint256 reserve1,) = referencePair.getReserves();
uint256 new1 = sqrt(myK.mul(reserve1).div(reserve0));
uint256 new0 = myK.div(new1);
uint32 validTo = ((uint32(block.timestamp) / 3600) + 1) * 3600;
GPv2Order.Data memory order = GPv2Order.Data(
token0,
token1,
target,
0,
0,
validTo,
keccak256("ConstantProductSwap"),
0,
GPv2Order.KIND_SELL,
false,
GPv2Order.BALANCE_ERC20,
GPv2Order.BALANCE_ERC20
);
if (new1 > my1) {
order.sellToken = token0;
order.buyToken = token1;
order.sellAmount = my0.sub(new0).sub(1);
order.buyAmount = new1.sub(my1).add(1);
console.log(order.sellAmount, order.buyAmount);
require(order.sellAmount > my0.mul(minTradeVolumeBps).div(MAX_BPS), "min amount");
require(order.sellAmount <= token0.balanceOf(target), "max amount");
order.sellToken = token1;
order.buyToken = token0;
order.sellAmount = my1.sub(new1).sub(1);
order.buyAmount = new0.sub(my0).add(1);
console.log(order.sellAmount, order.buyAmount);
require(order.sellAmount > my1.mul(minTradeVolumeBps).div(MAX_BPS), "min amount");
require(order.sellAmount <= token1.balanceOf(target), "max amount");
}
return order;
}
| 14,273,786 |
./full_match/5/0xb5D6C3ECf9466e30332dfaD9F3816B63d332d83E/sources/contracts/LinkedList.sol | Returns the length of the list. self The linked list./ | function length(LinkedList storage self) internal view returns (uint128) {
return self._length;
}
| 1,908,525 |
./full_match/1/0x271d0C1940fE546e787B273A0CCc780ECD8db461/sources/Exchanger.sol | issue amount to user | function refund(address from, bytes32 currencyKey, uint amount) internal {
synthetix().synths(currencyKey).issue(from, amount);
synthetix().emitExchangeRebate(from, currencyKey, amount);
}
| 9,731,343 |
./full_match/43114/0xb17A67F28645FAC19856f4F36A5985e91ecB8Ec9/sources/contracts/Strategies.sol | PUBLIC FUNCTIONS Reward token balance that can be claimed Staking rewards accrue to contract on each deposit/withdrawal return Unclaimed rewards/ | function checkReward() public view returns (uint256) {
uint256 pendingLyd = lydMasterChef.pendingLyd(lydPid, address(this));
return pendingLyd;
}
| 4,518,101 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "LibPart.sol";
import "LibRoyaltiesV2.sol";
import "RoyaltiesV2.sol";
import "ERC721.sol";
import "ERC721Enumerable.sol";
import "ERC721Burnable.sol";
import "Pausable.sol";
import "Ownable.sol";
import "Counters.sol";
import "Strings.sol";
import "ReentrancyGuard.sol";
import "Whitelist.sol";
contract DragonRascal is
RoyaltiesV2,
ERC721,
ERC721Enumerable,
ERC721Burnable,
Pausable,
Ownable,
ReentrancyGuard
{
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
uint256 public balanceLimit; // max dragons per address
uint96 public royaltyRate; // in basis points, i.e. 500 == 5%
address public royaltiesReceiver; // where the royalities are paid
uint256 public price; // price per dragon
uint256 public tokenLimit; // total available dragons
string public baseURI; // the prefix for tokenURI
string public suffixURI; // the suffix for the tokenURI
Whitelist[] public whitelists;
uint256 public mintStart; // the time public mint starts
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
constructor(
string memory _initBaseURI,
address _royaltiesRecipient,
uint256 _mintStart
) ERC721("Dragon Rascals", "DRAGON") {
balanceLimit = 10;
royaltyRate = 500; // 5%
royaltiesReceiver = _royaltiesRecipient;
price = 100000000000000000; // 0.1 ether
tokenLimit = 8888;
baseURI = _initBaseURI;
suffixURI = ".json";
_tokenIdCounter.increment(); // start tokenId at 1
mintStart = _mintStart;
}
function setMintStart(uint256 _mintStart) external onlyOwner {
mintStart = _mintStart;
}
// start is sale period start
// end is period end or 0 for no end
// addresses is the array to whitelist
// entries is the corresponding number of tokens availble to mint
function createWhitelist(
uint256 start,
uint256 end,
address[] calldata addresses,
uint256[] calldata entries
) external onlyOwner {
Whitelist whitelist = new Whitelist(start, end);
whitelist.set(addresses, entries);
whitelists.push(whitelist);
}
// Set the prefix for the tokenURI
function setBaseURI(string memory _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
// Set the suffix for the tokenURI
function setSuffixURI(string memory _suffixURI) external onlyOwner {
suffixURI = _suffixURI;
}
// Set the price per dragon
function setPrice(uint256 _price) external onlyOwner {
price = _price;
}
// Set the total available dragons
function setTokenLimit(uint256 _tokenLimit) external onlyOwner {
tokenLimit = _tokenLimit;
}
// Set the maximum number of tokens per address
function setBalanceLimit(uint256 _balanceLimit) external onlyOwner {
balanceLimit = _balanceLimit;
}
// Set the royalties rate in basis points
function setRoyaltyRate(uint96 _royaltyRate) external onlyOwner {
royaltyRate = _royaltyRate;
}
// Set the recipient address for royalties
function setRoyaltiesReceiver(address _royaltiesReceiver)
external
onlyOwner
{
royaltiesReceiver = _royaltiesReceiver;
}
function withdraw(address _recipient) external payable onlyOwner {
require(_recipient != address(0), "zero address");
payable(_recipient).transfer(address(this).balance);
}
function _isMintable(uint256 qty) private returns (bool) {
for (uint8 i = 0; i < whitelists.length; i++) {
if (whitelists[i].isMintable(qty, msg.sender)) {
return true;
}
}
// not on a whitelist
return
(block.timestamp > mintStart) &&
((balanceOf(msg.sender) + qty) <= balanceLimit);
}
function _doMint(address to, uint256 qty) private {
for (uint256 i = 0; i < qty; i++) {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
emit RoyaltiesSet(tokenId, _getRoyalties(tokenId));
emit Transfer(owner(), to, tokenId);
}
}
function airdrop(address to, uint256 qty) external onlyOwner {
_doMint(to, qty);
}
// Mint qty tokens to address to
function mint(address to, uint256 qty) external payable nonReentrant {
require((qty + totalSupply()) <= tokenLimit, "sold out");
require(_isMintable(qty), "denied");
// skip payment check for owner so we can airdop
require(msg.value >= (price * qty), "insufficient funds");
_doMint(to, qty);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
// the tokenURI is the concat of baseURI + tokenId + suffixURI
function tokenURI(uint256 tokenId)
public
view
override(ERC721)
returns (string memory)
{
ownerOf(tokenId); // raises on non-existent tokenId
return
string(
abi.encodePacked(baseURI, Strings.toString(tokenId), suffixURI)
);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return
(interfaceId == LibRoyaltiesV2._INTERFACE_ID_ROYALTIES) ||
(interfaceId == _INTERFACE_ID_ERC2981) ||
super.supportsInterface(interfaceId);
}
// ERC2981
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
return (royaltiesReceiver, (_salePrice * royaltyRate) / 10000);
}
function _getRoyalties(uint256 tokenId)
private
view
returns (LibPart.Part[] memory)
{
LibPart.Part[] memory _royalties = new LibPart.Part[](1);
_royalties[0].value = royaltyRate;
_royalties[0].account = payable(royaltiesReceiver);
return _royalties;
}
function getRaribleV2Royalties(uint256 id)
external
view
override
returns (LibPart.Part[] memory)
{
return _getRoyalties(id);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library LibPart {
bytes32 public constant TYPE_HASH =
keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library LibRoyaltiesV2 {
/*
* bytes4(keccak256('getRoyalties(LibAsset.AssetType)')) == 0xcad96cca
*/
bytes4 constant _INTERFACE_ID_ROYALTIES = 0xcad96cca;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "LibPart.sol";
interface RoyaltiesV2 {
event RoyaltiesSet(uint256 tokenId, LibPart.Part[] royalties);
function getRaribleV2Royalties(uint256 id)
external
view
returns (LibPart.Part[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC721.sol";
import "IERC721Receiver.sol";
import "IERC721Metadata.sol";
import "Address.sol";
import "Context.sol";
import "Strings.sol";
import "ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^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;
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");
(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");
(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");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "ERC721.sol";
import "IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "ERC721.sol";
import "Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Whitelist {
mapping(address => uint256) public whitelist; // address => count permitted during presale
uint256 public start; // sale period start
uint256 public end; // optional sale period end
// _end == 0 skips period end check
constructor(uint256 _start, uint256 _end) {
start = _start;
end = _end;
}
function setTimes(uint256 _start, uint256 _end) external {
start = _start;
end = _end;
}
function set(address[] calldata addresses, uint256[] calldata entries)
external
{
require(
addresses.length == entries.length,
"addresses length != entries length"
);
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "zero");
whitelist[addresses[i]] = entries[i];
}
}
function isMintable(uint256 qty, address to) public returns (bool) {
// if we're in the whitelist period
if (
(block.timestamp > start) && (end == 0 || (block.timestamp < end))
) {
// grab the current balance for this address
uint256 balance = whitelist[to];
// if the requested qty is greater than the balance
if (qty > balance) {
return false; // nope
}
// update the balance for this address
whitelist[to] = balance - qty;
return true; // yep!
}
return false;
}
} | start is sale period start end is period end or 0 for no end addresses is the array to whitelist entries is the corresponding number of tokens availble to mint | function createWhitelist(
uint256 start,
uint256 end,
address[] calldata addresses,
uint256[] calldata entries
) external onlyOwner {
Whitelist whitelist = new Whitelist(start, end);
whitelist.set(addresses, entries);
whitelists.push(whitelist);
}
| 1,600,971 |
./full_match/1/0x032Ba44EB2DB607d2F9424b90e191BbFb51152A1/sources/@pooltogether/v4-core/contracts/prize-strategy/PrizeSplitStrategy.sol | Award ticket tokens to prize split recipient. Award ticket tokens to prize split recipient via the linked PrizePool contract. _to Recipient of minted tokens. _amount Amount of minted tokens./ | function _awardPrizeSplitAmount(address _to, uint256 _amount) internal override {
IControlledToken _ticket = prizePool.getTicket();
prizePool.award(_to, _amount);
emit PrizeSplitAwarded(_to, _amount, _ticket);
}
| 16,513,472 |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./cron/contracts/IPeriod.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* Transfers are only accessible via transferFrom
*/
contract VoteToken is IERC20, Ownable {
using SafeMath for uint256;
IPeriod public period;
mapping (uint256 => mapping (address => uint256)) private _balances;
mapping (uint256 => mapping(address => mapping (address => uint256))) private _allowed;
mapping (uint256 => uint256) private _totalSupply;
mapping (uint256 => uint256) private _transferVolume;
function setPeriod(address _period) public {
period = IPeriod(_period);
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply[period.height()];
}
/**
* @dev Gets the balance of the specified address.
* @param _tokenOwner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _tokenOwner) public view returns (uint256) {
return balanceAt(period.height(), _tokenOwner);
}
/**
* @dev Gets the balance of the specified address.
* @param _tokenOwner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceAt(uint256 _epoch, address _tokenOwner) public view returns (uint256) {
return _balances[_epoch][_tokenOwner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _tokenOwner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _tokenOwner, address _spender) public view returns (uint256) {
if(_spender == owner()) {
return _balances[period.height()][_tokenOwner];
}
else {
return 0;
}
}
/**
* @dev Not necessary for the case, included to keep ERC20 compliance
*/
function transfer(address _to, uint256 _value) public returns (bool) {
return false;
}
/**
* @dev Not necessary for the case, included to keep ERC20 compliance
*
*/
function approve(address _spender, uint256 _value) public returns (bool) {
return false;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
_transfer(_from, _to, _value);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != address(0));
_balances[period.height()][_from] = _balances[period.height()][_from].sub(_value);
_balances[period.height()][_to] = _balances[period.height()][_to].add(_value);
_transferVolume[period.height()] = _transferVolume[period.height()].add(_value);
emit Transfer(_from, _to, _value);
}
function mint(address _account, uint256 _value) public {
require(msg.sender == owner());
_mint(_account, _value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param _account The account that will receive the created tokens.
* @param _value The amount that will be created.
*/
function _mint(address _account, uint256 _value) internal {
require(_account != address(0));
_totalSupply[period.height()] = _totalSupply[period.height()].add(_value);
_balances[period.height()][_account] = _balances[period.height()][_account].add(_value);
emit Transfer(address(0), _account, _value);
}
} | Function to check the amount of tokens that an owner allowed to a spender. _tokenOwner address The address which owns the funds. _spender address The address which will spend the funds. return A uint256 specifying the amount of tokens still available for the spender./ | function allowance(address _tokenOwner, address _spender) public view returns (uint256) {
if(_spender == owner()) {
return _balances[period.height()][_tokenOwner];
}
else {
return 0;
}
}
| 12,792,849 |
/**
* Copyright 2017-2020, bZeroX, LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.8;
pragma experimental ABIEncoderV2;
import "./AdvancedToken.sol";
import "../shared/OracleNotifierInterface.sol";
interface IBZx {
function takeOrderFromiToken(
bytes32 loanOrderHash, // existing loan order hash
address[4] calldata sentAddresses,
// trader: borrower/trader
// collateralTokenAddress: collateral token
// tradeTokenAddress: trade token
// receiver: receiver of funds (address(0) assumes trader address)
uint256[7] calldata sentAmounts,
// newInterestRate: new loan interest rate
// newLoanAmount: new loan size (principal from lender)
// interestInitialAmount: interestAmount sent to determine initial loan length (this is included in one of the below)
// loanTokenSent: loanTokenAmount + interestAmount + any extra
// collateralTokenSent: collateralAmountRequired + any extra
// tradeTokenSent: tradeTokenAmount (optional)
// withdrawalAmount: Actual amount sent to borrower (can't exceed newLoanAmount)
bytes calldata loanDataBytes)
external
returns (uint256);
function payInterestForOracle(
address oracleAddress,
address interestTokenAddress)
external
returns (uint256);
function getLenderInterestForOracle(
address lender,
address oracleAddress,
address interestTokenAddress)
external
view
returns (
uint256 interestPaid,
uint256 interestPaidDate,
uint256 interestOwedPerDay,
uint256 interestUnPaid);
function oracleAddresses(
address oracleAddress)
external
view
returns (address);
function getRequiredCollateral(
address loanTokenAddress,
address collateralTokenAddress,
address oracleAddress,
uint256 newLoanAmount,
uint256 marginAmount)
external
view
returns (uint256 collateralTokenAmount);
function getBorrowAmount(
address loanTokenAddress,
address collateralTokenAddress,
address oracleAddress,
uint256 collateralTokenAmount,
uint256 marginAmount)
external
view
returns (uint256 borrowAmount);
}
interface IBZxOracle {
function getTradeData(
address sourceTokenAddress,
address destTokenAddress,
uint256 sourceTokenAmount)
external
view
returns (
uint256 sourceToDestRate,
uint256 sourceToDestPrecision,
uint256 destTokenAmount
);
}
interface iChai {
function move(
address src,
address dst,
uint256 wad)
external
returns (bool);
function join(
address dst,
uint256 wad)
external;
function draw(
address src,
uint256 wad)
external;
function balanceOf(
address _who)
external
view
returns (uint256);
}
interface iPot {
function dsr()
external
view
returns (uint256);
function chi()
external
view
returns (uint256);
function rho()
external
view
returns (uint256);
}
contract LoanTokenLogicV4_Chai is AdvancedToken, OracleNotifierInterface {
using SafeMath for uint256;
address internal target_;
uint256 constant RAY = 10 ** 27;
address internal constant arbitraryCaller = 0x4c67b3dB1d4474c0EBb2DB8BeC4e345526d9E2fd;
// Mainnet
iChai public constant chai = iChai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
iPot public constant pot = iPot(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7);
ERC20 public constant dai = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
// Kovan
/*iChai public constant chai = iChai(0x71DD45d9579A499B58aa85F50E5E3B241Ca2d10d);
iPot public constant pot = iPot(0xEA190DBDC7adF265260ec4dA6e9675Fd4f5A78bb);
ERC20 public constant dai = ERC20(0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa);*/
modifier onlyOracle() {
require(msg.sender == IBZx(bZxContract).oracleAddresses(bZxOracle), "1");
_;
}
function()
external
{}
/* Public functions */
function mintWithChai(
address receiver,
uint256 depositAmount)
external
nonReentrant
returns (uint256 mintAmount)
{
return _mintToken(
receiver,
depositAmount,
true // withChai
);
}
function mint(
address receiver,
uint256 depositAmount)
external
nonReentrant
returns (uint256 mintAmount)
{
return _mintToken(
receiver,
depositAmount,
false // withChai
);
}
function burnToChai(
address receiver,
uint256 burnAmount)
external
nonReentrant
returns (uint256 chaiAmountPaid)
{
return _burnToken(
burnAmount,
receiver,
true // toChai
);
}
function burn(
address receiver,
uint256 burnAmount)
external
nonReentrant
returns (uint256 loanAmountPaid)
{
return _burnToken(
burnAmount,
receiver,
false // toChai
);
}
function flashBorrowToken(
uint256 borrowAmount,
address borrower,
address target,
string calldata signature,
bytes calldata data)
external
payable
nonReentrant
returns (bytes memory)
{
_settleInterest();
ERC20 _dai;
if (borrowAmount != 0) {
_dai = _dsrWithdraw(borrowAmount);
}
uint256 beforeEtherBalance = address(this).balance.sub(msg.value);
uint256 beforeAssetsBalance = _underlyingBalance()
.add(totalAssetBorrow);
require(beforeAssetsBalance != 0, "38");
if (borrowAmount != 0) {
require(_dai.transfer(
borrower,
borrowAmount
), "39");
}
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
burntTokenReserved = beforeAssetsBalance;
(bool success, bytes memory returnData) = arbitraryCaller.call.value(msg.value)(
abi.encodeWithSelector(
0xba25d2ff, // sendCall(address,address,bytes)
msg.sender,
target,
callData
)
);
require(success, "call failed");
burntTokenReserved = 0;
require(
address(this).balance >= beforeEtherBalance &&
_underlyingBalance()
.add(totalAssetBorrow) >= beforeAssetsBalance,
"40"
);
_dsrDeposit();
return returnData;
}
function borrowTokenFromDeposit(
uint256 borrowAmount,
uint256 leverageAmount,
uint256 initialLoanDuration, // duration in seconds
uint256 collateralTokenSent, // set to 0 if sending ETH
address borrower,
address receiver,
address collateralTokenAddress, // address(0) means ETH and ETH must be sent with the call
bytes memory loanDataBytes) // arbitrary order data
public
payable
returns (bytes32 loanOrderHash)
{
require(
((msg.value == 0 && collateralTokenAddress != address(0) && collateralTokenSent != 0) ||
(msg.value != 0 && (collateralTokenAddress == address(0) || collateralTokenAddress == wethContract) && collateralTokenSent == 0)),
"6"
);
if (msg.value != 0) {
collateralTokenAddress = wethContract;
collateralTokenSent = msg.value;
}
uint256 _borrowAmount = borrowAmount;
leverageAmount = uint256(keccak256(abi.encodePacked(leverageAmount,collateralTokenAddress)));
loanOrderHash = loanOrderHashes[leverageAmount];
require(loanOrderHash != 0, "7");
_settleInterest();
uint256[7] memory sentAmounts;
LoanData memory loanOrder = loanOrderData[loanOrderHash];
bool useFixedInterestModel = loanOrder.maxDurationUnixTimestampSec == 0;
if (_borrowAmount == 0) {
_borrowAmount = _getBorrowAmountForDeposit(
collateralTokenSent,
leverageAmount,
initialLoanDuration,
collateralTokenAddress
);
require(_borrowAmount != 0, "35");
// withdrawalAmount
sentAmounts[6] = _borrowAmount;
} else {
// withdrawalAmount
sentAmounts[6] = _borrowAmount;
}
// interestRate, interestInitialAmount, borrowAmount (newBorrowAmount)
(sentAmounts[0], sentAmounts[2], _borrowAmount) = _getInterestRateAndAmount(
_borrowAmount,
_totalAssetSupply(0), // interest is settled above
initialLoanDuration,
useFixedInterestModel
);
sentAmounts[6] = _borrowTokenAndUseFinal(
loanOrderHash,
[
borrower,
collateralTokenAddress,
address(0), // tradeTokenAddress
receiver
],
[
sentAmounts[0], // interestRate
_borrowAmount,
sentAmounts[2], // interestInitialAmount
0, // loanTokenSent
collateralTokenSent,
0, // tradeTokenSent
sentAmounts[6] // withdrawalAmount
],
loanDataBytes
);
require(sentAmounts[6] == _borrowAmount, "8");
_dsrDeposit();
}
// Called to borrow token for withdrawal or trade
// borrowAmount: loan amount to borrow
// leverageAmount: signals the amount of initial margin we will collect
// Please reference the docs for supported values.
// Example: 2000000000000000000 -> 150% initial margin
// 2000000000000000028 -> 150% initial margin, 28-day fixed-term
// interestInitialAmount: This value will indicate the initial duration of the loan
// This is ignored if the loan order has a fixed-term
// loanTokenSent: loan token sent (interestAmount + extra)
// collateralTokenSent: collateral token sent
// tradeTokenSent: trade token sent
// borrower: the address the loan will be assigned to (this address can be different than msg.sender)
// Collateral and interest for loan will be withdrawn from msg.sender
// receiver: the address that receives the funds (address(0) assumes borrower address)
// collateralTokenAddress: The token to collateralize the loan in
// tradeTokenAddress: The borrowed token will be swap for this token to start a leveraged trade
// If the borrower wished to instead withdraw the borrowed token to their wallet, set this to address(0)
// If set to address(0), initial collateral required will equal initial margin percent + 100%
// returns loanOrderHash for the base protocol loan
function borrowTokenAndUse(
uint256 borrowAmount,
uint256 leverageAmount,
uint256 interestInitialAmount,
uint256 loanTokenSent,
uint256 collateralTokenSent,
uint256 tradeTokenSent,
address borrower,
address receiver,
address collateralTokenAddress,
address tradeTokenAddress,
bytes memory loanDataBytes)
public
returns (bytes32 loanOrderHash)
{
address[4] memory sentAddresses;
sentAddresses[0] = borrower;
sentAddresses[1] = collateralTokenAddress;
sentAddresses[2] = tradeTokenAddress;
sentAddresses[3] = receiver;
uint256[7] memory sentAmounts;
//sentAmounts[0] = 0; // interestRate (found later)
sentAmounts[1] = borrowAmount;
sentAmounts[2] = interestInitialAmount;
sentAmounts[3] = loanTokenSent;
sentAmounts[4] = collateralTokenSent;
sentAmounts[5] = tradeTokenSent;
sentAmounts[6] = sentAmounts[1];
require(sentAddresses[1] != address(0) &&
(sentAddresses[2] == address(0) ||
sentAddresses[2] != address(_getDai())),
"9"
);
loanOrderHash = _borrowTokenAndUse(
uint256(keccak256(abi.encodePacked(leverageAmount,sentAddresses[1]))),
sentAddresses,
sentAmounts,
false, // amountIsADeposit
loanDataBytes
);
}
function marginTradeFromDeposit(
uint256 depositAmount,
uint256 leverageAmount,
uint256 loanTokenSent,
uint256 collateralTokenSent,
uint256 tradeTokenSent,
address trader,
address depositTokenAddress,
address collateralTokenAddress,
address tradeTokenAddress,
bytes memory loanDataBytes)
public
returns (bytes32 loanOrderHash)
{
return _marginTradeFromDeposit(
depositAmount,
leverageAmount,
loanTokenSent,
collateralTokenSent,
tradeTokenSent,
trader,
depositTokenAddress,
collateralTokenAddress,
tradeTokenAddress,
loanDataBytes
);
}
function transfer(
address _to,
uint256 _value)
public
returns (bool)
{
require(_value <= balances[msg.sender] &&
_to != address(0),
"13"
);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
// handle checkpoint update
uint256 currentPrice = tokenPrice();
if (balances[msg.sender] != 0) {
checkpointPrices_[msg.sender] = currentPrice;
} else {
checkpointPrices_[msg.sender] = 0;
}
if (balances[_to] != 0) {
checkpointPrices_[_to] = currentPrice;
} else {
checkpointPrices_[_to] = 0;
}
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value)
public
returns (bool)
{
uint256 allowanceAmount = allowed[_from][msg.sender];
require(_value <= balances[_from] &&
_value <= allowanceAmount &&
_to != address(0),
"14"
);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
if (allowanceAmount < MAX_UINT) {
allowed[_from][msg.sender] = allowanceAmount.sub(_value);
}
// handle checkpoint update
uint256 currentPrice = tokenPrice();
if (balances[_from] != 0) {
checkpointPrices_[_from] = currentPrice;
} else {
checkpointPrices_[_from] = 0;
}
if (balances[_to] != 0) {
checkpointPrices_[_to] = currentPrice;
} else {
checkpointPrices_[_to] = 0;
}
emit Transfer(_from, _to, _value);
return true;
}
/* Public View functions */
// the current Maker DSR normalized to APR
function dsr()
public
view
returns (uint256)
{
return _getPot().dsr()
.sub(RAY)
.mul(31536000) // seconds in a year
.div(10**7);
}
// daiAmount = chaiAmount * chaiPrice
function chaiPrice()
public
view
returns (uint256)
{
iPot _pot = _getPot();
uint256 rho = _pot.rho();
uint256 chi = _pot.chi();
if (now > rho) {
chi = rmul(rpow(_pot.dsr(), now - rho, RAY), chi);
}
return chi
.div(10**9);
}
function tokenPrice()
public
view
returns (uint256 price)
{
uint256 interestUnPaid;
if (lastSettleTime_ != block.timestamp) {
(,interestUnPaid) = _getAllInterest();
}
return _tokenPrice(_totalAssetSupply(interestUnPaid));
}
function checkpointPrice(
address _user)
public
view
returns (uint256 price)
{
return checkpointPrices_[_user];
}
function marketLiquidity()
public
view
returns (uint256)
{
uint256 totalSupply = totalAssetSupply();
if (totalSupply > totalAssetBorrow) {
return totalSupply.sub(totalAssetBorrow);
}
}
function protocolInterestRate()
public
view
returns (uint256)
{
return _protocolInterestRate(totalAssetBorrow);
}
// the minimum rate the next base protocol borrower will receive for variable-rate loans
function borrowInterestRate()
public
view
returns (uint256)
{
return _nextBorrowInterestRate(
0, // borrowAmount
false // useFixedInterestModel
);
}
function nextBorrowInterestRate(
uint256 borrowAmount)
public
view
returns (uint256)
{
return _nextBorrowInterestRate(
borrowAmount,
false // useFixedInterestModel
);
}
function nextBorrowInterestRateWithOption(
uint256 borrowAmount,
bool useFixedInterestModel)
public
view
returns (uint256)
{
return _nextBorrowInterestRate(
borrowAmount,
useFixedInterestModel
);
}
// the average interest that borrowers are currently paying for open loans
function avgBorrowInterestRate()
public
view
returns (uint256)
{
uint256 assetBorrow = totalAssetBorrow;
if (assetBorrow != 0) {
return _protocolInterestRate(assetBorrow)
.mul(checkpointSupply)
.div(totalAssetSupply());
} else {
return _getLowUtilBaseRate();
}
}
// interest that lenders are currently receiving when supplying to the pool
function supplyInterestRate()
public
view
returns (uint256)
{
return totalSupplyInterestRate(totalAssetSupply());
}
function nextSupplyInterestRate(
uint256 supplyAmount)
public
view
returns (uint256)
{
return totalSupplyInterestRate(totalAssetSupply().add(supplyAmount));
}
function totalSupplyInterestRate(
uint256 assetSupply)
public
view
returns (uint256)
{
uint256 assetBorrow = totalAssetBorrow;
if (assetBorrow != 0) {
return _supplyInterestRate(
assetBorrow,
assetSupply
);
} else {
return dsr();
}
}
function totalAssetSupply()
public
view
returns (uint256)
{
uint256 interestUnPaid;
if (lastSettleTime_ != block.timestamp) {
(,interestUnPaid) = _getAllInterest();
}
return _totalAssetSupply(interestUnPaid);
}
function getMaxEscrowAmount(
uint256 leverageAmount)
public
view
returns (uint256)
{
LoanData memory loanData = loanOrderData[loanOrderHashes[leverageAmount]];
if (loanData.initialMarginAmount == 0)
return 0;
return marketLiquidity()
.mul(loanData.initialMarginAmount)
.div(_adjustValue(
10**20, // maximum possible interest (100%)
loanData.maxDurationUnixTimestampSec,
loanData.initialMarginAmount));
}
function getLeverageList()
public
view
returns (uint256[] memory)
{
return leverageList;
}
function getLoanData(
bytes32 loanOrderHash)
public
view
returns (LoanData memory)
{
return loanOrderData[loanOrderHash];
}
// returns the user's balance of underlying token
function assetBalanceOf(
address _owner)
public
view
returns (uint256)
{
return balanceOf(_owner)
.mul(tokenPrice())
.div(10**18);
}
function getDepositAmountForBorrow(
uint256 borrowAmount,
uint256 leverageAmount, // use 2000000000000000000 for 150% initial margin
uint256 initialLoanDuration, // duration in seconds
address collateralTokenAddress) // address(0) means ETH
public
view
returns (uint256 depositAmount)
{
if (borrowAmount != 0) {
leverageAmount = uint256(keccak256(abi.encodePacked(leverageAmount,collateralTokenAddress)));
LoanData memory loanOrder = loanOrderData[loanOrderHashes[leverageAmount]];
uint256 marginAmount = loanOrder.initialMarginAmount
.add(10**20); // adjust for over-collateralized loan
//.add(loanOrder.marginPremiumAmount);
// adjust value since interest is also borrowed
borrowAmount = borrowAmount
.mul(_getTargetNextRateMultiplierValue(initialLoanDuration))
.div(10**22);
if (borrowAmount <= _underlyingBalance()) {
return IBZx(bZxContract).getRequiredCollateral(
address(_getDai()),
collateralTokenAddress != address(0) ? collateralTokenAddress : wethContract,
bZxOracle,
borrowAmount,
marginAmount
).add(10); // add some dust to ensure enough is borrowed later
}
}
}
function getBorrowAmountForDeposit(
uint256 depositAmount,
uint256 leverageAmount, // use 2000000000000000000 for 150% initial margin
uint256 initialLoanDuration, // duration in seconds
address collateralTokenAddress) // address(0) means ETH
public
view
returns (uint256 borrowAmount)
{
leverageAmount = uint256(keccak256(abi.encodePacked(leverageAmount,collateralTokenAddress)));
borrowAmount = _getBorrowAmountForDeposit(
depositAmount,
leverageAmount,
initialLoanDuration,
collateralTokenAddress
);
}
// can safely be called by anyone at anytime
function setupChai()
public
{
_getDai().approve(address(_getChai()), MAX_UINT);
_dsrDeposit();
}
/* Internal functions */
function _mintToken(
address receiver,
uint256 depositAmount,
bool withChai)
internal
returns (uint256 mintAmount)
{
require (depositAmount != 0, "17");
_settleInterest();
uint256 currentPrice = _tokenPrice(_totalAssetSupply(0));
uint256 currentChaiPrice;
ERC20 inAsset;
if (withChai) {
inAsset = ERC20(address(_getChai()));
currentChaiPrice = chaiPrice();
} else {
inAsset = ERC20(address(_getDai()));
}
require(inAsset.transferFrom(
msg.sender,
address(this),
depositAmount
), "18");
_dsrDeposit();
if (withChai) {
// convert to Dai
depositAmount = depositAmount
.mul(currentChaiPrice)
.div(10**18);
}
mintAmount = depositAmount
.mul(10**18)
.div(currentPrice);
_mint(receiver, mintAmount, depositAmount, currentPrice);
checkpointPrices_[receiver] = currentPrice;
}
function _burnToken(
uint256 burnAmount,
address receiver,
bool toChai)
internal
returns (uint256 amountPaid)
{
require(burnAmount != 0, "19");
if (burnAmount > balanceOf(msg.sender)) {
burnAmount = balanceOf(msg.sender);
}
_settleInterest();
uint256 currentPrice = _tokenPrice(_totalAssetSupply(0));
uint256 loanAmountOwed = burnAmount
.mul(currentPrice)
.div(10**18);
amountPaid = loanAmountOwed;
bool success;
if (toChai) {
_dsrDeposit();
iChai _chai = _getChai();
uint256 chaiBalance = _chai.balanceOf(address(this));
success = _chai.move(
address(this),
msg.sender,
amountPaid
);
// get Chai amount withdrawn
amountPaid = chaiBalance
.sub(_chai.balanceOf(address(this)));
} else {
success = _dsrWithdraw(amountPaid).transfer(
receiver,
amountPaid
);
_dsrDeposit();
}
require (success, "37"); // free liquidity of DAI/CHAI insufficient
_burn(msg.sender, burnAmount, loanAmountOwed, currentPrice);
if (balances[msg.sender] != 0) {
checkpointPrices_[msg.sender] = currentPrice;
} else {
checkpointPrices_[msg.sender] = 0;
}
}
function _settleInterest()
internal
{
if (lastSettleTime_ != block.timestamp) {
IBZx(bZxContract).payInterestForOracle(
bZxOracle, // (leave as original value)
address(_getDai()) // same as interestTokenAddress
);
lastSettleTime_ = block.timestamp;
}
}
// Called by pTokens to borrow and immediately get into a positions
// Other traders can call this, but it's recommended to instead use borrowTokenAndUse(...) instead
// assumption: depositAmount is collateral + interest deposit and will be denominated in deposit token
// assumption: loan token and interest token are the same
// returns loanOrderHash for the base protocol loan
function _marginTradeFromDeposit(
uint256 depositAmount,
uint256 leverageAmount,
uint256 loanTokenSent,
uint256 collateralTokenSent,
uint256 tradeTokenSent,
address trader,
address depositTokenAddress,
address collateralTokenAddress,
address tradeTokenAddress,
bytes memory loanDataBytes)
internal
returns (bytes32 loanOrderHash)
{
address _daiAddress = address(_getDai());
require(tradeTokenAddress != address(0) &&
tradeTokenAddress != _daiAddress,
"10"
);
uint256 amount = depositAmount;
// To calculate borrow amount and interest owed to lender we need deposit amount to be represented as loan token
if (depositTokenAddress == tradeTokenAddress) {
(,,amount) = IBZxOracle(bZxOracle).getTradeData(
tradeTokenAddress,
_daiAddress,
amount
);
} else if (depositTokenAddress != _daiAddress) {
// depositTokenAddress can only be tradeTokenAddress or loanTokenAddress
revert("11");
}
loanOrderHash = _borrowTokenAndUse(
leverageAmount,
[
trader,
collateralTokenAddress, // collateralTokenAddress
tradeTokenAddress, // tradeTokenAddress
trader // receiver
],
[
0, // interestRate (found later)
amount, // amount of deposit
0, // interestInitialAmount (interest is calculated based on fixed-term loan)
loanTokenSent,
collateralTokenSent,
tradeTokenSent,
0
],
true, // amountIsADeposit
loanDataBytes
);
}
function _getBorrowAmountForDeposit(
uint256 depositAmount,
uint256 leverageAmount, // use 2000000000000000000 for 150% initial margin
uint256 initialLoanDuration, // duration in seconds
address collateralTokenAddress) // address(0) means ETH
internal
view
returns (uint256 borrowAmount)
{
if (depositAmount != 0) {
LoanData memory loanOrder = loanOrderData[loanOrderHashes[leverageAmount]];
uint256 marginAmount = loanOrder.initialMarginAmount
.add(10**20); // adjust for over-collateralized loan
//.add(loanOrder.marginPremiumAmount);
borrowAmount = IBZx(bZxContract).getBorrowAmount(
address(_getDai()),
collateralTokenAddress != address(0) ? collateralTokenAddress : wethContract,
bZxOracle,
depositAmount,
marginAmount
);
// adjust value since interest is also borrowed
borrowAmount = borrowAmount
.mul(10**22)
.div(_getTargetNextRateMultiplierValue(initialLoanDuration));
if (borrowAmount > _underlyingBalance()) {
borrowAmount = 0;
}
}
}
function _getTargetNextRateMultiplierValue(
uint256 initialLoanDuration)
internal
view
returns (uint256)
{
return rateMultiplier
.mul(80 ether)
.div(10**20)
.add(baseRate)
.mul(initialLoanDuration)
.div(315360) // 365 * 86400 / 100
.add(10**22);
}
function _getInterestRateAndAmount(
uint256 borrowAmount,
uint256 assetSupply,
uint256 initialLoanDuration, // duration in seconds
bool useFixedInterestModel) // False=variable interest, True=fixed interest
internal
view
returns (uint256 interestRate, uint256 interestInitialAmount, uint256 newBorrowAmount)
{
(,interestInitialAmount) = _getInterestRateAndAmount2(
borrowAmount,
assetSupply,
initialLoanDuration,
useFixedInterestModel
);
(interestRate, interestInitialAmount) = _getInterestRateAndAmount2(
borrowAmount
.add(interestInitialAmount),
assetSupply,
initialLoanDuration,
useFixedInterestModel
);
newBorrowAmount = borrowAmount
.add(interestInitialAmount);
}
function _getInterestRateAndAmount2(
uint256 borrowAmount,
uint256 assetSupply,
uint256 initialLoanDuration,
bool useFixedInterestModel)
internal
view
returns (uint256 interestRate, uint256 interestInitialAmount)
{
interestRate = _nextBorrowInterestRate2(
borrowAmount,
assetSupply,
useFixedInterestModel
);
// initial interestInitialAmount
interestInitialAmount = borrowAmount
.mul(interestRate)
.mul(initialLoanDuration)
.div(31536000 * 10**20); // 365 * 86400 * 10**20
}
function _borrowTokenAndUse(
uint256 leverageAmount,
address[4] memory sentAddresses,
uint256[7] memory sentAmounts,
bool amountIsADeposit,
bytes memory loanDataBytes)
internal
returns (bytes32 loanOrderHash)
{
require(sentAmounts[1] != 0, "21"); // amount
loanOrderHash = loanOrderHashes[leverageAmount];
require(loanOrderHash != 0, "22");
_settleInterest();
LoanData memory loanOrder = loanOrderData[loanOrderHash];
bool useFixedInterestModel = loanOrder.maxDurationUnixTimestampSec == 0;
//sentAmounts[7] = loanOrder.marginPremiumAmount;
if (amountIsADeposit) {
(sentAmounts[1], sentAmounts[0]) = _getBorrowAmountAndRate( // borrowAmount, interestRate
loanOrderHash,
sentAmounts[1], // amount
useFixedInterestModel
);
// update for borrowAmount
sentAmounts[6] = sentAmounts[1]; // borrowAmount
} else {
// amount is borrow amount
sentAmounts[0] = _nextBorrowInterestRate2( // interestRate
sentAmounts[1], // amount
_totalAssetSupply(0),
useFixedInterestModel
);
}
if (sentAddresses[2] == address(0)) { // tradeTokenAddress
// tradeTokenSent is ignored if trade token isn't specified
sentAmounts[5] = 0;
}
uint256 borrowAmount = _borrowTokenAndUseFinal(
loanOrderHash,
sentAddresses,
sentAmounts,
loanDataBytes
);
require(borrowAmount == sentAmounts[1], "23");
_dsrDeposit();
}
// returns borrowAmount
function _borrowTokenAndUseFinal(
bytes32 loanOrderHash,
address[4] memory sentAddresses,
uint256[7] memory sentAmounts,
bytes memory loanDataBytes)
internal
returns (uint256)
{
require (sentAmounts[1] <= _underlyingBalance() && // borrowAmount
sentAddresses[0] != address(0), // borrower
"24"
);
if (sentAddresses[3] == address(0)) {
sentAddresses[3] = sentAddresses[0]; // receiver = borrower
}
// handle transfers prior to adding borrowAmount to loanTokenSent
_verifyTransfers(
sentAddresses,
sentAmounts
);
// adding the loan token amount from the lender to loanTokenSent
sentAmounts[3] = sentAmounts[3]
.add(sentAmounts[1]); // borrowAmount
sentAmounts[1] = IBZx(bZxContract).takeOrderFromiToken( // borrowAmount
loanOrderHash,
sentAddresses,
sentAmounts,
loanDataBytes
);
require (sentAmounts[1] != 0, "25");
// update total borrowed amount outstanding in loans
totalAssetBorrow = totalAssetBorrow
.add(sentAmounts[1]); // borrowAmount
// checkpoint supply since the base protocol borrow stats have changed
checkpointSupply = _totalAssetSupply(0);
emit Borrow(
sentAddresses[0], // borrower
sentAmounts[1], // borrowAmount
sentAmounts[0], // interestRate
sentAddresses[1], // collateralTokenAddress
sentAddresses[2], // tradeTokenAddress
sentAddresses[2] == address(0) // withdrawOnOpen
);
return sentAmounts[1]; // borrowAmount;
}
// sentAddresses[0]: borrower
// sentAddresses[1]: collateralTokenAddress
// sentAddresses[2]: tradeTokenAddress
// sentAddresses[3]: receiver
// sentAmounts[0]: interestRate
// sentAmounts[1]: borrowAmount
// sentAmounts[2]: interestInitialAmount
// sentAmounts[3]: loanTokenSent
// sentAmounts[4]: collateralTokenSent
// sentAmounts[5]: tradeTokenSent
// sentAmounts[6]: withdrawalAmount
function _verifyTransfers(
address[4] memory sentAddresses,
uint256[7] memory sentAmounts)
internal
{
address collateralTokenAddress = sentAddresses[1];
address tradeTokenAddress = sentAddresses[2];
address receiver = sentAddresses[3];
uint256 borrowAmount = sentAmounts[1];
uint256 loanTokenSent = sentAmounts[3];
uint256 collateralTokenSent = sentAmounts[4];
uint256 tradeTokenSent = sentAmounts[5];
uint256 withdrawalAmount = sentAmounts[6];
ERC20 _dai = _dsrWithdraw(borrowAmount);
bool success;
if (tradeTokenAddress == address(0)) { // withdrawOnOpen == true
success = _dai.transfer(
receiver,
withdrawalAmount
);
if (success && borrowAmount > withdrawalAmount) {
success = _dai.transfer(
bZxVault,
borrowAmount - withdrawalAmount
);
}
} else {
success = _dai.transfer(
bZxVault,
borrowAmount
);
}
require(success, "26");
success = false;
if (collateralTokenSent != 0) {
if (collateralTokenAddress == wethContract && msg.value != 0 && collateralTokenSent == msg.value) {
WETHInterface(wethContract).deposit.value(collateralTokenSent)();
success = ERC20(collateralTokenAddress).transfer(
bZxVault,
collateralTokenSent
);
} else {
if (collateralTokenAddress == address(_dai)) {
loanTokenSent = loanTokenSent.add(collateralTokenSent);
success = true;
} else if (collateralTokenAddress == tradeTokenAddress) {
tradeTokenSent = tradeTokenSent.add(collateralTokenSent);
success = true;
} else {
success = ERC20(collateralTokenAddress).transferFrom(
msg.sender,
bZxVault,
collateralTokenSent
);
}
}
require(success, "27");
}
if (loanTokenSent != 0) {
if (address(_dai) == tradeTokenAddress) {
tradeTokenSent = tradeTokenSent.add(loanTokenSent);
} else {
require(_dai.transferFrom(
msg.sender,
bZxVault,
loanTokenSent
), "31");
}
}
if (tradeTokenSent != 0) {
require(ERC20(tradeTokenAddress).transferFrom(
msg.sender,
bZxVault,
tradeTokenSent
), "32");
}
}
function _dsrDeposit()
internal
{
uint256 localBalance = _getDai().balanceOf(address(this));
if (localBalance != 0) {
_getChai().join(
address(this),
localBalance
);
}
}
function _dsrWithdraw(
uint256 _value)
internal
returns (ERC20 _dai)
{
_dai = _getDai();
uint256 localBalance = _dai.balanceOf(address(this));
if (_value > localBalance) {
_getChai().draw(
address(this),
_value - localBalance
);
}
}
function _underlyingBalance()
internal
view
returns (uint256)
{
return _getChai().balanceOf(address(this))
.mul(chaiPrice())
.div(10**18)
.add(_getDai().balanceOf(address(this)));
}
/* Internal View functions */
function _tokenPrice(
uint256 assetSupply)
internal
view
returns (uint256)
{
uint256 totalTokenSupply = totalSupply_;
return totalTokenSupply != 0 ?
assetSupply
.mul(10**18)
.div(totalTokenSupply) : initialPrice;
}
function _protocolInterestRate(
uint256 assetBorrow)
internal
view
returns (uint256)
{
if (assetBorrow != 0) {
(uint256 interestOwedPerDay,) = _getAllInterest();
return interestOwedPerDay
.mul(10**20)
.div(assetBorrow)
.mul(365);
}
}
// next supply interest adjustment
function _supplyInterestRate(
uint256 assetBorrow,
uint256 assetSupply)
public
view
returns (uint256)
{
uint256 _dsr = dsr();
if (assetBorrow != 0 && assetSupply >= assetBorrow) {
uint256 localBalance = _getDai().balanceOf(address(this));
uint256 _utilRate = _utilizationRate(
assetBorrow,
assetSupply
.sub(localBalance) // DAI not DSR'ed can't be counted
);
_dsr = _dsr
.mul(SafeMath.sub(100 ether, _utilRate));
if (localBalance != 0) {
_utilRate = _utilizationRate(
assetBorrow,
assetSupply
);
}
return _protocolInterestRate(assetBorrow)
.mul(_utilRate)
.add(_dsr)
.div(10**20);
} else {
return _dsr;
}
}
function _nextBorrowInterestRate(
uint256 borrowAmount,
bool useFixedInterestModel)
internal
view
returns (uint256)
{
uint256 interestUnPaid;
if (borrowAmount != 0) {
if (lastSettleTime_ != block.timestamp) {
(,interestUnPaid) = _getAllInterest();
}
uint256 balance = _underlyingBalance()
.add(interestUnPaid);
if (borrowAmount > balance) {
borrowAmount = balance;
}
}
return _nextBorrowInterestRate2(
borrowAmount,
_totalAssetSupply(interestUnPaid),
useFixedInterestModel
);
}
function _nextBorrowInterestRate2(
uint256 newBorrowAmount,
uint256 assetSupply,
bool useFixedInterestModel)
internal
view
returns (uint256 nextRate)
{
uint256 utilRate = _utilizationRate(
totalAssetBorrow.add(newBorrowAmount),
assetSupply
);
uint256 minRate;
uint256 maxRate;
uint256 thisBaseRate;
uint256 thisRateMultiplier;
if (useFixedInterestModel) {
if (utilRate < 80 ether) {
// target 80% utilization when loan is fixed-rate and utilization is under 80%
utilRate = 80 ether;
}
//keccak256("iToken_FixedInterestBaseRate")
//keccak256("iToken_FixedInterestRateMultiplier")
assembly {
thisBaseRate := sload(0x185a40c6b6d3f849f72c71ea950323d21149c27a9d90f7dc5e5ea2d332edcf7f)
thisRateMultiplier := sload(0x9ff54bc0049f5eab56ca7cd14591be3f7ed6355b856d01e3770305c74a004ea2)
}
} else if (utilRate < 50 ether) {
thisBaseRate = _getLowUtilBaseRate();
//keccak256("iToken_LowUtilRateMultiplier")
assembly {
thisRateMultiplier := sload(0x2b4858b1bc9e2d14afab03340ce5f6c81b703c86a0c570653ae586534e095fb1)
}
} else {
thisBaseRate = baseRate;
thisRateMultiplier = rateMultiplier;
}
if (utilRate > 90 ether) {
// scale rate proportionally up to 100%
utilRate = utilRate.sub(90 ether);
if (utilRate > 10 ether)
utilRate = 10 ether;
maxRate = thisRateMultiplier
.add(thisBaseRate)
.mul(90)
.div(100);
nextRate = utilRate
.mul(SafeMath.sub(100 ether, maxRate))
.div(10 ether)
.add(maxRate);
} else {
nextRate = utilRate
.mul(thisRateMultiplier)
.div(10**20)
.add(thisBaseRate);
minRate = thisBaseRate;
maxRate = thisRateMultiplier
.add(thisBaseRate);
if (nextRate < minRate)
nextRate = minRate;
else if (nextRate > maxRate)
nextRate = maxRate;
}
}
function _getAllInterest()
internal
view
returns (
uint256 interestOwedPerDay,
uint256 interestUnPaid)
{
(,,interestOwedPerDay,interestUnPaid) = IBZx(bZxContract).getLenderInterestForOracle(
address(this),
bZxOracle, // (leave as original value)
address(_getDai()) // same as interestTokenAddress
);
interestUnPaid = interestUnPaid
.mul(spreadMultiplier)
.div(10**20);
}
function _getBorrowAmountAndRate(
bytes32 loanOrderHash,
uint256 depositAmount,
bool useFixedInterestModel)
internal
view
returns (uint256 borrowAmount, uint256 interestRate)
{
LoanData memory loanData = loanOrderData[loanOrderHash];
require(loanData.initialMarginAmount != 0, "33");
interestRate = _nextBorrowInterestRate2(
depositAmount
.mul(10**20)
.div(loanData.initialMarginAmount),
totalAssetSupply(),
useFixedInterestModel
);
// assumes that loan, collateral, and interest token are the same
borrowAmount = depositAmount
.mul(10**40)
.div(_adjustValue(
interestRate,
loanData.maxDurationUnixTimestampSec,
loanData.initialMarginAmount))
.div(loanData.initialMarginAmount);
}
function _totalAssetSupply(
uint256 interestUnPaid)
internal
view
returns (uint256 assetSupply)
{
if (totalSupply_ != 0) {
uint256 assetsBalance = burntTokenReserved; // temporary holder when flash lending
if (assetsBalance == 0) {
assetsBalance = _underlyingBalance()
.add(totalAssetBorrow);
}
return assetsBalance
.add(interestUnPaid);
}
}
function _getLowUtilBaseRate()
internal
view
returns (uint256 lowUtilBaseRate)
{
//keccak256("iToken_LowUtilBaseRate")
assembly {
lowUtilBaseRate := sload(0x3d82e958c891799f357c1316ae5543412952ae5c423336f8929ed7458039c995)
}
}
function _adjustValue(
uint256 interestRate,
uint256 maxDuration,
uint256 marginAmount)
internal
pure
returns (uint256)
{
return maxDuration != 0 ?
interestRate
.mul(10**20)
.div(31536000) // 86400 * 365
.mul(maxDuration)
.div(marginAmount)
.add(10**20) :
10**20;
}
function _utilizationRate(
uint256 assetBorrow,
uint256 assetSupply)
internal
pure
returns (uint256)
{
if (assetBorrow != 0 && assetSupply != 0) {
// U = total_borrow / total_supply
return assetBorrow
.mul(10**20)
.div(assetSupply);
}
}
function _getChai()
internal
pure
returns (iChai)
{
return chai;
}
function _getPot()
internal
pure
returns (iPot)
{
return pot;
}
function _getDai()
internal
pure
returns (ERC20)
{
return dai;
}
function rmul(
uint256 x,
uint256 y)
internal
pure
returns (uint256 z)
{
require(y == 0 || (z = x * y) / y == x);
z /= RAY;
}
function rpow(
uint256 x,
uint256 n,
uint256 base)
public
pure
returns (uint256 z)
{
assembly {
switch x case 0 {switch n case 0 {z := base} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := base } default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, base)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, base)
}
}
}
}
}
/* Oracle-Only functions */
// called only by BZxOracle when a loan is partially or fully closed
function closeLoanNotifier(
BZxObjects.LoanOrder memory loanOrder,
BZxObjects.LoanPosition memory loanPosition,
address loanCloser,
uint256 closeAmount,
bool isLiquidation)
public
onlyOracle
returns (bool)
{
_settleInterest();
_dsrDeposit();
LoanData memory loanData = loanOrderData[loanOrder.loanOrderHash];
if (loanData.loanOrderHash == loanOrder.loanOrderHash) {
totalAssetBorrow = totalAssetBorrow > closeAmount ?
totalAssetBorrow.sub(closeAmount) : 0;
emit Repay(
loanOrder.loanOrderHash, // loanOrderHash
loanPosition.trader, // borrower
loanCloser, // closer
closeAmount, // amount
isLiquidation // isLiquidation
);
if (closeAmount == 0)
return true;
// checkpoint supply since the base protocol borrow stats have changed
checkpointSupply = _totalAssetSupply(0);
return true;
} else {
return false;
}
}
/* Owner-Only functions */
function updateSettings(
address settingsTarget,
bytes memory callData)
public
{
if (msg.sender != owner) {
address _lowerAdmin;
address _lowerAdminContract;
//keccak256("iToken_LowerAdminAddress")
//keccak256("iToken_LowerAdminContract")
assembly {
_lowerAdmin := sload(0x7ad06df6a0af6bd602d90db766e0d5f253b45187c3717a0f9026ea8b10ff0d4b)
_lowerAdminContract := sload(0x34b31cff1dbd8374124bd4505521fc29cab0f9554a5386ba7d784a4e611c7e31)
}
require(msg.sender == _lowerAdmin && settingsTarget == _lowerAdminContract);
}
address currentTarget = target_;
target_ = settingsTarget;
(bool result,) = address(this).call(callData);
uint256 size;
uint256 ptr;
assembly {
size := returndatasize
ptr := mload(0x40)
returndatacopy(ptr, 0, size)
if eq(result, 0) { revert(ptr, size) }
}
target_ = currentTarget;
assembly {
return(ptr, size)
}
}
}
| the average interest that borrowers are currently paying for open loans | function avgBorrowInterestRate()
public
view
returns (uint256)
{
uint256 assetBorrow = totalAssetBorrow;
if (assetBorrow != 0) {
return _protocolInterestRate(assetBorrow)
.mul(checkpointSupply)
.div(totalAssetSupply());
return _getLowUtilBaseRate();
}
}
| 5,462,748 |
./partial_match/4/0xEF6FF362d35973C63daB80484F4712aabd80a91E/sources/GovTreasurer.sol | DEPOSIT | FARMING ASSETS (TOKENS) | RE-ENTRANCY DEFENSE | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accGDAOPerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accGDAOPerShare).div(1e12);
safeGDAOTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(devaddr), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
| 8,769,177 |
./full_match/4/0x18Be7dB1a84062eE9e7361A686495d7b3Fc97a26/sources/contracts/TradingContract.sol | The withdraw function is a function with which investors can withdraw their funds in a tradingContract. Theapplicable fees will be calculated in this function. Check for equity in pairedToken, and swap the investor fraction into ETH. Check for equity in baseToken, and swap the investor fraction into ETH.In case of positive revenue, calculate and transfer the developer and the platform fee.Notice that revenue will be calculated in ETH (invested amount in ETH subtracted by final equity in ETH)Update all fractions of all the investors. | function withdraw() public updateSubtractedSupply(msg.sender) {
require(fractions[msg.sender] > 0);
uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this));
uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees);
uint256 _swappedAmountPaired;
uint256 _swappedAmountBase;
if (_pairedTokenBalance > 0) {
uint256 _amountInPaired = fractions[msg.sender].mul(_pairedTokenBalance).div(UNITY);
_swappedAmountPaired = swapForETH(pairedTokenAddress, WETHAddress, _amountInPaired, getAmountOutMin(pairedTokenAddress, WETHAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (_baseTokenBalance > 0) {
uint256 _amountInBase = fractions[msg.sender].mul(_baseTokenBalance).div(UNITY);
_swappedAmountBase = swapForETH(baseTokenAddress, WETHAddress, _amountInBase, getAmountOutMin(baseTokenAddress, WETHAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (invested[msg.sender] < _equity) {
uint256 _revenue = _equity.sub(invested[msg.sender]);
uint256 _developerFee = _revenue.mul(devFee).div(UNITY);
uint256 _platformFee = _revenue.mul(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getPlatformFee()).div(UNITY);
totalAccumulatedDevFees = totalAccumulatedDevFees.add(_developerFee);
developerAddress.transfer(_developerFee);
payable(owner()).transfer(_platformFee);
_equity = _equity.sub(_developerFee).sub(_platformFee);
}
if (totalSupply != 0) {
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(oldTotalSupply).div(totalSupply);
}
}
fractions[msg.sender] = 0;
totalInvested = totalInvested.sub(invested[msg.sender]);
invested[msg.sender] = 0;
investedInUSD[msg.sender] = 0;
wallets[msg.sender]= false;
ITradingContractDeployer(deployer).tradingCounterSub(msg.sender);
emit Withdrawn(msg.sender, _equity);
}
| 658,677 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract Triptcip is
ERC721Burnable,
ERC721URIStorage,
Ownable,
Pausable,
ReentrancyGuard
{
using Counters for Counters.Counter;
using ECDSA for bytes32;
using SafeERC20 for IERC20;
event CreateToken(
uint256 timestamp,
address indexed owner,
uint256 indexed tokenId,
uint256 royalty,
string metadataId
);
event AuctionCreate(
uint256 timestamp,
address indexed owner,
uint256 indexed tokenId,
uint256 reservePrice
);
event AuctionPlaceBid(
uint256 timestamp,
address indexed owner,
uint256 indexed tokenId,
uint256 amount,
uint256 deadline
);
event AcceptOffer(
uint256 timestamp,
address bidder,
uint256 tokenId,
uint256 amount,
uint256 deadline
);
event PlaceBidRefund(
uint256 timestamp,
uint256 indexed tokenId,
address indexed bidder,
uint256 amount
);
event AuctionClaim(
uint256 timestamp,
address indexed owner,
uint256 indexed tokenId
);
struct Bid {
address bidder;
uint256 amount;
uint256 timestamp;
}
struct WinningBid {
uint256 amount;
address bidder;
}
struct Auction {
address seller;
uint256 reservePrice;
bool isClaimed;
uint256 deadline;
WinningBid winningBid;
Bid[] bids;
}
address private serviceWallet;
uint private constant BP_DIVISOR = 10000;
uint256 private serviceFee;
mapping(uint256 => uint256) private royaltyFees;
address public wethAddress;
uint256 private deadlineInSeconds;
uint256 public timeBuffer;
uint256 public minBidIncrease;
mapping(uint256 => Auction) public auctions;
mapping(uint256 => address) private tokenMinters;
Counters.Counter private tokenIdCounter;
string private baseTokenURI;
uint private minReservePrice = 0.1 ether;
mapping(address => mapping(uint256 => bool)) private nonces;
modifier onlyAuctionedToken(uint256 _tokenId) {
require(auctions[_tokenId].seller != address(0), "Does not exist");
_;
}
modifier onlyTokenOwner(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender, "Not the owner");
_;
}
modifier onlyEOA() {
require(msg.sender == tx.origin, "No contract calls");
_;
}
constructor(
address _serviceWallet,
uint256 _serviceFee,
uint256 _deadlineInSeconds,
string memory _baseTokenURI,
address _wethAddress
) ERC721("Triptcip", "TRIP") onlyEOA {
require(_serviceWallet != address(0), "_serviceWallet required");
require(_serviceFee > 0, "_serviceFee invalid");
require(_serviceFee < BP_DIVISOR, "_serviceFee invalid");
baseTokenURI = _baseTokenURI;
serviceWallet = _serviceWallet;
serviceFee = _serviceFee;
wethAddress = _wethAddress;
deadlineInSeconds = _deadlineInSeconds;
timeBuffer = 15 * 60; // Extend 15 minutes after every bid is made in last 15 minutes
minBidIncrease = 1000; // Minimum 10% every bid
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
function updateBaseTokenURI(string memory _baseURI) public onlyOwner {
baseTokenURI = _baseURI;
}
function updateTimeBuffer(uint256 _timeBuffer) public onlyOwner {
timeBuffer = _timeBuffer;
}
function updateMinBidIncreasePercentage(uint256 _minBidIncrease)
public
onlyOwner
{
minBidIncrease = _minBidIncrease;
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function getMinter(uint256 _tokenId) external view returns (address) {
return tokenMinters[_tokenId];
}
function getRoyalty(uint256 _tokenId) external view returns (uint256) {
return royaltyFees[_tokenId];
}
function updateDeadline(uint256 _deadlineInSeconds) public onlyOwner {
deadlineInSeconds = _deadlineInSeconds;
}
function getDeadlineInSeconds() public view onlyOwner returns (uint256) {
return deadlineInSeconds;
}
function updateServiceFee(uint256 _serviceFee) public onlyOwner {
require(_serviceFee > 0, "_serviceFee invalid");
require(_serviceFee < BP_DIVISOR, "_serviceFee invalid");
serviceFee = _serviceFee;
}
function getServiceFee() public view onlyOwner returns (uint256) {
return serviceFee;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function setMinReservePrice(uint256 _minReservePrice) external onlyOwner {
minReservePrice = _minReservePrice;
}
function createToken(uint256 _royalty, string calldata metadataId)
public
onlyEOA
returns (uint256)
{
require(_royalty < BP_DIVISOR - serviceFee, "_royalty invalid");
tokenIdCounter.increment();
uint256 newTokenId = tokenIdCounter.current();
_mint(msg.sender, newTokenId);
royaltyFees[newTokenId] = _royalty;
tokenMinters[newTokenId] = msg.sender;
emit CreateToken(
block.timestamp,
msg.sender,
newTokenId,
_royalty,
metadataId
);
return newTokenId;
}
function acceptOffer(
uint256 _tokenId,
uint256 _amount,
uint256 _deadline,
uint256 _nonce,
address _signer,
bytes memory _signature
) external onlyTokenOwner(_tokenId) {
require(auctions[_tokenId].seller == address(0), "In auction");
require(block.timestamp <= _deadline, "Offer expired");
require(!nonces[_signer][_nonce], "Invalid nonce");
require(
keccak256(
abi.encodePacked(_tokenId, _amount, _deadline, _nonce, address(this))
).toEthSignedMessageHash().recover(_signature) == _signer,
"Invalid signer"
);
uint256 serviceFeeAmount = (_amount * serviceFee) / BP_DIVISOR;
uint256 royaltyFeeAmount = (_amount * royaltyFees[_tokenId]) / BP_DIVISOR;
// TODO: do we need to add "success" checks?
// Pay the platform
IERC20(wethAddress).safeTransferFrom(
_signer,
serviceWallet,
serviceFeeAmount
);
// Pay the royalties
IERC20(wethAddress).safeTransferFrom(
_signer,
tokenMinters[_tokenId],
royaltyFeeAmount
);
// Pay the seller
IERC20(wethAddress).safeTransferFrom(
_signer,
msg.sender,
(_amount - serviceFeeAmount - royaltyFeeAmount)
);
// Transfer the token
_safeTransfer(msg.sender, _signer, _tokenId, "");
nonces[_signer][_nonce] = true;
emit AcceptOffer(block.timestamp, msg.sender, _tokenId, _amount, _deadline);
}
function invalidateNonce(uint256 _nonce) external {
nonces[msg.sender][_nonce] = true;
}
function auctionCreate(uint256 _tokenId, uint256 _reservePrice)
public
onlyTokenOwner(_tokenId)
onlyEOA
{
Auction storage auction = auctions[_tokenId];
require(
_reservePrice >= minReservePrice,
"`_reservePrice` must be at least minReservePrice"
);
require(auction.seller == address(0), "Duplicate");
auction.seller = msg.sender;
auction.reservePrice = _reservePrice;
emit AuctionCreate(block.timestamp, msg.sender, _tokenId, _reservePrice);
}
function updateReservePrice(uint256 _tokenId, uint256 _reservePrice)
public
onlyAuctionedToken(_tokenId)
onlyTokenOwner(_tokenId)
{
require(
_reservePrice >= minReservePrice,
"`_reservePrice` must be at least minReservePrice"
);
Auction storage auction = auctions[_tokenId];
require(auction.bids.length == 0, "Bidding already started");
auction.reservePrice = _reservePrice;
}
function auctionPlaceBid(uint256 _tokenId)
public
payable
onlyAuctionedToken(_tokenId)
onlyEOA
nonReentrant
{
Auction storage auction = auctions[_tokenId];
uint current = auction.winningBid.amount;
require(msg.value >= auction.reservePrice, "Bid too low");
require(
msg.value >= current + 0.1 ether ||
msg.value >= (current * (BP_DIVISOR + minBidIncrease)) / BP_DIVISOR,
"Bid too low"
);
uint256 deadline = auction.deadline;
require(block.timestamp < deadline || deadline == 0, "Auction is over");
// This means, it's a fresh auction, no one has bid on it yet.
if (deadline == 0) {
// Start the deadline, it's set to NOW + 24 hours in seconds (86400)
// Deadline should prob be a contract level constant, or configurable here
auction.deadline = block.timestamp + deadlineInSeconds;
} else if (deadline - block.timestamp <= timeBuffer) {
// If within 15 minutes of expiry, extend with another 15 minutes
auction.deadline = deadline + timeBuffer;
}
uint256 previousBids = auction.bids.length;
auction.bids.push(Bid(msg.sender, msg.value, block.timestamp));
auction.winningBid.amount = msg.value;
auction.winningBid.bidder = msg.sender;
// Refund previous bid
if (previousBids > 0) {
address previousBidder = auction.bids[previousBids - 1].bidder;
uint256 previousBid = auction.bids[previousBids - 1].amount;
previousBidder.call{value: previousBid}("");
emit PlaceBidRefund(
block.timestamp,
_tokenId,
previousBidder,
previousBid
);
}
emit AuctionPlaceBid(
block.timestamp,
msg.sender,
_tokenId,
msg.value,
auction.deadline
);
}
function auctionClaim(uint256 _tokenId)
public
onlyAuctionedToken(_tokenId)
nonReentrant
{
Auction storage auction = auctions[_tokenId];
require(block.timestamp > auction.deadline, "Auction not over");
auction.isClaimed = true;
uint256 salePrice = auction.winningBid.amount;
uint256 serviceFeeAmount = (salePrice * serviceFee) / BP_DIVISOR;
uint256 royaltyFeeAmount = (salePrice * royaltyFees[_tokenId]) / BP_DIVISOR;
// Pay the platform
serviceWallet.call{value: serviceFeeAmount}("");
// Pay the royalty
tokenMinters[_tokenId].call{value: royaltyFeeAmount}("");
// Pay the seller
auction.seller.call{value: salePrice - serviceFeeAmount - royaltyFeeAmount}(
""
);
address winner = auction.winningBid.bidder;
delete auctions[_tokenId];
_safeTransfer(ownerOf(_tokenId), winner, _tokenId, "");
emit AuctionClaim(block.timestamp, msg.sender, _tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721) {
super._beforeTokenTransfer(from, to, tokenId);
require(auctions[tokenId].seller == address(0), "In auction");
require(!paused(), "Paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @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 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'
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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return recover(hash, r, vs);
} else {
revert("ECDSA: invalid signature length");
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^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;
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");
(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");
(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");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| Pay the platform Pay the royalty Pay the seller | function auctionClaim(uint256 _tokenId)
public
onlyAuctionedToken(_tokenId)
nonReentrant
{
Auction storage auction = auctions[_tokenId];
require(block.timestamp > auction.deadline, "Auction not over");
auction.isClaimed = true;
uint256 salePrice = auction.winningBid.amount;
uint256 serviceFeeAmount = (salePrice * serviceFee) / BP_DIVISOR;
uint256 royaltyFeeAmount = (salePrice * royaltyFees[_tokenId]) / BP_DIVISOR;
""
);
address winner = auction.winningBid.bidder;
delete auctions[_tokenId];
_safeTransfer(ownerOf(_tokenId), winner, _tokenId, "");
emit AuctionClaim(block.timestamp, msg.sender, _tokenId);
}
| 5,995,712 |
./partial_match/1/0xAdFc8C296eb7CEc677C2DdecE28007A3D4e465a1/sources/contracts/apestaking/base/CApe.sol | Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements - `to` cannot be the zero address./ | function _mint(address account, uint256 sharesAmount)
internal
virtual
whenNotPaused
{
require(account != address(0), "mint to the zero address");
_totalShare = _totalShare.add(sharesAmount);
shares[account] = shares[account].add(sharesAmount);
}
| 2,890,280 |
./partial_match/97/0x3601Fe48B06b0BEC400226Ea95543463566F78f7/sources/EchipsPresale.sol | return the number of token units a buyer gets per wei./ | function rate() public view returns (uint256) {
return _rate;
}
| 11,349,612 |
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/test/ExternalCollateralLiquidator.sol | @inheritdoc ICollateralLiquidator/ | function name() external pure returns (string memory) {
return "ExternalCollateralLiquidator";
}
| 9,659,466 |
./full_match/1/0x422d9dfD61Ba0a7d5F95f12636b0Fd90B34F9d55/sources/browser/CoreVaults.sol | Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. | function safeCoreTransfer(address _to, uint256 _amount) internal {
uint256 coreBal = core.balanceOf(address(this));
if (_amount > coreBal) {
core.transfer(_to, coreBal);
coreBalance = core.balanceOf(address(this));
core.transfer(_to, _amount);
coreBalance = core.balanceOf(address(this));
}
} else {
transferDevFee();
}
| 3,077,178 |
/*
Copyright 2019 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
pragma experimental "ABIEncoderV2";
import { ISocialTradingManager } from "set-protocol-strategies/contracts/managers/interfaces/ISocialTradingManager.sol";
import { SocialTradingLibrary } from "set-protocol-strategies/contracts/managers/lib/SocialTradingLibrary.sol";
import { IPerformanceFeeCalculator } from "set-protocol-contracts/contracts/core/interfaces/IPerformanceFeeCalculator.sol";
import { IRebalancingSetTokenV2 } from "set-protocol-contracts/contracts/core/interfaces/IRebalancingSetTokenV2.sol";
import { IRebalancingSetTokenV3 } from "set-protocol-contracts/contracts/core/interfaces/IRebalancingSetTokenV3.sol";
import { PerformanceFeeLibrary } from "set-protocol-contracts/contracts/core/fee-calculators/lib/PerformanceFeeLibrary.sol";
import { RebalancingSetTokenViewer } from "./RebalancingSetTokenViewer.sol";
/**
* @title TradingPoolViewer
* @author Set Protocol
*
* Interfaces for fetching multiple TradingPool state in a single read. Includes state
* specific to managing pool as well as underlying RebalancingSetTokenV2 state.
*/
contract TradingPoolViewer is RebalancingSetTokenViewer {
/*
* Fetches TradingPool details. Compatible with:
* - RebalancingSetTokenV2/V3
* - Any Fee Calculator
* - Any Liquidator
*
* @param _rebalancingSetToken RebalancingSetToken contract instance
* @return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken
* @return uint256[] Starting current set, start time, minimum bid, and remaining current sets
*/
function fetchNewTradingPoolDetails(
IRebalancingSetTokenV2 _tradingPool
)
external
view
returns (SocialTradingLibrary.PoolInfo memory, RebalancingSetCreateInfo memory, CollateralSetInfo memory)
{
RebalancingSetCreateInfo memory tradingPoolInfo = getRebalancingSetInfo(
address(_tradingPool)
);
SocialTradingLibrary.PoolInfo memory poolInfo = ISocialTradingManager(tradingPoolInfo.manager).pools(
address(_tradingPool)
);
CollateralSetInfo memory collateralSetInfo = getCollateralSetInfo(
tradingPoolInfo.currentSet
);
return (poolInfo, tradingPoolInfo, collateralSetInfo);
}
/*
* Fetches TradingPoolV2 details. Compatible with:
* - RebalancingSetTokenV2/V3
* - PerformanceFeeCalculator
* - Any Liquidator
*
* @param _rebalancingSetToken RebalancingSetToken contract instance
* @return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken
* @return uint256[] Starting current set, start time, minimum bid, and remaining current sets
*/
function fetchNewTradingPoolV2Details(
IRebalancingSetTokenV3 _tradingPool
)
external
view
returns (
SocialTradingLibrary.PoolInfo memory,
RebalancingSetCreateInfo memory,
PerformanceFeeLibrary.FeeState memory,
CollateralSetInfo memory,
address
)
{
(
RebalancingSetCreateInfo memory tradingPoolInfo,
PerformanceFeeLibrary.FeeState memory performanceFeeInfo,
CollateralSetInfo memory collateralSetInfo,
address performanceFeeCalculatorAddress
) = fetchNewRebalancingSetDetails(_tradingPool);
SocialTradingLibrary.PoolInfo memory poolInfo = ISocialTradingManager(tradingPoolInfo.manager).pools(
address(_tradingPool)
);
return (poolInfo, tradingPoolInfo, performanceFeeInfo, collateralSetInfo, performanceFeeCalculatorAddress);
}
/*
* Fetches all TradingPool state associated with a new rebalance auction. Compatible with:
* - RebalancingSetTokenV2/V3
* - Any Fee Calculator
* - Any liquidator (will omit additional TWAPLiquidator state)
*
* @param _rebalancingSetToken RebalancingSetToken contract instance
* @return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken
* @return uint256[] Starting current set, start time, minimum bid, and remaining current sets
*/
function fetchTradingPoolRebalanceDetails(
IRebalancingSetTokenV2 _tradingPool
)
external
view
returns (SocialTradingLibrary.PoolInfo memory, RebalancingSetRebalanceInfo memory, CollateralSetInfo memory)
{
(
RebalancingSetRebalanceInfo memory tradingPoolInfo,
CollateralSetInfo memory collateralSetInfo
) = fetchRBSetRebalanceDetails(_tradingPool);
address manager = _tradingPool.manager();
SocialTradingLibrary.PoolInfo memory poolInfo = ISocialTradingManager(manager).pools(
address(_tradingPool)
);
return (poolInfo, tradingPoolInfo, collateralSetInfo);
}
/*
* Fetches all TradingPool state associated with a new TWAP rebalance auction. Compatible with:
* - RebalancingSetTokenV2/V3
* - Any Fee Calculator
* - TWAP Liquidator
*
* @param _rebalancingSetToken RebalancingSetToken contract instance
* @return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken
* @return uint256[] Starting current set, start time, minimum bid, and remaining current sets
*/
function fetchTradingPoolTWAPRebalanceDetails(
IRebalancingSetTokenV2 _tradingPool
)
external
view
returns (SocialTradingLibrary.PoolInfo memory, TWAPRebalanceInfo memory, CollateralSetInfo memory)
{
(
TWAPRebalanceInfo memory tradingPoolInfo,
CollateralSetInfo memory collateralSetInfo
) = fetchRBSetTWAPRebalanceDetails(_tradingPool);
address manager = _tradingPool.manager();
SocialTradingLibrary.PoolInfo memory poolInfo = ISocialTradingManager(manager).pools(
address(_tradingPool)
);
return (poolInfo, tradingPoolInfo, collateralSetInfo);
}
function batchFetchTradingPoolOperator(
IRebalancingSetTokenV2[] calldata _tradingPools
)
external
view
returns (address[] memory)
{
// Cache length of addresses to fetch owner for
uint256 _poolCount = _tradingPools.length;
// Instantiate output array in memory
address[] memory operators = new address[](_poolCount);
for (uint256 i = 0; i < _poolCount; i++) {
IRebalancingSetTokenV2 tradingPool = _tradingPools[i];
operators[i] = ISocialTradingManager(tradingPool.manager()).pools(
address(tradingPool)
).trader;
}
return operators;
}
function batchFetchTradingPoolEntryFees(
IRebalancingSetTokenV2[] calldata _tradingPools
)
external
view
returns (uint256[] memory)
{
// Cache length of addresses to fetch entryFees for
uint256 _poolCount = _tradingPools.length;
// Instantiate output array in memory
uint256[] memory entryFees = new uint256[](_poolCount);
for (uint256 i = 0; i < _poolCount; i++) {
entryFees[i] = _tradingPools[i].entryFee();
}
return entryFees;
}
function batchFetchTradingPoolRebalanceFees(
IRebalancingSetTokenV2[] calldata _tradingPools
)
external
view
returns (uint256[] memory)
{
// Cache length of addresses to fetch rebalanceFees for
uint256 _poolCount = _tradingPools.length;
// Instantiate output array in memory
uint256[] memory rebalanceFees = new uint256[](_poolCount);
for (uint256 i = 0; i < _poolCount; i++) {
rebalanceFees[i] = _tradingPools[i].rebalanceFee();
}
return rebalanceFees;
}
function batchFetchTradingPoolAccumulation(
IRebalancingSetTokenV3[] calldata _tradingPools
)
external
view
returns (uint256[] memory, uint256[] memory)
{
// Cache length of addresses to fetch rebalanceFees for
uint256 _poolCount = _tradingPools.length;
// Instantiate streaming fees output array in memory
uint256[] memory streamingFees = new uint256[](_poolCount);
// Instantiate profit fees output array in memory
uint256[] memory profitFees = new uint256[](_poolCount);
for (uint256 i = 0; i < _poolCount; i++) {
address rebalanceFeeCalculatorAddress = address(_tradingPools[i].rebalanceFeeCalculator());
(
streamingFees[i],
profitFees[i]
) = IPerformanceFeeCalculator(rebalanceFeeCalculatorAddress).getCalculatedFees(
address(_tradingPools[i])
);
}
return (streamingFees, profitFees);
}
function batchFetchTradingPoolFeeState(
IRebalancingSetTokenV3[] calldata _tradingPools
)
external
view
returns (PerformanceFeeLibrary.FeeState[] memory)
{
// Cache length of addresses to fetch rebalanceFees for
uint256 _poolCount = _tradingPools.length;
// Instantiate output array in memory
PerformanceFeeLibrary.FeeState[] memory feeStates = new PerformanceFeeLibrary.FeeState[](_poolCount);
for (uint256 i = 0; i < _poolCount; i++) {
feeStates[i] = getPerformanceFeeState(
address(_tradingPools[i])
);
}
return feeStates;
}
}
| Fetches all TradingPool state associated with a new TWAP rebalance auction. Compatible with: - RebalancingSetTokenV2/V3 - Any Fee Calculator - TWAP Liquidator _rebalancingSetToken RebalancingSetToken contract instance return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken return uint256[] Starting current set, start time, minimum bid, and remaining current sets/ | function fetchTradingPoolTWAPRebalanceDetails(
IRebalancingSetTokenV2 _tradingPool
)
external
view
returns (SocialTradingLibrary.PoolInfo memory, TWAPRebalanceInfo memory, CollateralSetInfo memory)
{
(
TWAPRebalanceInfo memory tradingPoolInfo,
CollateralSetInfo memory collateralSetInfo
) = fetchRBSetTWAPRebalanceDetails(_tradingPool);
address manager = _tradingPool.manager();
SocialTradingLibrary.PoolInfo memory poolInfo = ISocialTradingManager(manager).pools(
address(_tradingPool)
);
return (poolInfo, tradingPoolInfo, collateralSetInfo);
}
| 5,456,666 |
pragma solidity ^0.4.24;
/**
* This utility library was forked from https://github.com/o0ragman0o/LibCLL
*/
library LinkedListLib {
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct LinkedList {
mapping (uint256 => mapping (bool => uint256)) list;
uint256 length;
uint256 index;
}
/**
* @dev returns true if the list exists
* @param self stored linked list from contract
*/
function listExists(LinkedList storage self)
internal
view returns (bool) {
return self.length > 0;
}
/**
* @dev returns true if the node exists
* @param self stored linked list from contract
* @param _node a node to search for
*/
function nodeExists(LinkedList storage self, uint256 _node)
internal
view returns (bool) {
if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {
if (self.list[HEAD][NEXT] == _node) {
return true;
} else {
return false;
}
} else {
return true;
}
}
/**
* @dev Returns the number of elements in the list
* @param self stored linked list from contract
*/
function sizeOf(LinkedList storage self)
internal
view
returns (uint256 numElements) {
return self.length;
}
/**
* @dev Returns the links of a node as a tuple
* @param self stored linked list from contract
* @param _node id of the node to get
*/
function getNode(LinkedList storage self, uint256 _node)
public
view
returns (bool, uint256, uint256) {
if (!nodeExists(self,_node)) {
return (false, 0, 0);
} else {
return (true, self.list[_node][PREV], self.list[_node][NEXT]);
}
}
/**
* @dev Returns the link of a node `_node` in direction `_direction`.
* @param self stored linked list from contract
* @param _node id of the node to step from
* @param _direction direction to step in
*/
function getAdjacent(LinkedList storage self, uint256 _node, bool _direction)
public
view
returns (bool, uint256) {
if (!nodeExists(self,_node)) {
return (false,0);
} else {
return (true,self.list[_node][_direction]);
}
}
/**
* @dev Can be used before `insert` to build an ordered list
* @param self stored linked list from contract
* @param _node an existing node to search from, e.g. HEAD.
* @param _value value to seek
* @param _direction direction to seek in
* @return next first node beyond '_node' in direction `_direction`
*/
function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction)
public
view
returns (uint256) {
if (sizeOf(self) == 0) {
return 0;
}
require((_node == 0) || nodeExists(self,_node));
bool exists;
uint256 next;
(exists,next) = getAdjacent(self, _node, _direction);
while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction];
return next;
}
/**
* @dev Creates a bidirectional link between two nodes on direction `_direction`
* @param self stored linked list from contract
* @param _node first node for linking
* @param _link node to link to in the _direction
*/
function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction)
private {
self.list[_link][!_direction] = _node;
self.list[_node][_direction] = _link;
}
/**
* @dev Insert node `_new` beside existing node `_node` in direction `_direction`.
* @param self stored linked list from contract
* @param _node existing node
* @param _new new node to insert
* @param _direction direction to insert node in
*/
function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction)
internal
returns (bool) {
if(!nodeExists(self,_new) && nodeExists(self,_node)) {
uint256 c = self.list[_node][_direction];
createLink(self, _node, _new, _direction);
createLink(self, _new, c, _direction);
self.length++;
return true;
} else {
return false;
}
}
/**
* @dev removes an entry from the linked list
* @param self stored linked list from contract
* @param _node node to remove from the list
*/
function remove(LinkedList storage self, uint256 _node)
internal
returns (uint256) {
if ((_node == NULL) || (!nodeExists(self,_node))) {
return 0;
}
createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT);
delete self.list[_node][PREV];
delete self.list[_node][NEXT];
self.length--;
return _node;
}
/**
* @dev pushes an enrty to the head of the linked list
* @param self stored linked list from contract
* @param _index The node Id
* @param _direction push to the head (NEXT) or tail (PREV)
*/
function add(LinkedList storage self, uint256 _index, bool _direction)
internal
returns (uint256) {
insert(self, HEAD, _index, _direction);
return self.index;
}
/**
* @dev pushes an enrty to the head of the linked list
* @param self stored linked list from contract
* @param _direction push to the head (NEXT) or tail (PREV)
*/
function push(LinkedList storage self, bool _direction)
internal
returns (uint256) {
self.index++;
insert(self, HEAD, self.index, _direction);
return self.index;
}
/**
* @dev pops the first entry from the linked list
* @param self stored linked list from contract
* @param _direction pop from the head (NEXT) or the tail (PREV)
*/
function pop(LinkedList storage self, bool _direction)
internal
returns (uint256) {
bool exists;
uint256 adj;
(exists,adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
}
/**
* Owned contract
*/
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed from, address indexed to);
/**
* Constructor
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Only the owner of contract
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev transfer the ownership to other
* - Only the owner can operate
*/
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
/**
* @dev Accept the ownership from last owner
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract TripioToken {
string public name;
string public symbol;
uint8 public decimals;
function transfer(address _to, uint256 _value) public returns (bool);
function balanceOf(address who) public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
}
contract TripioRoomNightData is Owned {
using LinkedListLib for LinkedListLib.LinkedList;
// Interface signature of erc165.
// bytes4(keccak256("supportsInterface(bytes4)"))
bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7;
// Interface signature of erc721 metadata.
// bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("tokenURI(uint256)"));
bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd;
// Interface signature of erc721.
// bytes4(keccak256("balanceOf(address)")) ^
// bytes4(keccak256("ownerOf(uint256)")) ^
// bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")) ^
// bytes4(keccak256("safeTransferFrom(address,address,uint256)")) ^
// bytes4(keccak256("transferFrom(address,address,uint256)")) ^
// bytes4(keccak256("approve(address,uint256)")) ^
// bytes4(keccak256("setApprovalForAll(address,bool)")) ^
// bytes4(keccak256("getApproved(uint256)")) ^
// bytes4(keccak256("isApprovedForAll(address,address)"));
bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5;
// Base URI of token asset
string public tokenBaseURI;
// Authorized contracts
struct AuthorizedContract {
string name;
address acontract;
}
mapping (address=>uint256) public authorizedContractIds;
mapping (uint256 => AuthorizedContract) public authorizedContracts;
LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0);
// Rate plan prices
struct Price {
uint16 inventory; // Rate plan inventory
bool init; // Whether the price is initied
mapping (uint256 => uint256) tokens;
}
// Vendor hotel RPs
struct RatePlan {
string name; // Name of rate plan.
uint256 timestamp; // Create timestamp.
bytes32 ipfs; // The address of rate plan detail on IPFS.
Price basePrice; // The base price of rate plan
mapping (uint256 => Price) prices; // date -> Price
}
// Vendors
struct Vendor {
string name; // Name of vendor.
address vendor; // Address of vendor.
uint256 timestamp; // Create timestamp.
bool valid; // Whether the vendor is valid(default is true)
LinkedListLib.LinkedList ratePlanList;
mapping (uint256=>RatePlan) ratePlans;
}
mapping (address => uint256) public vendorIds;
mapping (uint256 => Vendor) vendors;
LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0);
// Supported digital currencies
mapping (uint256 => address) public tokenIndexToAddress;
LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0);
// RoomNight tokens
struct RoomNight {
uint256 vendorId;
uint256 rpid;
uint256 token; // The digital currency token
uint256 price; // The digital currency price
uint256 timestamp; // Create timestamp.
uint256 date; // The checkin date
bytes32 ipfs; // The address of rate plan detail on IPFS.
}
RoomNight[] public roomnights;
// rnid -> owner
mapping (uint256 => address) public roomNightIndexToOwner;
// Owner Account
mapping (address => LinkedListLib.LinkedList) public roomNightOwners;
// Vendor Account
mapping (address => LinkedListLib.LinkedList) public roomNightVendors;
// The authorized address for each TRN
mapping (uint256 => address) public roomNightApprovals;
// The authorized operators for each address
mapping (address => mapping (address => bool)) public operatorApprovals;
// The applications of room night redund
mapping (address => mapping (uint256 => bool)) public refundApplications;
// The signature of `onERC721Received(address,uint256,bytes)`
// bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba;
/**
* This emits when contract authorized
*/
event ContractAuthorized(address _contract);
/**
* This emits when contract deauthorized
*/
event ContractDeauthorized(address _contract);
/**
* The contract is valid
*/
modifier authorizedContractValid(address _contract) {
require(authorizedContractIds[_contract] > 0);
_;
}
/**
* The contract is valid
*/
modifier authorizedContractIdValid(uint256 _cid) {
require(authorizedContractList.nodeExists(_cid));
_;
}
/**
* Only the owner or authorized contract is valid
*/
modifier onlyOwnerOrAuthorizedContract {
require(msg.sender == owner || authorizedContractIds[msg.sender] > 0);
_;
}
/**
* Constructor
*/
constructor() public {
// Add one invalid RoomNight, avoid subscript 0
roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0));
}
/**
* @dev Returns the node list and next node as a tuple
* @param self stored linked list from contract
* @param _node the begin id of the node to get
* @param _limit the total nodes of one page
* @param _direction direction to step in
*/
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
}else {
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
}else {
return (temp, ei);
}
}
}
/**
* @dev Authorize `_contract` to execute this contract's funs
* @param _contract The contract address
* @param _name The contract name
*/
function authorizeContract(address _contract, string _name)
public
onlyOwner
returns(bool) {
uint256 codeSize;
assembly { codeSize := extcodesize(_contract) }
require(codeSize != 0);
// Not exists
require(authorizedContractIds[_contract] == 0);
// Add
uint256 id = authorizedContractList.push(false);
authorizedContractIds[_contract] = id;
authorizedContracts[id] = AuthorizedContract(_name, _contract);
// Event
emit ContractAuthorized(_contract);
return true;
}
/**
* @dev Deauthorized `_contract` by address
* @param _contract The contract address
*/
function deauthorizeContract(address _contract)
public
onlyOwner
authorizedContractValid(_contract)
returns(bool) {
uint256 id = authorizedContractIds[_contract];
authorizedContractList.remove(id);
authorizedContractIds[_contract] = 0;
delete authorizedContracts[id];
// Event
emit ContractDeauthorized(_contract);
return true;
}
/**
* @dev Deauthorized `_contract` by contract id
* @param _cid The contract id
*/
function deauthorizeContractById(uint256 _cid)
public
onlyOwner
authorizedContractIdValid(_cid)
returns(bool) {
address acontract = authorizedContracts[_cid].acontract;
authorizedContractList.remove(_cid);
authorizedContractIds[acontract] = 0;
delete authorizedContracts[_cid];
// Event
emit ContractDeauthorized(acontract);
return true;
}
/**
* @dev Get authorize contract ids by page
* @param _from The begin authorize contract id
* @param _limit How many authorize contract ids one page
* @return The authorize contract ids and the next authorize contract id as tuple, the next page not exists when next eq 0
*/
function getAuthorizeContractIds(uint256 _from, uint256 _limit)
external
view
returns(uint256[], uint256){
return getNodes(authorizedContractList, _from, _limit, true);
}
/**
* @dev Get authorize contract by id
* @param _cid Then authorize contract id
* @return The authorize contract info(_name, _acontract)
*/
function getAuthorizeContract(uint256 _cid)
external
view
returns(string _name, address _acontract) {
AuthorizedContract memory acontract = authorizedContracts[_cid];
_name = acontract.name;
_acontract = acontract.acontract;
}
/*************************************** GET ***************************************/
/**
* @dev Get the rate plan by `_vendorId` and `_rpid`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
*/
function getRatePlan(uint256 _vendorId, uint256 _rpid)
public
view
returns (string _name, uint256 _timestamp, bytes32 _ipfs) {
_name = vendors[_vendorId].ratePlans[_rpid].name;
_timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp;
_ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs;
}
/**
* @dev Get the rate plan price by `_vendorId`, `_rpid`, `_date` and `_tokenId`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @return The price info(inventory, init, price)
*/
function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId)
public
view
returns(uint16 _inventory, bool _init, uint256 _price) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
_price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId];
if(!_init) {
// Get the base price
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
_price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
_init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
}
/**
* @dev Get the rate plan prices by `_vendorId`, `_rpid`, `_dates` and `_tokenId`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _dates The dates desc ([20180723,20180724,20180725])
* @param _tokenId The digital token id
* @return The price info(inventory, init, price)
*/
function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId)
public
view
returns(uint16[] _inventories, uint256[] _prices) {
uint16[] memory inventories = new uint16[](_dates.length);
uint256[] memory prices = new uint256[](_dates.length);
uint256 date;
for(uint256 i = 0; i < _dates.length; i++) {
date = _dates[i];
uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory;
bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init;
uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId];
if(!init) {
// Get the base price
inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
inventories[i] = inventory;
prices[i] = price;
}
return (inventories, prices);
}
/**
* @dev Get the inventory by by `_vendorId`, `_rpid` and `_date`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @return The inventory info(inventory, init)
*/
function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date)
public
view
returns(uint16 _inventory, bool _init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
if(!_init) {
// Get the base price
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
}
}
/**
* @dev Whether the rate plan is exist
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @return If the rate plan of the vendor is exist returns true otherwise return false
*/
function ratePlanIsExist(uint256 _vendorId, uint256 _rpid)
public
view
returns (bool) {
return vendors[_vendorId].ratePlanList.nodeExists(_rpid);
}
/**
* @dev Get orders of owner by page
* @param _owner The owner address
* @param _from The begin id of the node to get
* @param _limit The total nodes of one page
* @param _direction Direction to step in
* @return The order ids and the next id
*/
function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightOwners[_owner], _from, _limit, _direction);
}
/**
* @dev Get orders of vendor by page
* @param _owner The vendor address
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The order ids and the next id
*/
function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightVendors[_owner], _from, _limit, _direction);
}
/**
* @dev Get the token count of somebody
* @param _owner The owner of token
* @return The token count of `_owner`
*/
function balanceOf(address _owner)
public
view
returns(uint256) {
return roomNightOwners[_owner].length;
}
/**
* @dev Get rate plan ids of `_vendorId`
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The rate plan ids and the next id
*/
function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction);
}
/**
* @dev Get token ids
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The token ids and the next id
*/
function getTokens(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(tokenList, _from, _limit, _direction);
}
/**
* @dev Get token Info
* @param _tokenId The token id
* @return The token info(symbol, name, decimals)
*/
function getToken(uint256 _tokenId)
public
view
returns(string _symbol, string _name, uint8 _decimals, address _token) {
_token = tokenIndexToAddress[_tokenId];
TripioToken tripio = TripioToken(_token);
_symbol = tripio.symbol();
_name = tripio.name();
_decimals = tripio.decimals();
}
/**
* @dev Get vendor ids
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The vendor ids and the next id
*/
function getVendors(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendorList, _from, _limit, _direction);
}
/**
* @dev Get the vendor infomation by vendorId
* @param _vendorId The vendor id
* @return The vendor infomation(name, vendor, timestamp, valid)
*/
function getVendor(uint256 _vendorId)
public
view
returns(string _name, address _vendor,uint256 _timestamp, bool _valid) {
_name = vendors[_vendorId].name;
_vendor = vendors[_vendorId].vendor;
_timestamp = vendors[_vendorId].timestamp;
_valid = vendors[_vendorId].valid;
}
/*************************************** SET ***************************************/
/**
* @dev Update base uri of token metadata
* @param _tokenBaseURI The base uri
*/
function updateTokenBaseURI(string _tokenBaseURI)
public
onlyOwnerOrAuthorizedContract {
tokenBaseURI = _tokenBaseURI;
}
/**
* @dev Push order to user's order list
* @param _owner The buyer address
* @param _rnid The room night order id
* @param _direction direction to step in
*/
function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightOwners[_owner].listExists()) {
roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0);
}
roomNightOwners[_owner].add(_rnid, _direction);
}
/**
* @dev Remove order from owner's order list
* @param _owner The owner address
* @param _rnid The room night order id
*/
function removeOrderOfOwner(address _owner, uint _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightOwners[_owner].nodeExists(_rnid));
roomNightOwners[_owner].remove(_rnid);
}
/**
* @dev Push order to the vendor's order list
* @param _vendor The vendor address
* @param _rnid The room night order id
* @param _direction direction to step in
*/
function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightVendors[_vendor].listExists()) {
roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0);
}
roomNightVendors[_vendor].add(_rnid, _direction);
}
/**
* @dev Remove order from vendor's order list
* @param _vendor The vendor address
* @param _rnid The room night order id
*/
function removeOrderOfVendor(address _vendor, uint256 _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightVendors[_vendor].nodeExists(_rnid));
roomNightVendors[_vendor].remove(_rnid);
}
/**
* @dev Transfer token to somebody
* @param _tokenId The token id
* @param _to The target owner of the token
*/
function transferTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightIndexToOwner[_tokenId] = _to;
roomNightApprovals[_tokenId] = address(0);
}
/**
* @dev Approve `_to` to operate the `_tokenId`
* @param _tokenId The token id
* @param _to Somebody to be approved
*/
function approveTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightApprovals[_tokenId] = _to;
}
/**
* @dev Approve `_operator` to operate all the Token of `_to`
* @param _operator The operator to be approved
* @param _to The owner of tokens to be operate
* @param _approved Approved or not
*/
function approveOperatorTo(address _operator, address _to, bool _approved)
public
onlyOwnerOrAuthorizedContract {
operatorApprovals[_to][_operator] = _approved;
}
/**
* @dev Update base price of rate plan
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _tokenId The digital token id
* @param _price The price to be updated
*/
function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.init = true;
vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price;
}
/**
* @dev Update base inventory of rate plan
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _inventory The inventory to be updated
*/
function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory;
}
/**
* @dev Update price by `_vendorId`, `_rpid`, `_date`, `_tokenId` and `_price`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @param _price The price to be updated
*/
function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
/**
* @dev Update inventory by `_vendorId`, `_rpid`, `_date`, `_inventory`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The inventory to be updated
*/
function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
}
}
/**
* @dev Reduce inventories
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The amount to be reduced
*/
function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 a = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){
a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory;
}
}
/**
* @dev Add inventories
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The amount to be add
*/
function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 c = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c;
}
}
/**
* @dev Update inventory and price by `_vendorId`, `_rpid`, `_date`, `_tokenId`, `_price` and `_inventory`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @param _price The price to be updated
* @param _inventory The inventory to be updated
*/
function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
/**
* @dev Push rate plan to `_vendorId`'s rate plan list
* @param _vendorId The vendor id
* @param _name The name of rate plan
* @param _ipfs The rate plan IPFS address
* @param _direction direction to step in
*/
function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false));
uint256 id = vendors[_vendorId].ratePlanList.push(_direction);
vendors[_vendorId].ratePlans[id] = rp;
return id;
}
/**
* @dev Remove rate plan of `_vendorId` by `_rpid`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
*/
function removeRatePlan(uint256 _vendorId, uint256 _rpid)
public
onlyOwnerOrAuthorizedContract {
delete vendors[_vendorId].ratePlans[_rpid];
vendors[_vendorId].ratePlanList.remove(_rpid);
}
/**
* @dev Update `_rpid` of `_vendorId` by `_name` and `_ipfs`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _name The rate plan name
* @param _ipfs The rate plan IPFS address
*/
function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs;
vendors[_vendorId].ratePlans[_rpid].name = _name;
}
/**
* @dev Push token contract to the token list
* @param _direction direction to step in
*/
function pushToken(address _contract, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = tokenList.push(_direction);
tokenIndexToAddress[id] = _contract;
return id;
}
/**
* @dev Remove token by `_tokenId`
* @param _tokenId The digital token id
*/
function removeToken(uint256 _tokenId)
public
onlyOwnerOrAuthorizedContract {
delete tokenIndexToAddress[_tokenId];
tokenList.remove(_tokenId);
}
/**
* @dev Generate room night token
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _token The token id
* @param _price The token price
* @param _ipfs The rate plan IPFS address
*/
function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs));
// Give the token to `_customer`
uint256 rnid = uint256(roomnights.length - 1);
return rnid;
}
/**
* @dev Update refund applications
* @param _buyer The room night token holder
* @param _rnid The room night token id
* @param _isRefund Is redund or not
*/
function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund)
public
onlyOwnerOrAuthorizedContract {
refundApplications[_buyer][_rnid] = _isRefund;
}
/**
* @dev Push vendor info to the vendor list
* @param _name The name of vendor
* @param _vendor The vendor address
* @param _direction direction to step in
*/
function pushVendor(string _name, address _vendor, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = vendorList.push(_direction);
vendorIds[_vendor] = id;
vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0));
return id;
}
/**
* @dev Remove vendor from vendor list
* @param _vendorId The vendor id
*/
function removeVendor(uint256 _vendorId)
public
onlyOwnerOrAuthorizedContract {
vendorList.remove(_vendorId);
address vendor = vendors[_vendorId].vendor;
vendorIds[vendor] = 0;
delete vendors[_vendorId];
}
/**
* @dev Make vendor valid or invalid
* @param _vendorId The vendor id
* @param _valid The vendor is valid or not
*/
function updateVendorValid(uint256 _vendorId, bool _valid)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].valid = _valid;
}
/**
* @dev Modify vendor's name
* @param _vendorId The vendor id
* @param _name Then vendor name
*/
function updateVendorName(uint256 _vendorId, string _name)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].name = _name;
}
} | Update inventory and price by `_vendorId`, `_rpid`, `_date`, `_tokenId`, `_price` and `_inventory` _vendorId The vendor id _rpid The rate plan id _date The date desc (20180723) _tokenId The digital token id _price The price to be updated _inventory The inventory to be updated/ | function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
| 1,978,841 |
./partial_match/1/0x89D660f454314021ceb19dEfBe000675a21B6C2a/sources/SabaiVesting.sol | Release vested amount of tokens. vestingScheduleId the vesting schedule identifier amount the amount to release/ | function release(
bytes32 vestingScheduleId,
uint256 amount
)
public
nonReentrant
onlyIfVestingScheduleNotRevoked(vestingScheduleId){
VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId];
bool isBeneficiary = msg.sender == vestingSchedule.beneficiary;
require(
isBeneficiary,
"TokenVesting: only beneficiary can release vested tokens"
);
uint256 vestedAmount = _computeReleasableAmount(vestingSchedule);
require(vestedAmount >= amount, "TokenVesting: cannot release tokens, not enough vested tokens");
vestingSchedule.released = vestingSchedule.released.add(amount);
vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(amount);
_token.safeTransfer(vestingSchedule.beneficiary, amount);
}
| 16,175,810 |
./full_match/1/0xa3fe7EdAB15b257227Ebc296C6d8C15Bc6772b01/sources/contracts/JBToken.sol | / Can't approve for a wrong project. | function approve(
uint256 _projectId,
address _spender,
uint256 _amount
) external override {
if (projectId != 0 && _projectId != projectId) revert BAD_PROJECT();
approve(_spender, _amount);
}
Transfer tokens to an account.
@param _projectId The ID of the project to which the token belongs. This is ignored.
@param _to The destination address.
@param _amount The amount of the transfer, as a fixed point number with 18 decimals.
| 17,119,699 |
pragma solidity ^0.4.20;
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
/**
* Owned contract
*/
contract Owned {
address[] public pools;
address public owner;
function Owned() {
owner = msg.sender;
pools.push(msg.sender);
}
modifier onlyPool {
require(isPool(msg.sender));
_;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/// add new pool address to pools
function addPool(address newPool) onlyOwner {
assert (newPool != 0);
if (isPool(newPool)) throw;
pools.push(newPool);
}
/// remove a address from pools
function removePool(address pool) onlyOwner{
assert (pool != 0);
if (!isPool(pool)) throw;
for (uint i=0; i<pools.length - 1; i++) {
if (pools[i] == pool) {
pools[i] = pools[pools.length - 1];
break;
}
}
pools.length -= 1;
}
function isPool(address pool) internal returns (bool ok){
for (uint i=0; i<pools.length; i++) {
if (pools[i] == pool)
return true;
}
return false;
}
function transferOwnership(address newOwner) onlyOwner public {
removePool(owner);
addPool(newOwner);
owner = newOwner;
}
}
/**
* BP crowdsale contract
*/
contract BPToken is SafeMath, Owned, ERC20 {
string public constant name = "Backpack Token";
string public constant symbol = "BP";
uint256 public constant decimals = 18;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function BPToken() {
totalSupply = 2000000000 * 10 ** uint256(decimals);
balances[msg.sender] = totalSupply;
}
/// asset pool map
mapping (address => address) addressPool;
/// address base amount
mapping (address => uint256) addressAmount;
/// per month seconds
uint perMonthSecond = 2592000;
/// calc the balance that the user shuold hold
function shouldHadBalance(address who) constant returns (uint256){
if (isPool(who)) return 0;
address apAddress = getAssetPoolAddress(who);
uint256 baseAmount = getBaseAmount(who);
/// Does not belong to AssetPool contract
if( (apAddress == address(0)) || (baseAmount == 0) ) return 0;
/// Instantiate ap contract
AssetPool ap = AssetPool(apAddress);
uint startLockTime = ap.getStartLockTime();
uint stopLockTime = ap.getStopLockTime();
if (block.timestamp > stopLockTime) {
return 0;
}
if (ap.getBaseLockPercent() == 0) {
return 0;
}
// base lock amount
uint256 baseLockAmount = safeDiv(safeMul(baseAmount, ap.getBaseLockPercent()),100);
if (block.timestamp < startLockTime) {
return baseLockAmount;
}
/// will not linear release
if (ap.getLinearRelease() == 0) {
if (block.timestamp < stopLockTime) {
return baseLockAmount;
} else {
return 0;
}
}
/// will linear release
/// now timestamp before start lock time
if (block.timestamp < startLockTime + perMonthSecond) {
return baseLockAmount;
}
// total lock months
uint lockMonth = safeDiv(safeSub(stopLockTime,startLockTime),perMonthSecond);
if (lockMonth <= 0) {
if (block.timestamp >= stopLockTime) {
return 0;
} else {
return baseLockAmount;
}
}
// unlock amount of every month
uint256 monthUnlockAmount = safeDiv(baseLockAmount,lockMonth);
// current timestamp passed month
uint hadPassMonth = safeDiv(safeSub(block.timestamp,startLockTime),perMonthSecond);
return safeSub(baseLockAmount,safeMul(hadPassMonth,monthUnlockAmount));
}
function getAssetPoolAddress(address who) internal returns(address){
return addressPool[who];
}
function getBaseAmount(address who) internal returns(uint256){
return addressAmount[who];
}
function getBalance() constant returns(uint){
return balances[msg.sender];
}
function setPoolAndAmount(address who, uint256 amount) onlyPool returns (bool) {
assert(balances[msg.sender] >= amount);
if (owner == who) {
return true;
}
address apAddress = getAssetPoolAddress(who);
uint256 baseAmount = getBaseAmount(who);
assert((apAddress == msg.sender) || (baseAmount == 0));
addressPool[who] = msg.sender;
addressAmount[who] += amount;
return true;
}
/// get balance of the special address
function balanceOf(address who) constant returns (uint) {
return balances[who];
}
/// @notice Transfer `value` BP tokens from sender's account
/// `msg.sender` to provided account address `to`.
/// @notice This function is disabled during the funding.
/// @dev Required state: Success
/// @param to The address of the recipient
/// @param value The number of BPs to transfer
/// @return Whether the transfer was successful or not
function transfer(address to, uint256 value) returns (bool) {
if (safeSub(balances[msg.sender],value) < shouldHadBalance(msg.sender)) throw;
uint256 senderBalance = balances[msg.sender];
if (senderBalance >= value && value > 0) {
senderBalance = safeSub(senderBalance, value);
balances[msg.sender] = senderBalance;
balances[to] = safeAdd(balances[to], value);
Transfer(msg.sender, to, value);
return true;
} else {
throw;
}
}
/// @notice Transfer `value` BP tokens from sender 'from'
/// to provided account address `to`.
/// @notice This function is disabled during the funding.
/// @dev Required state: Success
/// @param from The address of the sender
/// @param to The address of the recipient
/// @param value The number of BPs to transfer
/// @return Whether the transfer was successful or not
function transferFrom(address from, address to, uint256 value) returns (bool) {
// Abort if not in Success state.
// protect against wrapping uints
if (balances[from] >= value &&
allowed[from][msg.sender] >= value &&
safeAdd(balances[to], value) > balances[to])
{
balances[to] = safeAdd(balances[to], value);
balances[from] = safeSub(balances[from], value);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], value);
Transfer(from, to, value);
return true;
} else {
throw;
}
}
/// @notice `msg.sender` approves `spender` to spend `value` tokens
/// @param spender The address of the account able to transfer the tokens
/// @param value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address spender, uint256 value) returns (bool) {
if (safeSub(balances[msg.sender],value) < shouldHadBalance(msg.sender)) throw;
// Abort if not in Success state.
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
return true;
}
/// @param owner The address of the account owning tokens
/// @param spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address owner, address spender) constant returns (uint) {
uint allow = allowed[owner][spender];
return allow;
}
}
contract ownedPool {
address public owner;
function ownedPool() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
/**
* Asset pool contract
*/
contract AssetPool is ownedPool {
uint baseLockPercent;
uint startLockTime;
uint stopLockTime;
uint linearRelease;
address public bpTokenAddress;
BPToken bp;
function AssetPool(address _bpTokenAddress, uint _baseLockPercent, uint _startLockTime, uint _stopLockTime, uint _linearRelease) {
assert(_stopLockTime > _startLockTime);
baseLockPercent = _baseLockPercent;
startLockTime = _startLockTime;
stopLockTime = _stopLockTime;
linearRelease = _linearRelease;
bpTokenAddress = _bpTokenAddress;
bp = BPToken(bpTokenAddress);
owner = msg.sender;
}
/// set role value
function setRule(uint _baseLockPercent, uint _startLockTime, uint _stopLockTime, uint _linearRelease) onlyOwner {
assert(_stopLockTime > _startLockTime);
baseLockPercent = _baseLockPercent;
startLockTime = _startLockTime;
stopLockTime = _stopLockTime;
linearRelease = _linearRelease;
}
/// set bp token contract address
// function setBpToken(address _bpTokenAddress) onlyOwner {
// bpTokenAddress = _bpTokenAddress;
// bp = BPToken(bpTokenAddress);
// }
/// assign BP token to another address
function assign(address to, uint256 amount) onlyOwner returns (bool) {
if (bp.setPoolAndAmount(to,amount)) {
if (bp.transfer(to,amount)) {
return true;
}
}
return false;
}
/// get the balance of current asset pool
function getPoolBalance() constant returns (uint) {
return bp.getBalance();
}
function getStartLockTime() constant returns (uint) {
return startLockTime;
}
function getStopLockTime() constant returns (uint) {
return stopLockTime;
}
function getBaseLockPercent() constant returns (uint) {
return baseLockPercent;
}
function getLinearRelease() constant returns (uint) {
return linearRelease;
}
} | remove a address from pools | function removePool(address pool) onlyOwner{
assert (pool != 0);
if (!isPool(pool)) throw;
for (uint i=0; i<pools.length - 1; i++) {
if (pools[i] == pool) {
pools[i] = pools[pools.length - 1];
break;
}
}
pools.length -= 1;
}
| 7,648,199 |
Subsets and Splits